text,length,is_long_context,metric_val,label_metric "== Step-by-step Cloud Foundry migration === Preview https://docs.google.com/presentation/d/e/2PACX-1vSsEHn8cJfz8oWIwwUhdULt7nZzz3bBLK7OqM8UInkZ0LbQBCpPdhMoxsYGPe_90h9OvCu7dFlAimMJ/pub?start=false&loop=false&delayms=3000[Click here] to check out the slides by https://twitter.com/ciberkleid[Cora Iberkleid] where she migrates a setup of applications to be compliant with Spring Cloud Pipelines. === Introduction This tutorial covers refactoring applications to comply with, and take advantage of, Spring Cloud Pipelines. We will use a simple 3-tier application as an example: image::{cf-migration-root-docs}/use_case_logical.png[title=""Use Case - Logical View""] At the end of this tutorial, it will be possible to instantly create a Concourse pipeline for each app and run successfully through a full lifecycle, from source code commit to production deployment, following the lifecycle stages for testing and deployment recommended by Spring Cloud Pipelines. The app code bases will be improved with organized test coverage, a contract-based API, and a versioned database schema, enabling Spring Cloud Pipelines to carry out stubbed testing and to ensure backward compatibility for API and database schema changes. === Sample application - initial state The sample application is implemented using Spring Boot apps for the UI and service tiers, and MySQL for the database. The apps are built using Maven and pushed manually to Cloud Foundry. They leverage the three Pivotal Spring Cloud Services: Config Server, Service Discovery, and Circuit Breaker Dashboard. Rabbit is used to propagate Config Server refresh triggers. The source code for the two Spring Boot apps is stored on GitHub, as is the backing repo for Config Server. image::{cf-migration-root-docs}/use_case_implementation.png[title=""Use Case - Implementation""] === Sample application - end state Through this tutorial, we will be adding Concourse and JFrog Bintray to manage the application lifecycle. We will also be refactoring the application to comply with Spring Cloud Pipelines requirements and recommendations, including adding/organizing tests and introducing database versioning using Flyway and API contracts using Spring Cloud Contract. === Tutorial - toolset * *GitHub* - sample app source code and config repositories, a sample stubrunner app repository, and the Spring Cloud Pipelines code base - https://github.com/ciberkleid/greeting-ui[greeting-ui] - https://github.com/ciberkleid/fortune-service[fortune-service] - https://github.com/ciberkleid/app-config[app-config] - https://github.com/spring-cloud-samples/cloudfoundry-stub-runner-boot[cloudfoundry-stub-runner-boot] - https://github.com/spring-cloud/spring-cloud-pipelines[spring-cloud-pipelines] * *Pivotal Web Services* - public hosted Cloud Foundry offering http://run.pivotal.io[free trial accounts] and including MySQL, Rabbit, and Pivotal Spring Cloud Services in the Marketplace * *Concourse* * *JFrog Bintray* - public hosted Maven repository offering free https://bintray.com/signup/oss[OSS accounts] * *Client Tools* - on your local machine, you will need an IDE as well as the mvn, git, cf, and fly (Concourse) CLIs === Tutorial - overview The migration steps are broken down into three stages: . *Scaffolding* - Minimal refactoring to comply with basic Spring Cloud Pipelines requirements. - At the end of this stage, each app will have a corresponding pipeline on Concourse. The pipelines will successfully build the apps, store the artifacts in Bintray, tag the GitHub repositories, and deploy the apps to Test, Stage, and Prod spaces in Cloud Foundry. . *Tests* - Add/organize tests to comply with Spring Cloud Pipelines recommendations. Incorporate flyway for database schema versioning and initial data loading. - At the end of this stage, the pipelines will trigger unit and integration tests during the Build stage, smoke tests in the Test environment, and end-to-end tests in the Stage environment. The pipelines will also ensure backward compatibility for the database, such that you can safely roll back the backend service app, even after the database schema has been updated. . *Contracts* - Incorporate Spring Cloud Contract to define the API between the UI and service apps and auto-generate tests and stubs. - At the end of this stage, the pipelines will catch breaking API changes during the Build stage and ensure backward compatibility for the API, such that you can safely roll back the backend service (producer) app, even after an API change. === Tutorial - step-by-step ==== Prep: Before you begin If you want to simply review the migration steps explained below, you can look at the various branches in the https://github.com/ciberkleid/greeting-ui[greeting-ui] and https://github.com/ciberkleid/fortune-service[fortune-service] repositories - there is a branch representing the end-state of each stage: image::{cf-migration-root-docs}/github_branches.png[title=""GitHub Branches""] If you want to use this tutorial as a hands-on lab, fork each of the following repositories: - https://github.com/ciberkleid/greeting-ui[greeting-ui] - https://github.com/ciberkleid/fortune-service[fortune-service] - https://github.com/ciberkleid/app-config[app-config] Then, create a new directory on your local machine. You may name it anything you like; we will refer to it as `$SCP_HOME` throughout this tutorial. In `$SCP_HOME`, clone your forks of `greeting-ui` and `fortune-service`, as well as the following two repositories: - https://github.com/spring-cloud-samples/cloudfoundry-stub-runner-boot[cloudfoundry-stub-runner-boot] - https://github.com/spring-cloud/spring-cloud-pipelines[spring-cloud-pipelines] Finally, create a directory called `$SCP_HOME/credentials`. Leave it empty for now. ==== Stage 1: Scaffolding In this stage, we make minimal changes to satisfy basic Spring Cloud Pipelines requirements so that the apps can run through the entire pipeline without error. We make ""scaffolding"" changes only - no code changes. The steps in this stage must be completed for both `greeting-ui` and `fortune-service`. ===== 1.1 Create GitHub branches ```bash git branch version git checkout -b sc-pipelines ``` Branch *version* is required to exist, though it can be created as an empty branch. It is used by Spring Coud Pipelines to generate a version number for each new pipeline execution. Branch *sc-pipelines* is optional and can be named anything you wish. The intention is for you to use it as a working branch for the changes suggested in this tutorial (hence we create it and also check it out). ===== 1.2 Add Maven wrapper ```bash mvn -N io.takari:maven:wrapper ``` This commands adds 4 files to a project: [source,bash] ---- . ├── mvnw ├── mvnw.cmd └── .mvn └── wrapper    ├── maven-wrapper.jar    └── maven-wrapper.properties ---- Make sure all four files are tracked by Git. For example, you can add the following to the `.gitignore` file: ``` #Exceptions !/mvnw !/mvnw.cmd !/.mvn/wrapper/maven-wrapper.jar !/.mvn/wrapper/maven-wrapper.properties ``` ===== 1.3 Create Bintray maven repo package We are using Bintray as the maven repository. Bintray requires that a package exist before any app artifacts can be uploaded. Log into the Bintray UI and create the packages as follows. You can use the `Import from GitHub` option to create these: image::{cf-migration-root-docs}/bintray_packages.png[title=""Bintray Packages""] ===== 1.4 Configure distribution management using Bintray maven repo Edit the app `pom.xml` files as follows. Make sure the Bintray URLs match the URLs of the corresponding packages created in the previous step. The values you use will be different from the example shown below. ```xml ... bintray https://api.bintray.com/maven/ciberkleid/maven-repo/fortune-service ... ${distribution.management.release.id} ${distribution.management.release.url} ``` Though not required by Spring Cloud Pipelines, it makes sense to also configure your local maven settings with the credentials to your Bintray maven repo. To do so, edit your maven settings file, usually `~/.m2/settings.xml`. If the file does not exist, create it. Note that the `id` must match the id specified in the previous step. Also, make sure to use your username and API token (not account password) instead of the sample values shown below. ```xml bintray ciberkleid my-super-secret-api-token ``` ===== 1.5 Push changes to GitHub Push the above changes to GitHub. You should be pushing the following to each of the two app repos: * 4 new maven wrapper files * a modified .gitignore file * a modified pom.xml ===== 1.6 Add Spring Cloud Pipelines credentials file In `$SCP_HOME/credentials`, make two copies of the file `$SCP_HOME/spring-cloud-pipelines/concourse/credentials-sample-cf.yml`. Rename them as `credentials-fortune-service.yml` and `credentials-greeting-ui.yml`. CAUTION: These files will contain credentials to your GitHub repo, your Bintray repo, and your Cloud Foundry foundation. Hence, we opt to put them in a separate directory. You may choose to store these files in a private git repo, but do not push them to a public repo. Edit the git properties of each credentials file. Make sure to replace the sample values shown below as appropriate. For `tools-branch`, you may opt to use a fixed release (use v1.0.0.M8 or later for Cloud Foundry). Leave other values as they are, we will update those in later steps. ```yml app-url: git@github.com:ciberkleid/fortune-service.git app-branch: sc-pipelines tools-scripts-url: https://github.com/spring-cloud/spring-cloud-pipelines.git tools-branch: master build-options: """" github-private-key: | -----BEGIN RSA PRIVATE KEY----- MIIJKQIBAAKCAgEAvwkL97vBllOSE39Wa5ppczT1cr5Blmkhadfoa1Va2/IBVyvk NJ9PqoTI+BahF2EgzweyiDSvKsstlTsG7QgiM9So8Voi2PlDOrXL6uOfCuAS/G8X ... -----END RSA PRIVATE KEY----- git-email: ciberkleid@pivotal.io git-name: Cora Iberkleid ``` Edit the maven repo properties of each credentials file. Make sure to replace the sample values shown below as appropriate. Bintray requires separate URLs for uploads and downloads. If you are using a different artifact repository, such as Artifactory or Nexus, and the repository URL is the same for uploads and downloads, then you do not need to set `repo-with-binaries-for-upload`. ```yml m2-settings-repo-id: bintray m2-settings-repo-username: ciberkleid m2-settings-repo-password: my-super-secret-api-token repo-with-binaries: https://ciberkleid:my-super-secret-api-token@dl.bintray.com/ciberkleid/maven-repo repo-with-binaries-for-upload: https://api.bintray.com/maven/ciberkleid/maven-repo/fortune-service ``` ===== 1.7 Set Concourse pipeline At this point, all of the build jobs, which run on Concourse workers, will succeed. To verify this, log in to your Concourse target and set the Concourse pipelines. Update the target name in the example below as appropriate. ```bash # Set greeting-ui pipeline fly -t myTarget set-pipeline -p greeting-ui -c ""${SCP_HOME}/spring-cloud-pipelines/concourse/pipeline.yml"" -l ""${SCP_HOME}/credentials/credentials-greeting-ui.yml"" -n # Set fortune-service pipeline fly -t myTarget set-pipeline -p fortune-service -c ""${SCP_HOME}/spring-cloud-pipelines/concourse/pipeline.yml"" -l ""${SCP_HOME}/credentials/credentials-fortune-service.yml"" -n ``` Log into the Concourse UI and unpause the pipelines. Start each. You should see that the build jobs all succeed. image::{cf-migration-root-docs}/concourse_build_success.png[title=""Build Success""] In addition, you will see a new dev/ tag in each GitHub repo, as well as the app jars uploaded into Bintray. The test, stage, and prod jobs will fail because we have not yet added scaffolding for deployment to Cloud Foundry. We will do that next. ===== 1.8 Add Cloud Foundry manifest If you are deploying to Cloud Foundry, you may already be routinely including manifest files with your apps. Our sample apps did not have manifest files, so we add them now. In the `greeting-ui` repo, create a `manifest.yml` file as follows: ```yml --- applications: - name: greeting-ui timeout: 120 services: - config-server - cloud-bus - service-registry - circuit-breaker-dashboard env: JAVA_OPTS: -Djava.security.egd=file:///dev/urandom TRUST_CERTS: api.run.pivotal.io ``` In the `fortune-service` repo, create a `manifest.yml` file as follows: ```yml --- applications: - name: fortune-service timeout: 120 services: - fortune-db - config-server - cloud-bus - service-registry - circuit-breaker-dashboard env: JAVA_OPTS: -Djava.security.egd=file:///dev/urandom TRUST_CERTS: api.run.pivotal.io ``` The `TRUST_CERTS` variable is used by the Pivotal Spring Cloud Services (Config Server, Service Registry, and Circuit Breaker Dashboard), which we are using in this example. The value specified above assumes deployment to Pivotal Web Services. Update it accordingly if you are deploying to a different Cloud Foundry foundation, or you can leave it out altogether if you are replacing the Pivotal Spring Cloud Services with alternative implementations (e.g. deploying the services as apps and exposing them as user-provided services). You may add additional values to the manifest files if you wish, for example if additional values are useful for any manual deployment you may still want to do, or desirable in your Spring Cloud Pipelines deployment. For example, an alternative manifest.yml for `fortune-service` could be as follows: ```yml --- applications: - name: fortune-service timeout: 120 instances: 3 memory: 1024M buildpack: https://github.com/cloudfoundry/java-buildpack.git random-route: true path: ./target/fortune-service-0.0.1-SNAPSHOT.jar services: - fortune-db - config-server - cloud-bus - service-registry - circuit-breaker-dashboard env: SPRING_PROFILES_ACTIVE: someProfile JAVA_OPTS: -Djava.security.egd=file:///dev/urandom TRUST_CERTS: api.run.pivotal.io ``` Note that `random-route` and `path` are ignored by Spring Cloud Pipelines. `instances` is honored in stage and prod, but overridden with a value of 1 for test. ===== 1.9 Add Spring Cloud Pipelines manifest The Cloud Foundry manifest created in the previous step includes the logical names of the services to which the apps should be bound, but it does describe how the services can be provisioned. Hence, we add a second manifest file so that Spring Cloud Pipelines can provision the services. Add a file called `sc-pipelines.yml` to each app, and include the same list of services as in the corresponding `manifest.yml`. Add the necessary details such that Spring Cloud Pipelines can construct a `cf create-service` command. NOTE: The `type: broker' parameter shown below instructs Spring Cloud Pipelines to provision a service using `cf create-service'. Other service types are also supported: cups, syslog, route, app, and stubrunner. More specifically, for `greeting-ui`, create an `sc-pipelines.yml` file with the following content: ```yml test: services: - name: config-server type: broker broker: p-config-server plan: standard params: git: uri: https://github.com/ciberkleid/app-config useExisting: true - name: cloud-bus type: broker broker: cloudamqp plan: lemur useExisting: true - name: service-registry type: broker broker: p-service-registry plan: standard useExisting: true - name: circuit-breaker-dashboard type: broker broker: p-circuit-breaker-dashboard plan: standard useExisting: true ``` The `sc-pipelines.yml` file for `fortune-service` is similar, with the addition of the `fortune-db` service: ```yml test: # list of required services services: - name: fortune-db type: broker broker: cleardb plan: spark useExisting: true - name: config-server type: broker broker: p-config-server plan: standard params: git: uri: https://github.com/ciberkleid/app-config useExisting: true - name: cloud-bus type: broker broker: cloudamqp plan: lemur useExisting: true - name: service-registry type: broker broker: p-service-registry plan: standard useExisting: true - name: circuit-breaker-dashboard type: broker broker: p-circuit-breaker-dashboard plan: standard useExisting: true ``` The values above assume deployment to Pivotal Web Services. If you are deploying to a different Cloud Foundry foundation, please update the values accordingly. Also, make sure to replace the `config-server` uri with the address of your fork of the https://github.com/ciberkleid/app-config[app-config] repo. TIP: Notice the `useExisting: true` parameter above. By default, Spring Cloud Pipelines will delete and recreate services in the `test` space. To override this behavior and re-use existing services, we set `useExisting: true`. This is helpful in cases where services may take time to provision and initialize, where there is no risk in re-using them between pipeline runs, or where it is desirable to retain the service instance from the last pipeline run (e.g. a database migration). ===== 1.10 Push changes to GitHub Push the above changes to GitHub. You should be pushing the following to each of the two app repos: * new app manifest file * new sc-pipelines manifest file ===== 1.11 Create Cloud Foundry Orgs/Spaces Spring Cloud Pipelines requires that the Cloud Foundry test, stage, and prod spaces exist before a pipeline is run. If you wish, you can use different foundations, orgs, and users for each. For simplicity, in this example, we use a single foundation (PWS), a single org, and a single user. You can name the org(s) and spaces anything you like. Each app requires its own test space. The stage and prod spaces are shared. For this example, create the following spaces: ```bash cf create-space scp-test-greeting-ui cf create-space scp-test-fortune-service cf create-space scp-stage cf create-space scp-prod ``` ===== 1.12 Create Cloud Foundry stage and prod service instances Spring Cloud Pipelines will dynamically create the services in the test spaces as per the `sc-pipelines.yml` file we created previously. Optionally, a second section can be added to the `sc-pipelines.yml` file for the stage environment, and these will be created dynamically as well. Prod services, however, must always be created manually. For this example, we will create the stage and prod services manually. Create the services listed in the app manifest files in both `scp-stage` and `scp-prod`. ===== 1.13 Update Spring Cloud Pipelines credentials file Update the `greeting-ui` and `fortune-service` credentials files with Cloud Foundry information. Replace values in the example below as appropriate for your Cloud Foundry environment. Notice that the test space name specified is a prefix, unlike the stage and prod space names, which are literals. Spring Cloud Pipelines will append the app name to the test space name, thereby matching the test space names we created manually. The stage and prod space names are not prefixes and will not be altered by Spring Cloud Pipelines. Note also the `paas-hostname-uuid`. The value will be included in each route created. This value is optional, but it is useful in shared/multi-tenant environments such as PWS, as it helps ensure routes are unique. Change it to a unique uuid of your choosing. ```yml pipeline-descriptor: sc-pipelines.yml paas-type: cf paas-hostname-uuid: cyi # test values paas-test-api-url: https://api.run.pivotal.io paas-test-username: ciberkleid@pivotal.io paas-test-password: secret paas-test-org: S1Pdemo12 paas-test-space-prefix: scp-test # stage values paas-stage-api-url: https://api.run.pivotal.io paas-stage-username: ciberkleid@pivotal.io paas-stage-password: my-super-secret-password paas-stage-org: S1Pdemo12 paas-stage-space: scp-stage # prod values paas-prod-api-url: https://api.run.pivotal.io paas-prod-username: ciberkleid@pivotal.io paas-prod-password: my-super-secret-password paas-prod-org: S1Pdemo12 paas-prod-space: scp-prod ``` ===== 1.14 Update Concourse pipeline with updated credentials files Set the Concourse pipelines again, as we did previously, to update them with the values added to the credentials files. The test, stage, and prod jobs will all now succeed. image::{cf-migration-root-docs}/concourse_test_stage_prod_success.png[title=""Test, Stage, & Prod Success""] On Cloud Foundry, you will now see the apps deployed in the test, stage, and prod spaces. The image below shows the deployment of `fortune-service` to its dedicated test space. Notice that the 5 services declared in its manifest files (`sc-pipelines.yml` for provisioning, and `manifest.yml` for binding) have also been automatically provisioned. The image also shows the deployment of the same app to the shared prod space. Notice that the instance of the previous version has been renamed as *""venerable""* and stopped. If a rollback were deemed necessary, the `prod-rollback` job in the pipeline could be triggered to remove the currently running version, remove the `prod/` tag from GitHub, and re-start the former (*""venerable""*) version. image::{cf-migration-root-docs}/cf_test_and_prod_deployed.png[title=""Cloud Foundry Test and Prod Deployment""] ===== Stage 1 Recap & next steps What have we accomplished? * By adding the basic scaffolding needed to enable Spring Cloud Pipelines to manage the lifecycle of `greeting-ui` and `fortune-service` from source code commit to production deploy, we have made it possible for the app dev teams to instantly and easily create pipelines for each app using a common, standardized template * We can count on the pipelines to: - automatically provision services in test spaces, and optionally in stage as well - dynamically clean up the test spaces between pipeline executions - upload the app artifacts to the maven repo (e.g. Bintray) - tag the git repositories with `dev/` and `prod/` * After each successful pipeline run, we are in a position to roll back to the last deployed version using the `prod-rollback` job, if necessary These accomplishments are extremely valuable, but in order to derive confidence and reliability from the pipelines, we need to incorporate testing. We do this in Stage 2 of the app migration. ==== Stage 2: Tests In this stage, we enable Spring Cloud Pipelines to execute tests so that we can increase confidence in the code being deployed. We do so by adding test profiles to the pom.xml files, and then organizing and/or adding tests in a way that corresponds to the profiles. By doing so, we are establishing standards around testing across development teams in the enterprise. We will also enable database schema versioning in this stage, thereby providing the foundation for rollback testing during schema changes. ===== 2.1 Add Maven profiles For both `greeting-ui` and `fortune-service`, add a `profiles` section to the `pom.xml` file, as shown below. Note that we are adding four profiles: * default ** For unit and integration tests. Note that this profile includes all tests except those that will explicitly be called by the smoke and e2e profiles. ** Tests matching this profile will be executed during the build-and-upload job * apicompatibility ** For ensuring backward compatibility in case of API changes. Note that this is not effective until Stage 3, when we will add contracts. However, we add this profile now to ensure the api-compatibility-check job does not execute other tests. * smoke ** For tests to be run against the app deployed in the test space. * e2e ** For tests to be run against the app deployed in the stage space. ```xml default true org.apache.maven.plugins maven-surefire-plugin **/*Tests.java **/*Test.java **/smoke/** **/e2e/** org.springframework.boot spring-boot-maven-plugin apicompatibility org.apache.maven.plugins maven-surefire-plugin **/contracttests/**/*Tests.java **/contracttests/**/*Test.java smoke org.apache.maven.plugins maven-surefire-plugin smoke/**/*Tests.java smoke/**/*Test.java e2e org.apache.maven.plugins maven-surefire-plugin e2e/**/*Tests.java e2e/**/*Test.java ``` ===== 2.2 Add/organize tests Next, we ensure that we have a matching test package structure in our apps: image::{cf-migration-root-docs}/test_package_structure.png[title=""Test Package Structure""] Note that we are creating matching packages for the default, smoke, and e2e profiles only. We will address the package for the apicompatibility profile in Stage 3. When working with your own apps, if you have existing tests, you would move the files into one of these packages now, and rename them so that they are included by the filters declared in the profiles (i.e. the file names end in `Test.java` or `Tests.java`) In the case of our sample apps, there are no tests, so we add some now as follows. *fortune-service default tests* Add your unit and integration tests so that they match the default profile as defined in the `fortune-service` `pom.xml` file. These will be executed on Concourse against the `fortune-service` application running on the Concourse worker in the `build-and-upload` job. As an example, we will add two tests, one that loads the context, and another that verifies the number of rows expected in the database: ```java package io.pivotal; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.jdbc.core.JdbcTemplate; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.*; @RunWith(SpringRunner.class) @SpringBootTest(classes = FortuneServiceApplication.class) public class FortuneServiceApplicationTests { @Test public void contextLoads() throws Exception { } @Autowired private JdbcTemplate template; @Test public void testDefaultSettings() throws Exception { assertThat(this.template.queryForObject(""SELECT COUNT(*) from FORTUNE"", Integer.class)).isEqualTo(7); } } ``` *fortune-service smoke tests* Add your smoke tests so that they match the smoke profile as defined in the `fortune-service` `pom.xml` file. These will be executed on Concourse against the `fortune-service` application deployed in the Cloud Foundry `scp-test-fortune-service` space. Two versions of these tests are executed against the app: . the current version, in the `test-smoke` job . the latest prod version, in the `test-rollback-smoke` job image::{cf-migration-root-docs}/fortune_service_smoke_tests.png[title=""fortune-service Smoke Tests""] In the test environment, we choose to verify that `fortune-service` is retrieving a fortune from `fortune-db`, and not returning its Hystrix fallback response: ```java package smoke; import org.assertj.core.api.BDDAssertions; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestTemplate; @RunWith(SpringRunner.class) @SpringBootTest(classes = SmokeTests.class, webEnvironment = SpringBootTest.WebEnvironment.NONE) @EnableAutoConfiguration public class SmokeTests { @Value(""${application.url}"") String applicationUrl; RestTemplate restTemplate = new RestTemplate(); @Test public void should_return_a_fortune() { ResponseEntity response = this.restTemplate .getForEntity(""http://"" + this.applicationUrl + ""/"", String.class); BDDAssertions.then(response.getStatusCodeValue()).isEqualTo(200); // Filter out the known Hystrix fallback response BDDAssertions.then(response.getBody()).doesNotContain(""The fortuneteller will be back soon.""); } } ``` *fortune-service e2e tests* Add your e2e tests so that they match the e2e profile as defined in the `fortune-service` `pom.xml` file. These will be executed on Concourse against the `fortune-service` application deployed in the Cloud Foundry `scp-stage` space. This space is shared, so we assume `greeting-ui` is also present. image::{cf-migration-root-docs}/fortune_service_e2e_tests.png[title=""fortune-service E2E Tests""] In the e2e environment, we choose to use a string replacement to obtain the URL for `greeting-ui`. We also choose to verify that we are hitting `fortune-db` and not receiving Hystrix fallback responses from either application: ```java package e2e; import org.assertj.core.api.BDDAssertions; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestTemplate; @RunWith(SpringRunner.class) @SpringBootTest(classes = E2eTests.class, webEnvironment = SpringBootTest.WebEnvironment.NONE) @EnableAutoConfiguration public class E2eTests { // The app is running in CF but the tests are executed from Concourse worker, // so the test will deduce the url to greeting-ui: it will assume the same host // as fortune-service, and simply replace ""fortune-service"" with ""greeting-ui"" in the url @Value(""${application.url}"") String applicationUrl; RestTemplate restTemplate = new RestTemplate(); @Test public void should_return_a_fortune() { ResponseEntity response = this.restTemplate .getForEntity(""http://"" + this.applicationUrl.replace(""fortune-service"", ""greeting-ui"") + ""/"", String.class); BDDAssertions.then(response.getStatusCodeValue()).isEqualTo(200); // Filter out the known Hystrix fallback responses from both fortune and greeting BDDAssertions.then(response.getBody()).doesNotContain(""This fortune is no good. Try another."").doesNotContain(""The fortuneteller will be back soon.""); } } ``` *greeting-ui default tests* Add your unit and integration tests so that they match the default profile as defined in the `greeting-ui` `pom.xml` file. These will be executed on Concourse against the `greeting-ui` application running on the Concourse worker in the `build-and-upload` job. As an example, we will add one test that loads the context: ```java package io.pivotal; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(classes = GreetingUIApplication.class) public class GreetingUIApplicationTests { @Test public void contextLoads() throws Exception { } } ``` *greeting-ui smoke tests* Add your smoke tests so that they match the smoke profile as defined in the `greeting-ui` `pom.xml` file. These will be executed on Concourse against the `greeting-ui` application deployed in the Cloud Foundry `scp-test-greeting-ui` space. Two versions of these tests are executed against the app: . the current version, in the `test-smoke` job . the latest prod version, in the `test-rollback-smoke` job image::{cf-migration-root-docs}/greeting_ui_smoke_tests.png[title=""greeting-ui Smoke Tests""] Since `fortune-service` is not deployed to the `scp-test-greeting-ui` space, we expect to receive the Hystrix fallback response defined in `greeting-ui`. Hence, our smoke test validates that condition: ```java package smoke; import org.assertj.core.api.BDDAssertions; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestTemplate; @RunWith(SpringRunner.class) @SpringBootTest(classes = SmokeTests.class, webEnvironment = SpringBootTest.WebEnvironment.NONE) @EnableAutoConfiguration public class SmokeTests { @Value(""${application.url}"") String applicationUrl; RestTemplate restTemplate = new RestTemplate(); @Test public void should_return_a_fallback_fortune() { ResponseEntity response = this.restTemplate .getForEntity(""http://"" + this.applicationUrl + ""/"", String.class); BDDAssertions.then(response.getStatusCodeValue()).isEqualTo(200); // Expect the hystrix fallback response BDDAssertions.then(response.getBody()).contains(""This fortune is no good. Try another.""); } } ``` *greeting-ui e2e tests* Add your e2e tests so that they match the e2e profile as defined in the `greeting-ui` `pom.xml` file. These will be executed on Concourse against the `greeting-ui` application deployed in the Cloud Foundry `scp-stage` space. This space is shared, so we assume `fortune-service` is also present. image::{cf-migration-root-docs}/greeting_ui_e2e_tests.png[title=""greeting-ui E2E Tests""] In the e2e environment, we choose to verify that we are hitting `fortune-service` and not receiving the Hystrix fallback response from `greeting-ui`: ```java package e2e; import org.assertj.core.api.BDDAssertions; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestTemplate; @RunWith(SpringRunner.class) @SpringBootTest(classes = E2eTests.class, webEnvironment = SpringBootTest.WebEnvironment.NONE) @EnableAutoConfiguration public class E2eTests { @Value(""${application.url}"") String applicationUrl; RestTemplate restTemplate = new RestTemplate(); @Test public void should_return_a_fortune() { ResponseEntity response = this.restTemplate .getForEntity(""http://"" + this.applicationUrl + ""/"", String.class); BDDAssertions.then(response.getStatusCodeValue()).isEqualTo(200); // Filter out the known Hystrix fallback response BDDAssertions.then(response.getBody()).doesNotContain(""This fortune is no good. Try another.""); } } ``` ===== 2.3 Enable database versioning At this point we will also incorporate https://flywaydb.org/[Flyway], an OSS database migration tool, to track database schema versions and handle schema changes and data loading. This change only needs to be made to `fortune-service`, since `fortune-service` owns the interaction with `fortune-db`. *Add Flyway dependency* We first add the Flyway dependency to the `fortune-service` `pom.xml`. We need not add a version as Spring Boot will take care of that for us. ```xml org.flywaydb flyway-core ``` *Create Flyway migration* Next, we create a migration directory and our initial migration file following Flyway's file naming convention: image::{cf-migration-root-docs}/fortune_service_flyway_file_name.png[title=""fortune-service Flyway File Name""] Note the filename specifies the version (`V1`), followed by two underscore characters. We place our CREATE TABLE and INSERT statements in our `src/main/resources/db/migration/V1__init.sql` file: ```sql CREATE TABLE fortune ( id BIGINT PRIMARY KEY AUTO_INCREMENT, text varchar(255) not null ); INSERT INTO fortune (text) VALUES ('Do what works.'); INSERT INTO fortune (text) VALUES ('Do the right thing.'); INSERT INTO fortune (text) VALUES ('Always be kind.'); INSERT INTO fortune (text) VALUES ('You learn from your mistakes... You will learn a lot today.'); INSERT INTO fortune (text) VALUES ('You can always find happiness at work on Friday.'); INSERT INTO fortune (text) VALUES ('You will be hungry again in one hour.'); INSERT INTO fortune (text) VALUES ('Today will be an awesome day!'); ``` *Disable JPA DDL initialization* Now that we are relying on Flyway to create and populate the schema, we need to disable JPA-based database initialization. We can set `ddl-auto` to `validate`, which will validate the schema against the application entities and throw an error in case of a mismatch, but not actually generate the schema: ```yml spring: jpa: hibernate: ddl-auto: validate ``` There are a few options for where to store the `ddl-auto` configuration, both in terms of location (in the `fortune-service` app or on the `app-config` GitHub repo) and in terms of file name. For this example, update the `application.yml` in the `fortune-service` app for local testing. Additionally, save these values in a new file called `application-flyway.yml` on your fork of https://github.com/ciberkleid/app-config[app-config]. By convention, `fortune-service` will pick up the configurations in `application-flyway.yml` if the string `flyway` is in the list of active Spring profiles. Thus, we add `flyway` to the environment variable `SPRING_PROFILES_ACTIVE` via the `fortune-service` `manifest.yml`: ```yml --- applications: - name: fortune-service timeout: 120 services: - fortune-db - config-server - cloud-bus - service-registry - circuit-breaker-dashboard env: SPRING_PROFILES_ACTIVE: flyway JAVA_OPTS: -Djava.security.egd=file:///dev/urandom TRUST_CERTS: api.run.pivotal.io ``` *Remove non-Flyway data loading* We can now remove the old code that populated the database. In our sample app, this was found in class `io.pivotal.FortuneServiceApplication`. The following shows the code we now remove: ```java @Bean CommandLineRunner loadDatabase(FortuneRepository fortuneRepo) { return args -> { // logger.debug(""loading database..""); // fortuneRepo.save(new Fortune(1L, ""Do what works."")); // fortuneRepo.save(new Fortune(2L, ""Do the right thing."")); // fortuneRepo.save(new Fortune(3L, ""Always be kind."")); // fortuneRepo.save(new Fortune(4L, ""You learn from your mistakes... You will learn a lot today."")); // fortuneRepo.save(new Fortune(5L, ""You can always find happiness at work on Friday."")); // fortuneRepo.save(new Fortune(6L, ""You will be hungry again in one hour."")); // fortuneRepo.save(new Fortune(7L, ""Today will be an awesome day!"")); logger.debug(""record count: {}"", fortuneRepo.count()); fortuneRepo.findAll().forEach(x -> logger.debug(x.toString())); }; } ``` We also no longer need the Fortune entity constructors, so we can comment these out in class `io.pivotal.fortune.Fortune` as shown below: ```java // public Fortune() { // } // // public Fortune(Long id, String text) { // super(); // this.id = id; // this.text = text; // } ``` *Flyway integration summary* With that, we have completed the setup for Flyway and our database schema is now versioned. From this point onward, Spring Boot will call `Flyway.migrate()` to perform the database migration. As long as we follow Flyway conventions for future schema changes, Flyway will take care of tracking the schema version and migrating the database for us. From a rollback perspective, Spring Cloud Pipelines includes two jobs in the `test` phase - `test-rollback-deploy` and `test-rollback-smoke` - wherein it validates that the latest prod jar works against the newly updated database. The purpose is to ensure that we can roll back the application in prod if a problem is discovered after the prod database schema has been updated, and avoid the burden of rolling back the database. Read more about https://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html#howto-use-a-higher-level-database-migration-tool[Spring Boot database initialization with Flyway] for further information, including Flyway configuration options. ===== 2.4 Push changes to GitHub For `greeting-ui`, you should be pushing the following new or modified files: * pom.xml * src/test/java/e2e/E2eTests.java * src/test/java/io/pivotal/GreetingUIApplicationTests.java * src/test/java/smoke/SmokeTests.java For `fortune-service`, you should be pushing the following new or modified files: * pom.xml * src/test/java/e2e/E2eTests.java * src/test/java/io/pivotal/FortuneServiceApplicationTests.java * src/test/java/smoke/SmokeTests.java * src/main/resources/db/migration/V1__init.sql * src/main/resources/application.yml * manifest.yml * src/main/java/io/pivotal/FortuneServiceApplication.java * src/main/java/io/pivotal/fortune/Fortune.java For `app-config`, you should be pushing the following new or modified files: * application-flyway.yml ===== 2.5 Re-run the pipelines Run through the pipelines again and view the output for the jobs that run the default, smoke, and e2e tests. You will see that the tests we added in this stage were executed. As you run through the pipelines a second time, you will see the smoke tests from the latest prod version run against the database in the `test-rollback-smoke` job. In this case there is no schema upgrade, but nonetheless the tests confirm that the latest prod version of the app can be used with the current database schema. You can see the database version information stored in the database by Flyway either by querying the database itself or by hitting the flyway endpoint on the `fortune-service` URL. Here is an example from the scp-stage environment: image::{cf-migration-root-docs}/fortune_service_flyway_schema_info.png[title=""fortune-service Flyway Schema Info""] ===== Stage 2 Recap & next steps What have we accomplished? * By integrating our applications with the testing strategy built into Spring Cloud Pipelines, we have increased the effectiveness of the pipelines, as well as our confidence in them * Established a standard approach to organizing tests that will bring consistency within and across development teams * Enabled auto-managed database versioning and backward compatibility testing that will alleviate database schema management throughout the release management lifecycle We are now positioned to add any unit, integration, smoke, and end-to-end tests to our code base and extract a very high level of reliability and confidence from our pipelines. We are also better positioned to ensure that our dev teams conform to these practices, given the structure established by Spring Cloud Pipelines and the fast feedback and visibility we gain from the pipelines as they execute the tests. However, we could benefit further by incorporating contracts to define and test the API integration points between applications. We do this in Stage 3 of the app migration. ==== Stage 3: Contracts In this stage, we introduce contract-based programming practices into our sample application. Doing so improves API management capabilities, including defining, communicating, and testing API semantics. It also enables us to catch breaking API changes (i.e. validate API backward compatibility) in the build phase. This will extend the effectiveness of the pipelines, encourage better communication and programming practices across development teams, and provide faster feedback to developers. We will integrate Spring Cloud Contract and add contracts, stubs, and a stub runner. We will also now complete and make use of the apicompatibility profile defined in Stage 2. ===== 3.1 Create a contract Let's start by creating the contract for the interaction between `greeting-ui` and `fortune-service`. The contract should describe the following expectation: * `greeting-ui` makes a `GET` request to the root URL of `fortune-service` and expects a response with status 200 and a string (""foo fortune"") in the body We codify this using groovy syntax as follows: ```groovy import org.springframework.cloud.contract.spec.Contract Contract.make { description("""""" should return a fortune string """""") request { method GET() url ""/"" } response { status 200 body ""foo fortune"" } } ``` Save this contract in the `fortune-service` code base in the following location, which is compliant with Spring Cloud Contract convention (`src/test/resources/contracts//`): image::{cf-migration-root-docs}/fortune_service_contract_file.png[title=""fortune-service Flyway Contract File""] NOTE: You can optionally enable your IDE to assist with contract syntax by adding the Spring Cloud Contract Verifier to your `pom.xml` file. It is pluggable, and includes groovy and pact by default. ```xml org.springframework.cloud spring-cloud-starter-contract-verifier test ``` ===== 3.2 Create a base class for contract tests Now that we have a codified contract, we want to enable auto-generation of contract-based tests. The auto-generation, which we will configure in the next steps, requires a base class that stubs out the service that satisfies the API call, so that we can run the test without external dependencies (e.g. the DB). The objective is to focus on testing API semantics. We create the base class in the `fortune-service` test package as follows: ```java package io.pivotal.fortune; import io.restassured.module.mockmvc.RestAssuredMockMvc; import org.junit.Before; import org.mockito.BDDMockito; public class BaseClass { @Before public void setup() { FortuneService service = BDDMockito.mock(FortuneService.class); BDDMockito.given(service.getFortune()).willReturn(""foo fortune""); RestAssuredMockMvc.standaloneSetup(new FortuneController(service)); } } ``` ===== 3.3 Enable automated contract-based testing Now that we have a contract and a base class, we can use the *Spring Cloud Contract maven plugin* to auto-generate contract tests, stubs, and a stub jar. First we add the Spring Cloud Contract version to the list of properties in the `fortune-service` `pom.xml` file, since we will reference it when we enable the Spring Cloud Contract maven plugin: ```xml ... 1.2.1.RELEASE ... ``` Next, we edit the `default` profile in the `fortune-service` `pom.xml` file as follows: * Add a plugin block for Spring Cloud Contract maven plugin * Configure it to use our base class (`io.pivotal.fortune.BaseClass`) to generate tests * Configure it to place auto-generated tests in the test package `io.pivotal.fortune.contracttests` Note that the package of the contracttests will be included by the `include` filter in the `default` profile, so these tests will be run against the app during the `build-and-upload` job. For `fortune-service`, this serves to validate that the app conforms to the contract. Here is the complete profile: ```xml default true org.apache.maven.plugins maven-surefire-plugin **/*Tests.java **/*Test.java **/smoke/** **/e2e/** org.springframework.boot spring-boot-maven-plugin org.springframework.cloud spring-cloud-contract-maven-plugin ${spring-cloud-contract.version} true io.pivotal.fortune.BaseClass io.pivotal.fortune.contracttests ``` When the app is built, the Spring Cloud Contract maven plugin will also now produce a stub and a stub jar containing the contract and stub. This stub jar will be uploaded to Bintray, along with the usual app jar. As we will see shortly, this stub jar can be used by the `greeting-ui` dev team while they wait for `fortune-service` to be completed. In other words, this gives the `greeting-ui` dev team a producer to test against that is based on a mutually agreed-upon contract without the lead time of having to wait for `fortune-service` to implement anything more than a base class, and without having to manually stub out calls to `fortune-service` based on arbitrary or static responses. TIP: Package the project locally (run `mvn package`) to observe the tests, stubs, and stub jar that the Spring Cloud Contract maven plugin generates. See the image below for reference. image::{cf-migration-root-docs}/fortune_service_generated_tests.png[title=""Generated Tests and Stubs""] ===== 3.4 Enable backward compatibility API check To enable Spring Cloud Pipelines to catch any breaking API changes during the `build-api-compatibility-check` job, we add the Spring Cloud Contract maven plugin to the `apicompatibility` profile as well. In this case, we want the plugin to generate tests based on contracts outside of the project (the ones from the latest prod version), so we configure the plugin to download the latest prod stub jar, which contains the old contract. The plugin will use the old contract and the specified base class, which in our example is the same as the one in the previous step, to generate contract tests. These tests are run against the new code to validate that it is still compatible with consumers complying with the prior contract. This ensures backward compatibility for the API. In short, we edit the apicompatibility profile in the `fortune-service` `pom.xml` file as follows: * Add a plugin block for Spring Cloud Contract maven plugin * Configure it to download the latest prod stub jar from Bintray to obtain the old contract * Configure it to use our base class (`io.pivotal.fortune.BaseClass`) to generate tests (we are using the same one as in the prior step) * Configure it to place auto-generated tests in the test package `io.pivotal.fortune.contracttests` Note that the package of the contracttests matches the `include` filter in the `apicompatibility` profile, so these tests will be run against the app during the `build-api-compatibility-check` job. For `fortune-service`, this serves to validate that the app conforms to the old contract. Here is the complete profile: ```xml apicompatibility org.apache.maven.plugins maven-surefire-plugin **/contracttests/**/*Tests.java **/contracttests/**/*Test.java org.springframework.cloud spring-cloud-contract-maven-plugin ${spring-cloud-contract.version} true ${repo.with.binaries} ${project.groupId} ${project.artifactId} stubs ${latest.production.version} / io.pivotal.fortune.BaseClass io.pivotal.fortune.contracttests ``` The values for `${repo.with.binaries}` and `${latest.production.version}` will be injected dynamically by Spring Cloud Pipelines. You can run this locally by providing these values manually as system properties in the maven command. ===== 3.5 Push changes to GitHub All changes in Stage 3 thus far are in `fortune-service`. At this point, you should be pushing the following new or modified files: * pom.xml * src/test/resources/contracts/greeting-ui/shouldReturnAFortune.groovy * src/test/java/io/pivotal/fortune/BaseClass.java ===== 3.6 Re-run the fortune-service pipeline Run through the `fortune-service` pipeline to generate stubs. The following output from the `build-and-upload` job shows the auto-generation of tests and stubs: image::{cf-migration-root-docs}/fortune_service_build_and_upload_test_and_stub_generation.png[title=""fortune-service build-and-upload Test and Stub Generation""] You will also see output in the `build-and-upload` job showing the execution of these tests against the code. Additionally, you will see the stub jar uploaded to Bintray along with the usual app jar. Finally, as you run through the pipeline a second time, you will see the contract tests from the latest prod version run against the new code in the output of the `build-api-compatibility-check` job. In this case there is no API change, but nonetheless the tests confirm that the latest prod version of the API can be used with the current code base. ===== 3.7 Enable stubs for integration tests We are in the home stretch! Let's turn our attention to `greeting-ui`. The following image compares the path of a request through `greeting-ui` in the build phase, both with and without stubs. image::{cf-migration-root-docs}/greeting_ui_build_flow.png[title=""greeting-ui Build Flow""] Without stubs, we expect the response to be the hystrix fallback response that is hard-coded in `greeting-ui`. With stubs, however, we can expect the response that was declared in the contract. In this case, the stubs are loaded into the `greeting-ui` process. This leads us to our next task: load the stubs produced by `fortune-service`. *Enable in-process stub runner* To load the stubs into the `greeting-ui` process, we must enable the Spring Cloud Contract Stub Runner dependency. This dependency will start an in-process stub runner that automatically configures Wiremock. Add the following to the `greeting-ui` `pom.xml` file: ```xml org.springframework.cloud spring-cloud-starter-contract-stub-runner test ``` *Add integration tests aligned with the contract* Next, we add integration tests to `greeting-ui` that test for the expected response declared in the contract. Add the following class to the test package in `greeting-ui`: ```java package io.pivotal.fortune; import io.pivotal.GreetingUIApplication; import org.assertj.core.api.BDDAssertions; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.contract.stubrunner.spring.AutoConfigureStubRunner; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(classes = GreetingUIApplication.class, webEnvironment = SpringBootTest.WebEnvironment.NONE, properties = {""spring.application.name=greeting-ui"", ""spring.cloud.circuit.breaker.enabled=false"", ""hystrix.stream.queue.enabled=false""}) @AutoConfigureStubRunner(ids = {""io.pivotal:fortune-service:1.0.0.M1-20180102_203542-VERSION""}, repositoryRoot = ""${REPO_WITH_BINARIES}"" //workOffline = true ) public class FortuneServiceTests { @Autowired FortuneService fortuneService; @Test public void shouldSendRequestToFortune() { // when String fortune = fortuneService.getFortune(); // then BDDAssertions.then(fortune).isEqualTo(""foo fortune""); } } ``` At this point, we can get through the build phase for `greeting-ui`, and the integration tests will be executed against the `fortune-service` stubs running in the `greeting-ui` process on the Concourse worker. TIP: Notice the configuration of `@AutoConfigureStubRunner` - you can replace the version with a `+` sign if using Artifactory or Nexus and it will automatically choose the latest available version on the maven repo. TIP: Setting `workOffline=true` (commented out but shown for informational purposes above) would make the stub runner get the stubs from the local maven repo. This is useful for local testing. Alternatively, set the `$REPO_WITH_BINARIES` environment variable to the value used in the credentials file before doing a local maven build, and the local build will download the stubs from your remote maven repo (e.g. Bintray). ===== 3.8 Enable stubs for smoke tests The following image compares the path of a request through `greeting-ui` in the test phase, both with and without stubs. Note that in the build phase, where the app process is running on the Concourse worker, we ran the stubs in the same process. In the test environment (Cloud Foundry), we will run the stubs in a separate process using a standalone stub runner application. image::{cf-migration-root-docs}/greeting_ui_test_flow.png[title=""greeting-ui Test Flow""] As in the build phase, without stubs we expect the response to be the hystrix fallback response that is hard-coded in `greeting-ui`. With stubs, however, we can expect the response that was declared in the contract. We will rely on Spring Cloud Pipelines to: * Deploy a stub runner application * Provide the stub runner application the necessary information to download the stubs * Open a port on the stub runner application for each stub We will rely on the stub runner application to: * Download the stubs from our maven repo (Bintray) * Expose each stub on a separate port * Register each stub in the Service Discovery server The following steps describe how to configure this. *Provide standalone stub runner app jar* In the Prep step for this tutorial, you cloned the https://github.com/spring-cloud-samples/cloudfoundry-stub-runner-boot[cloudfoundry-stub-runner-boot] repo to your local machine. The next step is to build this app and upload it to Bintray to make the jar available to Spring Cloud Pipelines. As mentioned in Stage 1 of this tutorial, Bintray requires that a package exist before any app artifacts can be uploaded. Log into the Bintray UI and create a package for `cloudfoundry-stub-runner-boot`. If you forked this repo, you can use the `Import from GitHub` option. Otherwise, create the package manually and choose any license (e.g. Apache 2.0). Now you are ready to build and upload this app to Bintray. The following script shows cloning, building and uploading. Edit as appropriate to match your Bintray URL, the Bintray ID in your `~/.m2/settings/xml` file, and the `cloudfoundry-stub-runner-boot` repo URL if you chose to fork it. ```bash # Edit to match your Bintray URL and M2 repo ID setting (check your ~/.m2/settings.xml file) MAVEN_REPO_URL=https://api.bintray.com/maven/ciberkleid/maven-repo/cloudfoundry-stub-runner-boot MAVEN_REPO_ID=bintray # Clone cloudfoundry-stub-runner-boot git clone https://github.com/spring-cloud-samples/cloudfoundry-stub-runner-boot.git cd cloudfoundry-stub-runner-boot # Build and upload ./mvnw clean deploy -Ddistribution.management.release.url=""${MAVEN_REPO_URL}"" -Ddistribution.management.release.id=""${MAVEN_REPO_ID}"" ``` You should now see the `cloudfoundry-stub-runner-boot` artifacts uploaded on Bintray. *Provide standalone stub runner app manifest* Next, we add a manifest file for the stub runner app for deployment to Cloud Foundry. We will place this file in the `greeting-ui` repo. The file name and location can be your choice. For this example, we will use `sc-pipelines/manifest-stubrunner.yml`: image::{cf-migration-root-docs}/greeting_ui_stubrunner_manifest.png[title=""greeting-ui Stub Runner Manifest""] We populate this `manifest-stubrunner.yml` with the content shown below so that the stub runner binds to `service-registry`. The stub runner will register the `fortune-service` stub there so that `greeting-ui` can discover it in the same way it will discover the actual `fortune-service` app endpoint in stage and prod. From the `greeting-ui` perspective, there is no difference in how it interacts with Eureka and the stub runner app in test and the way it will interact with Eureka and the `fortune-service` app in stage and prod. ```yml --- applications: - name: stubrunner timeout: 120 services: - service-registry env: JAVA_OPTS: -Djava.security.egd=file:///dev/urandom TRUST_CERTS: api.run.pivotal.io ``` *Provide stub runner jar and manifest info to the pipeline* Now that we have a jar file and manifest file for our stub runner app, we need to provide this information to our `greeting-ui` pipeline so that the pipeline downloads the jar from Bintray and deploys it to Cloud Foundry. We do this through the `greeting-ui` `sc-pipelines.yml` file. We add an entry to the list of services in the `test` section, as follows: ```yml - name: stubrunner type: stubrunner coordinates: io.pivotal:cloudfoundry-stub-runner-boot:0.0.1.M1 pathToManifest: sc-pipelines/manifest-stubrunner.yml ``` Notice that `name` matches the name of the app in `manifest-stubrunner.yml`, `coordinates` corresponds to the jar coordinates on the maven repo, and `pathToManifest` matches our chosen fie name for the stub runner app manifest. Note also the `type` is set to `stubrunner`, which Spring Cloud Pipelines will recognize as a stanalone stub runner app and treat accordingly. *Provide stub configuration for stub runner app* The final steps in the configuration of the standalone stub runner app are: * Enable the stub runner app to download the `fortune-service` stub from Bintray * Open a second port on the container to receive requests for this stub To accomplish this, we put stub and port configuration information into the properties section of the `greeting-ui` `pom.xml` file, using a property called `stubrunner.ids`. This property can accept a list of stubrunner ids, but for this tutorial, we only have one: ```xml ... io.pivotal:fortune-service:1.0.0.M1-20180102_203542-VERSION:stubs:10000 ``` Spring Cloud Pipelines will use this information in two ways: . It will provide this information to the stub runner app via the app's environment variables - Spring Cloud Pipelines will aslo provide the `$REPO_WITH_BINARIES` as an env var for the stub runner app - The stub runner app will use this information to download the stub from Bintray and expose it on the specified port . It will open the additional port specified on the stub runner app and map a new route to it - The format for each route will be `----.` - In our example, this would be `stubrunner-cyi-test-greeting-ui-10000.cfapps.io` Since we bound our stub runner app to `service-registry` (Eureka), the stub runner app will register the stub URL under the application name `FORTUNE-SERVICE` on Eureka: image::{cf-migration-root-docs}/greeting_ui_stub_runner_eureka_registration.png[title=""greeting-ui Stub Runner Eureka Registration""] This completes the process of configuring the standalone stub runner application. NOTE: The port configuration may be automated by Spring Cloud Pipelines in the future, such that it will not be necessary to include the port in the `stubrunner.ids`, but for the moment, we are required to specify the port each stub should use. *Edit smoke tests to align with the contract* Finally, we edit our smoke tests for `greeting-ui` to ensure the response does *not* contain the hystrix fallback, since we are now expecting a response from the stub. ```java package smoke; import org.assertj.core.api.BDDAssertions; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestTemplate; @RunWith(SpringRunner.class) @SpringBootTest(classes = SmokeTests.class, webEnvironment = SpringBootTest.WebEnvironment.NONE) @EnableAutoConfiguration public class SmokeTests { @Value(""${application.url}"") String applicationUrl; RestTemplate restTemplate = new RestTemplate(); @Test public void should_return_a_fortune() { ResponseEntity response = this.restTemplate .getForEntity(""http://"" + this.applicationUrl + ""/"", String.class); BDDAssertions.then(response.getStatusCodeValue()).isEqualTo(200); // Filter out the known Hystrix fallback response BDDAssertions.then(response.getBody()).doesNotContain(""This fortune is no good. Try another.""); } } ``` In this case, in contrast to the integration test we created earlier for `greeting-ui`, we do not include `@AutoConfigureStubRunner` since we are using a standalone stub runner application. ===== 3.9 Push changes to GitHub Push contract-based changes for `greeting-ui`. You should be pushing the following new or modified files: * pom.xml * sc-pipelines.yml * sc-pipelines/manifest-stubrunner.yml * src/test/java/io/pivotal/fortune/FortuneServiceTests.java * src/test/java/smoke/SmokeTests.java At this point, we can run through the full pipeline for `greeting-ui` and leverage the contract-based stub in both the build and test environments. ===== Stage 3 Recap What have we accomplished? By implementing a contract-driven approach with auto-generation of tests and stubs, we have introduced a clean, structured, and reliable way to define, communicate, document, manage and test APIs * Inter-team communication will be simpler - Consumer and producer teams can now communicate requirements through codified contracts - The inventory of contracts serves as a record and reference of the agreed upon APIs * Developer productivity will increase - Producers can quickly and easily generate contract-based stubs - Consumers no longer have to manually stub out APIs and write tests with arbitrary hard-coded responses - instead they can use the auto-generated stubs and test for contract-based responses - Both producers and consumers can validate they are compliant with the contract - Producers can verify backward compatibility of API changes - Troubleshooting will be easier - Failure and feedback will be faster === Conclusion This concludes the tutorial on migrating apps for Spring Cloud Pipelines for Cloud Foundry. Moving forward, the refactoring work needed here can be incorporated into your and/or your team's standard practices. In short: *Good:* * Use maven or gradle wrappers * Include a Cloud Foundry manifest file in your app repo * Include a pipeline descriptor (`sc-manifest.yml`) in your app repo * Create an empty `version` branch in your app repo * Include artifact repository configuration in the pom.xml file * Align your Cloud Foundry spaces with Spring Cloud Pipelines model (isolated test space, shared stage and prod spaces) *Better* * Include default, apicompatibility, smoke, and e2e profiles in the pom.xml file * Organize tests accordingly in your app repo *Best* * Use a database migration tool like flyway * Use contract-based API programming Implementing all the *""good""* practices above already positions you to instantly create pipelines for your apps usign Spring Cloud Pipelines. This is a huge win in terms of consistency and productivity, and standardization across development teams. Of course, this is an open source project, so it can be modified to meet your needs. Implementing the *""better""* practices will ensure the proper tests get run at the proper time. At that point you can add as much test coverage as you need to have high confidence in your pipelines. Implementing the *""best""* practices will give you additional confidence in your pipeline and encourage better programming practices for database version and API management across development teams. It will also give you higher confidence in your pipelines and enable you to avoid the cumbersome business of rolling back a database. Happy coding! ",16253,True,2814.784687227654,median "== Step-by-step Cloud Foundry migration === Preview https://docs.google.com/presentation/d/e/2PACX-1vSsEHn8cJfz8oWIwwUhdULt7nZzz3bBLK7OqM8UInkZ0LbQBCpPdhMoxsYGPe_90h9OvCu7dFlAimMJ/pub?start=false&loop=false&delayms=3000[Click here] to check out the slides by https://twitter.com/ciberkleid[Cora Iberkleid] where she migrates a setup of applications to be compliant with Spring Cloud Pipelines. === Introduction This tutorial covers refactoring applications to comply with, and take advantage of, Spring Cloud Pipelines. We will use a simple 3-tier application as an example: image::{cf-migration-root-docs}/use_case_logical.png[title=""Use Case - Logical View""] At the end of this tutorial, it will be possible to instantly create a Concourse pipeline for each app and run successfully through a full lifecycle, from source code commit to production deployment, following the lifecycle stages for testing and deployment recommended by Spring Cloud Pipelines. The app code bases will be improved with organized test coverage, a contract-based API, and a versioned database schema, enabling Spring Cloud Pipelines to carry out stubbed testing and to ensure backward compatibility for API and database schema changes. === Sample application - initial state The sample application is implemented using Spring Boot apps for the UI and service tiers, and MySQL for the database. The apps are built using Maven and pushed manually to Cloud Foundry. They leverage the three Pivotal Spring Cloud Services: Config Server, Service Discovery, and Circuit Breaker Dashboard. Rabbit is used to propagate Config Server refresh triggers. The source code for the two Spring Boot apps is stored on GitHub, as is the backing repo for Config Server. image::{cf-migration-root-docs}/use_case_implementation.png[title=""Use Case - Implementation""] === Sample application - end state Through this tutorial, we will be adding Concourse and JFrog Bintray to manage the application lifecycle. We will also be refactoring the application to comply with Spring Cloud Pipelines requirements and recommendations, including adding/organizing tests and introducing database versioning using Flyway and API contracts using Spring Cloud Contract. === Tutorial - toolset * *GitHub* - sample app source code and config repositories, a sample stubrunner app repository, and the Spring Cloud Pipelines code base - https://github.com/ciberkleid/greeting-ui[greeting-ui] - https://github.com/ciberkleid/fortune-service[fortune-service] - https://github.com/ciberkleid/app-config[app-config] - https://github.com/spring-cloud-samples/cloudfoundry-stub-runner-boot[cloudfoundry-stub-runner-boot] - https://github.com/spring-cloud/spring-cloud-pipelines[spring-cloud-pipelines] * *Pivotal Web Services* - public hosted Cloud Foundry offering http://run.pivotal.io[free trial accounts] and including MySQL, Rabbit, and Pivotal Spring Cloud Services in the Marketplace * *Concourse* * *JFrog Bintray* - public hosted Maven repository offering free https://bintray.com/signup/oss[OSS accounts] * *Client Tools* - on your local machine, you will need an IDE as well as the mvn, git, cf, and fly (Concourse) CLIs === Tutorial - overview The migration steps are broken down into three stages: . *Scaffolding* - Minimal refactoring to comply with basic Spring Cloud Pipelines requirements. - At the end of this stage, each app will have a corresponding pipeline on Concourse. The pipelines will successfully build the apps, store the artifacts in Bintray, tag the GitHub repositories, and deploy the apps to Test, Stage, and Prod spaces in Cloud Foundry. . *Tests* - Add/organize tests to comply with Spring Cloud Pipelines recommendations. Incorporate flyway for database schema versioning and initial data loading. - At the end of this stage, the pipelines will trigger unit and integration tests during the Build stage, smoke tests in the Test environment, and end-to-end tests in the Stage environment. The pipelines will also ensure backward compatibility for the database, such that you can safely roll back the backend service app, even after the database schema has been updated. . *Contracts* - Incorporate Spring Cloud Contract to define the API between the UI and service apps and auto-generate tests and stubs. - At the end of this stage, the pipelines will catch breaking API changes during the Build stage and ensure backward compatibility for the API, such that you can safely roll back the backend service (producer) app, even after an API change. === Tutorial - step-by-step ==== Prep: Before you begin If you want to simply review the migration steps explained below, you can look at the various branches in the https://github.com/ciberkleid/greeting-ui[greeting-ui] and https://github.com/ciberkleid/fortune-service[fortune-service] repositories - there is a branch representing the end-state of each stage: image::{cf-migration-root-docs}/github_branches.png[title=""GitHub Branches""] If you want to use this tutorial as a hands-on lab, fork each of the following repositories: - https://github.com/ciberkleid/greeting-ui[greeting-ui] - https://github.com/ciberkleid/fortune-service[fortune-service] - https://github.com/ciberkleid/app-config[app-config] Then, create a new directory on your local machine. You may name it anything you like; we will refer to it as `$SCP_HOME` throughout this tutorial. In `$SCP_HOME`, clone your forks of `greeting-ui` and `fortune-service`, as well as the following two repositories: - https://github.com/spring-cloud-samples/cloudfoundry-stub-runner-boot[cloudfoundry-stub-runner-boot] - https://github.com/spring-cloud/spring-cloud-pipelines[spring-cloud-pipelines] Finally, create a directory called `$SCP_HOME/credentials`. Leave it empty for now. ==== Stage 1: Scaffolding In this stage, we make minimal changes to satisfy basic Spring Cloud Pipelines requirements so that the apps can run through the entire pipeline without error. We make ""scaffolding"" changes only - no code changes. The steps in this stage must be completed for both `greeting-ui` and `fortune-service`. ===== 1.1 Create GitHub branches ```bash git branch version git checkout -b sc-pipelines ``` Branch *version* is required to exist, though it can be created as an empty branch. It is used by Spring Coud Pipelines to generate a version number for each new pipeline execution. Branch *sc-pipelines* is optional and can be named anything you wish. The intention is for you to use it as a working branch for the changes suggested in this tutorial (hence we create it and also check it out). ===== 1.2 Add Maven wrapper ```bash mvn -N io.takari:maven:wrapper ``` This commands adds 4 files to a project: [source,bash] ---- . ├── mvnw ├── mvnw.cmd └── .mvn └── wrapper    ├── maven-wrapper.jar    └── maven-wrapper.properties ---- Make sure all four files are tracked by Git. For example, you can add the following to the `.gitignore` file: ``` #Exceptions !/mvnw !/mvnw.cmd !/.mvn/wrapper/maven-wrapper.jar !/.mvn/wrapper/maven-wrapper.properties ``` ===== 1.3 Create Bintray maven repo package We are using Bintray as the maven repository. Bintray requires that a package exist before any app artifacts can be uploaded. Log into the Bintray UI and create the packages as follows. You can use the `Import from GitHub` option to create these: image::{cf-migration-root-docs}/bintray_packages.png[title=""Bintray Packages""] ===== 1.4 Configure distribution management using Bintray maven repo Edit the app `pom.xml` files as follows. Make sure the Bintray URLs match the URLs of the corresponding packages created in the previous step. The values you use will be different from the example shown below. ```xml ... bintray https://api.bintray.com/maven/ciberkleid/maven-repo/fortune-service ... ${distribution.management.release.id} ${distribution.management.release.url} ``` Though not required by Spring Cloud Pipelines, it makes sense to also configure your local maven settings with the credentials to your Bintray maven repo. To do so, edit your maven settings file, usually `~/.m2/settings.xml`. If the file does not exist, create it. Note that the `id` must match the id specified in the previous step. Also, make sure to use your username and API token (not account password) instead of the sample values shown below. ```xml bintray ciberkleid my-super-secret-api-token ``` ===== 1.5 Push changes to GitHub Push the above changes to GitHub. You should be pushing the following to each of the two app repos: * 4 new maven wrapper files * a modified .gitignore file * a modified pom.xml ===== 1.6 Add Spring Cloud Pipelines credentials file In `$SCP_HOME/credentials`, make two copies of the file `$SCP_HOME/spring-cloud-pipelines/concourse/credentials-sample-cf.yml`. Rename them as `credentials-fortune-service.yml` and `credentials-greeting-ui.yml`. CAUTION: These files will contain credentials to you GitHub repo, your Bintray repo, and your Cloud Foundry foundation. Hence, we opt to put them in a separate directory. You may choose to store these files in a private git repo, but do not push them to a public repo. Edit the git properties of each credentials file. Make sure to replace the sample values shown below as appropriate. For `tools-branch`, you may opt to use a fixed release (use v1.0.0.M8 or later for Cloud Foundry). Leave other values as they are, we will update those in later steps. ```yml app-url: git@github.com:ciberkleid/fortune-service.git app-branch: sc-pipelines tools-scripts-url: https://github.com/spring-cloud/spring-cloud-pipelines.git tools-branch: master build-options: """" github-private-key: | -----BEGIN RSA PRIVATE KEY----- MIIJKQIBAAKCAgEAvwkL97vBllOSE39Wa5ppczT1cr5Blmkhadfoa1Va2/IBVyvk NJ9PqoTI+BahF2EgzweyiDSvKsstlTsG7QgiM9So8Voi2PlDOrXL6uOfCuAS/G8X ... -----END RSA PRIVATE KEY----- git-email: ciberkleid@pivotal.io git-name: Cora Iberkleid ``` Edit the maven repo properties of each credentials file. Make sure to replace the sample values shown below as appropriate. Bintray requires separate URLs for uploads and downloads. If you are using a different artifact repository, such as Artifactory or Nexus, and the repository URL is the same for uploads and downloads, then you do not need to set `repo-with-binaries-for-upload`. ```yml m2-settings-repo-id: bintray m2-settings-repo-username: ciberkleid m2-settings-repo-password: my-super-secret-api-token repo-with-binaries: https://ciberkleid@my-super-secret-api-token@dl.bintray.com/ciberkleid/maven-repo repo-with-binaries-for-upload: https://api.bintray.com/maven/ciberkleid/maven-repo/fortune-service ``` ===== 1.7 Set Concourse pipeline At this point, all of the build jobs, which run on Concourse workers, will succeed. To verify this, log in to your Concourse target and set the Concourse pipelines. Update the target name in the example below as appropriate. ```bash # Set greeting-ui pipeline fly -t myTarget set-pipeline -p greeting-ui -c ""${SCP_HOME}/spring-cloud-pipelines/concourse/pipeline.yml"" -l ""${SCP_HOME}/credentials/credentials-greeting-ui.yml"" -n # Set fortune-service pipeline fly -t myTarget set-pipeline -p fortune-service -c ""${SCP_HOME}/spring-cloud-pipelines/concourse/pipeline.yml"" -l ""${SCP_HOME}/credentials/credentials-fortune-service.yml"" -n ``` Log into the Concourse UI and unpause the pipelines. Start each. You should see that the build jobs all succeed. image::{cf-migration-root-docs}/concourse_build_success.png[title=""Build Success""] In addition, you will see a new dev/ tag in each GitHub repo, as well as the app jars uploaded into Bintray. The test, stage, and prod jobs will fail because we have not yet added scaffolding for deployment to Cloud Foundry. We will do that next. ===== 1.8 Add Cloud Foundry manifest If you are deploying to Cloud Foundry, you may already be routinely including manifest files with your apps. Our sample apps did not have manifest files, so we add them now. In the `greeting-ui` repo, create a `manifest.yml` file as follows: ```yml --- applications: - name: greeting-ui timeout: 120 services: - config-server - cloud-bus - service-registry - circuit-breaker-dashboard env: JAVA_OPTS: -Djava.security.egd=file:///dev/urandom TRUST_CERTS: api.run.pivotal.io ``` In the `fortune-service` repo, create a `manifest.yml` file as follows: ```yml --- applications: - name: fortune-service timeout: 120 services: - fortune-db - config-server - cloud-bus - service-registry - circuit-breaker-dashboard env: JAVA_OPTS: -Djava.security.egd=file:///dev/urandom TRUST_CERTS: api.run.pivotal.io ``` The `TRUST_CERTS` variable is used by the Pivotal Spring Cloud Services (Config Server, Service Registry, and Circuit Breaker Dashboard), which we are using in this example. The value specified above assumes deployment to Pivotal Web Services. Update it accordingly if you are deploying to a different Cloud Foundry foundation, or you can leave it out altogether if you are replacing the Pivotal Spring Cloud Services with alternative implementations (e.g. deploying apps and exposing them as user-provided services). You may add additional values to the manifest files if you wish, for example if additional values are useful for any manual deployment you may still want to do, or desirable in your Spring Cloud Pipelines deployment. For example, an alternative manifest.yml for `fortune-service` could be as follows: ```yml --- applications: - name: fortune-service timeout: 120 instances: 3 memory: 1024M buildpack: https://github.com/cloudfoundry/java-buildpack.git random-route: true path: ./target/fortune-service-0.0.1-SNAPSHOT.jar services: - fortune-db - config-server - cloud-bus - service-registry - circuit-breaker-dashboard env: SPRING_PROFILES_ACTIVE: someProfile JAVA_OPTS: -Djava.security.egd=file:///dev/urandom TRUST_CERTS: api.run.pivotal.io ``` Note that `random-route` and `path` are ignored by Spring Cloud Pipelines. `instances` is honored in stage and prod, but overridden with a value of 1 for test. ===== 1.9 Add Spring Cloud Pipelines manifest The Cloud Foundry manifest created in the previous step includes the logical names of the services to which the apps should be bound, but it does describe how the services can be provisioned. Hence, we add a second manifest file so that Spring Cloud Pipelines can provision the services. Add a file called `sc-pipelines.yml` to each app, and include the same list of services as in the corresponding `manifest.yml`. Add the necessary details such that Spring Cloud Pipelines can construct a `cf create-service` command. NOTE: The `type: broker' parameter shown below instructs Spring Cloud Pipelines to provision a service using `cf create-service'. Other service types are also supported: cups, syslog, route, app, and stubrunner. More specifically, for `greeting-ui`, create an `sc-pipelines.yml` file with the following content: ```yml test: services: - name: config-server type: broker broker: p-config-server plan: standard params: git: uri: https://github.com/ciberkleid/app-config useExisting: true - name: cloud-bus type: broker broker: cloudamqp plan: lemur useExisting: true - name: service-registry type: broker broker: p-service-registry plan: standard useExisting: true - name: circuit-breaker-dashboard type: broker broker: p-circuit-breaker-dashboard plan: standard useExisting: true ``` The `sc-pipelines.yml` file for `fortune-service` is similar, with the addition of the `fortune-db` service: ```yml test: # list of required services services: - name: fortune-db type: broker broker: cleardb plan: spark useExisting: true - name: config-server type: broker broker: p-config-server plan: standard params: git: uri: https://github.com/ciberkleid/app-config useExisting: true - name: cloud-bus type: broker broker: cloudamqp plan: lemur useExisting: true - name: service-registry type: broker broker: p-service-registry plan: standard useExisting: true - name: circuit-breaker-dashboard type: broker broker: p-circuit-breaker-dashboard plan: standard useExisting: true ``` The values above assume deployment to Pivotal Web Services. If you are deploying to a different Cloud Foundry foundation, please update the values accordingly. Also, make sure to replace the `config-server` uri with the address of your fork of the https://github.com/ciberkleid/app-config[app-config] repo. TIP: Notice the `useExisting: true` parameter above. By default, Spring Cloud Pipelines will delete and recreate services in the `test` space. To override this behavior and re-use existing services, we set `useExisting: true`. This is helpful in cases where services may take time to provision and initialize, where there is no risk in re-using them between pipeline runs, or where it is desirable to retain the service instance from the last pipeline run (e.g. a database migration). ===== 1.10 Push changes to GitHub Push the above changes to GitHub. You should be pushing the following to each of the two app repos: * new app manifest file * new sc-pipelines manifest file ===== 1.11 Create Cloud Foundry Orgs/Spaces Spring Cloud Pipelines requires that the Cloud Foundry test, stage, and prod spaces exist before a pipeline is run. If you wish, you can use different foundations, orgs, and users for each. For simplicity, in this example, we use a single foundation (PWS), a single org, and a single user. You can name the org(s) and spaces anything you like. Each app requires its own test space. The stage and prod spaces are shared. For this example, create the following spaces: ```bash cf create-space scp-test-greeting-ui cf create-space scp-test-fortune-service cf create-space scp-stage cf create-space scp-prod ``` ===== 1.12 Create Cloud Foundry stage and prod service instances Spring Cloud Pipelines will dynamically create the services in the test spaces as per the `sc-pipelines.yml` file we created previously. Optionally, a second section can be added to the `sc-pipelines.yml` file for the stage environment, and these will be created dynamically as well. Prod services, however, must always be created manually. For this example, we will create the stage and services manually. Create the services listed in the app manifest files in both `scp-stage` and `scp-prod`. ===== 1.13 Update Spring Cloud Pipelines credentials file Update the `greeting-ui` and `fortune-service` credentials files with Cloud Foundry information. Replace values in the example below as appropriate for your Cloud Foundry environment. Notice that the space name specified is a prefix. Spring Cloud Pipelines will append the app name, matching the test space names created previously. The stage and prod space names are not prefixes and will not be altered by Spring Cloud Pipelines. Note also the `paas-hostname-uuid`. The value will be included in each route created. This value is optional, but it is useful in shared/multi-tenant environments such as PWS, as it helps ensure routes are unique. Change it to a unique uuid of your choosing. ```yml pipeline-descriptor: sc-pipelines.yml paas-type: cf paas-hostname-uuid: cyi # test values paas-test-api-url: https://api.run.pivotal.io paas-test-username: ciberkleid@pivotal.io paas-test-password: secret paas-test-org: S1Pdemo12 paas-test-space-prefix: scp-test # stage values paas-stage-api-url: https://api.run.pivotal.io paas-stage-username: ciberkleid@pivotal.io paas-stage-password: my-super-secret-password paas-stage-org: S1Pdemo12 paas-stage-space: scp-stage # prod values paas-prod-api-url: https://api.run.pivotal.io paas-prod-username: ciberkleid@pivotal.io paas-prod-password: my-super-secret-password paas-prod-org: S1Pdemo12 paas-prod-space: scp-prod ``` ===== 1.14 Update Concourse pipeline with updated credentials files Set the Concourse pipelines again, as we did previously, to update them with the values added to the credentials files. The test, stage, and prod jobs will all now succeed. image::{cf-migration-root-docs}/concourse_test_stage_prod_success.png[title=""Test, Stage, & Prod Success""] On Cloud Foundry, you will now see the apps deployed in the test, stage, and prod spaces. The image below shows the deploymnet of `fortune-service` to its isolated and dedicated test space, with the 5 services declared in its manifest files (`sc-pipelines.yml` for provisioning, and `manifest.yml` for binding). It also shows the deployment of the same app to the shared prod space, including the stopped instance of the previous version. If a rollback were deemed necessary, the `prod-rollback` job in the pipeline could be triggered to remove the currently running version, remove the `prod/` tag from GitHub, and re-start the former (*""venerable""*) version. image::{cf-migration-root-docs}/cf_test_and_prod_deployed.png[title=""Cloud Foundry Test and Prod Deployment""] ===== Stage 1 Recap & next steps What have we accomplished? * By adding the basic scaffolding needed to enable Spring Cloud Pipelines to manage the lifecycle of `greeting-ui` and `fortune-service` from source code commit to production deploy, we have made it possible for the app dev teams to instantly and easily create pipelines for each app using a common, standardized template * We can count on the pipelines to: - automatically provision services in test spaces, and optionally in stage as well - dynamically clean up the test spaces between pipeline executions - upload the app artifacts to the maven repo (Bintray) - tag the GitHub repositories with `dev/` and `prod/` * After each successful pipeline run, we are in a position to roll back to the last deployed version using the `prod-rollback` job, if necessary These accomplishments are extremely valuable, but in order to derive confidence and reliability from the pipelines, we need to incorporate testing. We do this in Stage 2 of the app migration. ==== Stage 2: Tests In this stage, we enable Spring Cloud Pipelines to execute tests so that we can increase confidence in the code being deployed. We do so by adding test profiles to the pom.xml files, and then organizing and/or adding tests in a way that corresponds to the profiles. By doing so, we are establishing standards around testing across development teams in the enterprise. We will also enable database schema versioning in this stage, thereby providing the foundation for rollback testing during schema changes. ===== 2.1 Add Maven profiles For both `greeting-ui` and `fortune-service`, add a `profiles` section to the `pom.xml` file, as shown below. Note that we are adding four profiles: * default ** For unit and integration tests. Note that this profile includes all tests except those that will explicitly be called by the smoke and e2e profiles. ** Tests matching this profile will be executed during the build-and-upload job * apicompatibility ** For ensuring backward compatibility in case of API changes. Note that this is not effective until Stage 3, when we will add contracts. However, we add this profile now to ensure the api-compatibility-check job does not execute other tests. * smoke ** For tests to be run against the app deployed in the test space. * e2e ** For tests to be run against the app deployed in the stage space. ```xml default true org.apache.maven.plugins maven-surefire-plugin **/*Tests.java **/*Test.java **/smoke/** **/e2e/** org.springframework.boot spring-boot-maven-plugin apicompatibility org.apache.maven.plugins maven-surefire-plugin **/contracttests/**/*Tests.java **/contracttests/**/*Test.java smoke org.apache.maven.plugins maven-surefire-plugin smoke/**/*Tests.java smoke/**/*Test.java e2e org.apache.maven.plugins maven-surefire-plugin e2e/**/*Tests.java e2e/**/*Test.java ``` ===== 2.2 Add/organize tests Next, we ensure that we have a matching test package structure in our apps: image::{cf-migration-root-docs}/test_package_structure.png[title=""Test Package Structure""] Note that we are creating matching packages for the default, smoke, and e2e profiles only. We will address the package for the apicompatibility profile in Stage 3. When working with your own apps, if you have existing tests, you would now move them into one of these packages now, and rename them so that they are included in the filters declared in the profiles (i.e. the file names end in `Test.java` or `Tests.java`) In the case of our sample apps, there are no tests, so we add some now as follows. *fortune-service default tests* Add your unit and integration tests so that they match the default profile as defined in the `fortune-service` `pom.xml` file. These will be executed on Concourse against the `fortune-service` application running on the Concourse worker in the `build-and-upload` job. As an example, we will add two tests, one that loads the context, and another that verifies the number of rows expected in the database: ```java package io.pivotal; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.jdbc.core.JdbcTemplate; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.*; @RunWith(SpringRunner.class) @SpringBootTest(classes = FortuneServiceApplication.class) public class FortuneServiceApplicationTests { @Test public void contextLoads() throws Exception { } @Autowired private JdbcTemplate template; @Test public void testDefaultSettings() throws Exception { assertThat(this.template.queryForObject(""SELECT COUNT(*) from FORTUNE"", Integer.class)).isEqualTo(7); } } ``` *fortune-service smoke tests* Add your smoke tests so that they match the smoke profile as defined in the `fortune-service` `pom.xml` file. These will be executed on Concourse against the `fortune-service` application deployed in the Cloud Foundry `scp-test-fortune-service` space. Two versions of these tests are executed against the app: . the current version, in the `test-smoke` job . the latest prod version, in the `test-rollback-smoke` job image::{cf-migration-root-docs}/fortune_service_smoke_tests.png[title=""fortune-service Smoke Tests""] In the test environment, we choose to verify that `fortune-service` is retrieving a fortune from `fortune-db`, and not returning its Hystrix fallback response: ```java package smoke; import org.assertj.core.api.BDDAssertions; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestTemplate; @RunWith(SpringRunner.class) @SpringBootTest(classes = SmokeTests.class, webEnvironment = SpringBootTest.WebEnvironment.NONE) @EnableAutoConfiguration public class SmokeTests { @Value(""${application.url}"") String applicationUrl; RestTemplate restTemplate = new RestTemplate(); @Test public void should_return_a_fortune() { ResponseEntity response = this.restTemplate .getForEntity(""http://"" + this.applicationUrl + ""/"", String.class); BDDAssertions.then(response.getStatusCodeValue()).isEqualTo(200); // Filter out the known Hystrix fallback response BDDAssertions.then(response.getBody()).doesNotContain(""The fortuneteller will be back soon.""); } } ``` *fortune-service e2e tests* Add your e2e tests so that they match the e2e profile as defined in the `fortune-service` `pom.xml` file. These will be executed on Concourse against the `fortune-service` application deployed in the Cloud Foundry `scp-stage` space. This space is shared, so we assume `greeting-ui` is also present. image::{cf-migration-root-docs}/fortune_service_e2e_tests.png[title=""fortune-service E2E Tests""] In the e2e environment, we choose to use a string replacement to obtain the URL for `greeting-ui`. We also choose to verify that we are hitting `fortune-db` and not receiving Hystrix fallback responses from either application: ```java package e2e; import org.assertj.core.api.BDDAssertions; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestTemplate; @RunWith(SpringRunner.class) @SpringBootTest(classes = E2eTests.class, webEnvironment = SpringBootTest.WebEnvironment.NONE) @EnableAutoConfiguration public class E2eTests { // The app is running in CF but the tests are executed from Concourse worker, // so the test will deduce the url to greeting-ui: it will assume the same host // as fortune-service, and simply replace ""fortune-service"" with ""greeting-ui"" in the url @Value(""${application.url}"") String applicationUrl; RestTemplate restTemplate = new RestTemplate(); @Test public void should_return_a_fortune() { ResponseEntity response = this.restTemplate .getForEntity(""http://"" + this.applicationUrl.replace(""fortune-service"", ""greeting-ui"") + ""/"", String.class); BDDAssertions.then(response.getStatusCodeValue()).isEqualTo(200); // Filter out the known Hystrix fallback responses from both fortune and greeting BDDAssertions.then(response.getBody()).doesNotContain(""This fortune is no good. Try another."").doesNotContain(""The fortuneteller will be back soon.""); } } ``` *greeting-ui default tests* Add your unit and integration tests so that they match the default profile as defined in the `greeting-ui` `pom.xml` file. These will be executed on Concourse against the `greeting-ui` application running on the Concourse worker in the `build-and-upload` job. As an example, we will add one test that loads the context: ```java package io.pivotal; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(classes = GreetingUIApplication.class) public class GreetingUIApplicationTests { @Test public void contextLoads() throws Exception { } } ``` *greeting-ui smoke tests* Add your smoke tests so that they match the smoke profile as defined in the `greeting-ui` `pom.xml` file. These will be executed on Concourse against the `greeting-ui` application deployed in the Cloud Foundry `scp-test-greeting-ui` space. Two versions of these tests are executed against the app: . the current version, in the `test-smoke` job . the latest prod version, in the `test-rollback-smoke` job image::{cf-migration-root-docs}/greeting_ui_smoke_tests.png[title=""greeting-ui Smoke Tests""] Since `fortune-service` is not deployed to the `scp-test-greeting-ui` space, we expect to receive the Hystrix fallback response defined in `greeting-ui`. Hence, our smoke test validates that condition: ```java package smoke; import org.assertj.core.api.BDDAssertions; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestTemplate; @RunWith(SpringRunner.class) @SpringBootTest(classes = SmokeTests.class, webEnvironment = SpringBootTest.WebEnvironment.NONE) @EnableAutoConfiguration public class SmokeTests { @Value(""${application.url}"") String applicationUrl; RestTemplate restTemplate = new RestTemplate(); @Test public void should_return_a_fallback_fortune() { ResponseEntity response = this.restTemplate .getForEntity(""http://"" + this.applicationUrl + ""/"", String.class); BDDAssertions.then(response.getStatusCodeValue()).isEqualTo(200); // Expect the hystrix fallback response BDDAssertions.then(response.getBody()).contains(""This fortune is no good. Try another.""); } } ``` *greeting-ui e2e tests* Add your e2e tests so that they match the e2e profile as defined in the `greeting-ui` `pom.xml` file. These will be executed on Concourse against the `greeting-ui` application deployed in the Cloud Foundry `scp-stage` space. This space is shared, so we assume `fortune-service` is also present. image::{cf-migration-root-docs}/greeting_ui_e2e_tests.png[title=""greeting-ui E2E Tests""] In the e2e environment, we choose to verify that we are hitting `fortune-service` and not receiving the Hystrix fallback response from `greeting-ui`: ```java package e2e; import org.assertj.core.api.BDDAssertions; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestTemplate; @RunWith(SpringRunner.class) @SpringBootTest(classes = E2eTests.class, webEnvironment = SpringBootTest.WebEnvironment.NONE) @EnableAutoConfiguration public class E2eTests { @Value(""${application.url}"") String applicationUrl; RestTemplate restTemplate = new RestTemplate(); @Test public void should_return_a_fortune() { ResponseEntity response = this.restTemplate .getForEntity(""http://"" + this.applicationUrl + ""/"", String.class); BDDAssertions.then(response.getStatusCodeValue()).isEqualTo(200); // Filter out the known Hystrix fallback response BDDAssertions.then(response.getBody()).doesNotContain(""This fortune is no good. Try another.""); } } ``` ===== 2.3 Enable database versioning At this point will also incorporate https://flywaydb.org/[Flyway], an OSS database migration tool, to track database schema versions and handle schema changes and data loading. This change only needs to be made to `fortune-service`, since `fortune-service` owns the interaction with `fortune-db`. *Add Flyway dependency* We first add the Flyway dependency to the `fortune-service` `pom.xml`. We need not add a version as Spring Boot will take care of that for us. ```xml org.flywaydb flyway-core ``` *Create Flyway migration* Next, we create a migration directory and our initial migration file following Flyway's file naming convention: image::{cf-migration-root-docs}/fortune_service_flyway_file_name.png[title=""fortune-service Flyway File Name""] Note the filename specifies the version (`V1`), followed by two underscore characters. We place our CREATE TABLE and INSERT statements in our `src/main/resources/db/migration/V1__init.sql` file: ```sql CREATE TABLE fortune ( id BIGINT PRIMARY KEY AUTO_INCREMENT, text varchar(255) not null ); INSERT INTO fortune (text) VALUES ('Do what works.'); INSERT INTO fortune (text) VALUES ('Do the right thing.'); INSERT INTO fortune (text) VALUES ('Always be kind.'); INSERT INTO fortune (text) VALUES ('You learn from your mistakes... You will learn a lot today.'); INSERT INTO fortune (text) VALUES ('You can always find happiness at work on Friday.'); INSERT INTO fortune (text) VALUES ('You will be hungry again in one hour.'); INSERT INTO fortune (text) VALUES ('Today will be an awesome day!'); ``` *Disable JPA DDL initialization* Now that we are relying on Flyway to create and populate the schema, we need to disable JPA-based database initialization. We can set `ddl-auto` to `validate`, which will validate the schema against the application entities and throw an error in case of a mismatch, but not actually generate the schema: ```yml spring: jpa: hibernate: ddl-auto: validate ``` There are a few options for where to store the `ddl-auto` configuration, both in terms of location (in the `fortune-service` app or on the `app-config` GitHub repo) and in terms of file name. For this example, update the `application.yml` in the `fortune-service` app for local testing. additionally, save these values in a new file called `application-flyway.yml` on your fork of https://github.com/ciberkleid/app-config[app-config]. By convention, `fortune-service` will pick up the configurations in `application-flyway.yml` if the string `flyway` is in the list of active Spring profiles. Thus, we add `flyway` to the environment variable `SPRING_PROFILES_ACTIVE` via the `fortune-service` `manifest.yml`: ```yml --- applications: - name: fortune-service timeout: 120 services: - fortune-db - config-server - cloud-bus - service-registry - circuit-breaker-dashboard env: SPRING_PROFILES_ACTIVE: flyway JAVA_OPTS: -Djava.security.egd=file:///dev/urandom TRUST_CERTS: api.run.pivotal.io ``` *Remove non-Flyway data loading* We can now remove the old code that populated the database. In our sample app, this was found in class `io.pivotal.FortuneServiceApplication`. The following shows the code we now remove: ```java @Bean CommandLineRunner loadDatabase(FortuneRepository fortuneRepo) { return args -> { // logger.debug(""loading database..""); // fortuneRepo.save(new Fortune(1L, ""Do what works."")); // fortuneRepo.save(new Fortune(2L, ""Do the right thing."")); // fortuneRepo.save(new Fortune(3L, ""Always be kind."")); // fortuneRepo.save(new Fortune(4L, ""You learn from your mistakes... You will learn a lot today."")); // fortuneRepo.save(new Fortune(5L, ""You can always find happiness at work on Friday."")); // fortuneRepo.save(new Fortune(6L, ""You will be hungry again in one hour."")); // fortuneRepo.save(new Fortune(7L, ""Today will be an awesome day!"")); logger.debug(""record count: {}"", fortuneRepo.count()); fortuneRepo.findAll().forEach(x -> logger.debug(x.toString())); }; } ``` We also no longer need the Fortune entity constructors, so we can comment these out in class `io.pivotal.fortune.Fortune` as shown below: ```java // public Fortune() { // } // // public Fortune(Long id, String text) { // super(); // this.id = id; // this.text = text; // } ``` *Flyway integration summary* With that, we have completed the setup for Flyway and our database schema is now versioned. From this point onward, Spring Boot will call `Flyway.migrate()` to perform the database migration. As long as we follow Flyway conventions for future schema changes, Flyway will take care of tracking the schema version and migrating the database for us. From a rollback perspective, Spring Cloud Pipelines includes two jobs in the `test` phase - `test-rollback-deploy` and `test-rollback-smoke` - wherein it validates that the latest prod jar works against the newly updated database. The purpose is to ensure that we can roll back the application in prod if a problem is discovered after the prod database schema has been updated, and avoid the burden of rolling back the database. Read more about https://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html#howto-use-a-higher-level-database-migration-tool[Spring Boot database initialization with Flyway] for further information, including Flyway configuration options. ===== 2.4 Push changes to GitHub For `greeting-ui`, you should be pushing the following new or modified files: * pom.xml * src/test/java/e2e/E2eTests.java * src/test/java/io/pivotal/GreetingUIApplicationTests.java * src/test/java/smoke/SmokeTests.java For `fortune-service`, you should be pushing the following new or modified files: * pom.xml * src/test/java/e2e/E2eTests.java * src/test/java/io/pivotal/FortuneServiceApplicationTests.java * src/test/java/smoke/SmokeTests.java * src/main/resources/db/migration/V1__init.sql * src/main/resources/application.yml * manifest.yml * src/main/java/io/pivotal/FortuneServiceApplication.java * src/main/java/io/pivotal/fortune/Fortune.java For `app-config`, you should be pushing the following new or modified files: * application-flyway.yml ===== 2.5 Re-run the pipelines Run through the pipelines again and view the output for the jobs that run the default, smoke, and e2e tests. You will see that the tests we added in this stage were executed. As you run through the pipelines a second time, you will see the smoke tests from the latest prod version run against the database in the `test-rollback-smoke` job. In this case there is no schema upgrade, but nonetheless the tests confirm that the latest prod version of the app can be used with the current database schema. You can see the database version information stored in the database by Flyway either by querying the database itself or by hitting the flyway endpoint on the `fortune-service` URL. Here is an example from the scp-stage environment: image::{cf-migration-root-docs}/fortune_service_flyway_schema_info.png[title=""fortune-service Flyway Schema Info""] ===== Stage 2 Recap & next steps What have we accomplished? * By integrating our applications with the testing strategy built into Spring Cloud Pipelines, we have increased the effectiveness of the pipelines, as well as our confidence in them * Established a standard approach to organizing tests that will bring consistency within and across development teams * Enabled auto-managed database versioning and backward compatibility testing that will alleviate database schema management throughout the release management lifecycle We are now positioned to add any unit, integration, smoke, and end-to-end tests to our code base and extract a very high level of reliability and confidence from our pipelines. We are also better positioned to ensure that our dev teams conform to these practices, given the structure imposed by Spring Cloud Pipelines and the fast feedback and visibility we gain from the pipelines as they execute the tests. However, we could benefit further by incorporating contracts to define and test the API integration points between applications. We do this in Stage 3 of the app migration. ==== Stage 3: Contracts In this stage, we introduce contract-based programming practices into our sample application. Doing so improves API management capabilities, including defining, communicating, and testing API semantics. It also enables us to catch breaking API changes (i.e. validate API backward compatibility) in the build phase. This will extend the effectiveness of the pipelines, encourage better communication and programming practices across development teams, and provide faster feedback to developers. We will integrate Spring Cloud Contract and add contracts, stubs, and a stub runner. We will also now complete and make use of the apicompatibility profile defined in Stage 2. ===== 3.1 Create a contract Let's start by creating the contract for the interaction between `greeting-ui` and `fortune-service`. The contract should describe the following expectation: * `greeting-ui` makes a `GET` request to the root URL of `fortune-service` and expects a response with status 200 and a string (""foo fortune"") in the body We codify this using groovy syntax as follows: ```groovy import org.springframework.cloud.contract.spec.Contract Contract.make { description("""""" should return a fortune string """""") request { method GET() url ""/"" } response { status 200 body ""foo fortune"" } } ``` Save this contract in the `fortune-service` code base in the following location, which is compliant with Spring Cloud Contract convention (`src/test/resources/contracts//`): image::{cf-migration-root-docs}/fortune_service_contract_file.png[title=""fortune-service Flyway Contract File""] NOTE: You can optionally enable your IDE to assist with contract syntax by adding the Spring Cloud Contract Verifier to your `pom.xml` file. It is pluggable, and includes groovy and pact by default. ```xml org.springframework.cloud spring-cloud-starter-contract-verifier test ``` ===== 3.2 Create a base class for contract tests Now that we have a codified contract, we want to enable auto-generation of contract-based tests. The auto-generation, which we will configure in the next steps, requires a base class that stubs out the service that satisfies the API call, so that we can run the test without external dependencies (e.g. the DB). The objective is to focus on testing API semantics. We create the base class in the `fortune-service` test package as follows: ```java package io.pivotal.fortune; import io.restassured.module.mockmvc.RestAssuredMockMvc; import org.junit.Before; import org.mockito.BDDMockito; public class BaseClass { @Before public void setup() { FortuneService service = BDDMockito.mock(FortuneService.class); BDDMockito.given(service.getFortune()).willReturn(""foo fortune""); RestAssuredMockMvc.standaloneSetup(new FortuneController(service)); } } ``` ===== 3.3 Enable automated contract-based testing Now that we have a contract and a base class, we can use the *Spring Cloud Contract maven plugin* to auto-generate contract tests, stubs, and a stub jar. First we add the Spring Cloud Contract version to the list of properties in the `fortune-service` `pom.xml` file, since we will reference it when we enable the Spring Cloud Contract maven plugin: ```xml ... 1.2.1.RELEASE ... ``` Next, we edit the `default` profile in the `fortune-service` `pom.xml` file as follows: * Add a plugin block for Spring Cloud Contract maven plugin * Configure it to use our base class (`io.pivotal.fortune.BaseClass`) to generate tests * Configure it to place auto-generated tests in the test package `io.pivotal.fortune.contracttests` Note that the package of the contracttests will be included by the `include` filter in the `default` profile, so these tests will be run against the app during the `build-and-upload` job. For `fortune-service`, this serves to validate that the app conforms to the contract. Here is the complete profile: ```xml default true org.apache.maven.plugins maven-surefire-plugin **/*Tests.java **/*Test.java **/smoke/** **/e2e/** org.springframework.boot spring-boot-maven-plugin org.springframework.cloud spring-cloud-contract-maven-plugin ${spring-cloud-contract.version} true io.pivotal.fortune.BaseClass io.pivotal.fortune.contracttests ``` When the app is built, the Spring Cloud Contract maven plugin will also now produce a stub and a stub jar containing the contract and stub. This stub jar will be uploaded to Bintray, along with the usual app jar. As we will see shortly, this stub jar can be used by the `greeting-ui` dev team while they wait for `fortune-service` to be completed. Note that this gives the `greeting-ui` dev team a producer to test against that is based on a mutually agreed-upon contract without the lead time of having to wait for `fortune-service` to implement anything more than a base class, and without having to manually stub out calls to `fortune-service` based on arbitrary or static responses. TIP: Package the project locally (run `mvn package`) to observe the tests, stubs, and stub jar that the Spring Cloud Contract maven plugin generates. See the image below for reference. image::{cf-migration-root-docs}/fortune_service_generated_tests.png[title=""Generated Tests and Stubs""] ===== 3.4 Enable backward compatibility API check To enable Spring Cloud Pipelines to catch any breaking API changes during the `build-api-compatibility-check` job, we add the Spring Cloud Contract maven plugin to the `apicompatibility` profile as well. In this case, we want the plugin to generate tests based on contracts outside of the project (the ones from the latest prod version), so we configure the plugin to download the latest prod stub jar, which contains the old contract. The plugin will use the old contract and the specified base class, which in our example is the same as the one in the previous step, to generate contract tests. These tests are run against the new code to validate that it is still compatible with consumers complying with the prior contract. This ensures backward compatibility for the API. In short, we edit the apicompatibility profile in the `fortune-service` `pom.xml` file as follows: * Add a plugin block for Spring Cloud Contract maven plugin * Configure it to download the latest prod stub jar from Bintray to obtain the old contract * Configure it to use our base class (`io.pivotal.fortune.BaseClass`) to generate tests (we are using the same one as in the prrior step) * Configure it to place auto-generated tests in the test package `io.pivotal.fortune.contracttests` Note that the package of the contracttests matches the `include` filter in the `apicompatibility` profile, so these tests will be run against the app during the `build-api-compatibility-check` job. For `fortune-service`, this serves to validate that the app conforms to the old contract. Here is the complete profile: ```xml apicompatibility org.apache.maven.plugins maven-surefire-plugin **/contracttests/**/*Tests.java **/contracttests/**/*Test.java org.springframework.cloud spring-cloud-contract-maven-plugin ${spring-cloud-contract.version} true ${repo.with.binaries} ${project.groupId} ${project.artifactId} stubs ${latest.production.version} / io.pivotal.fortune.BaseClass io.pivotal.fortune.contracttests ``` The values for `${repo.with.binaries}` and `${latest.production.version}` will be injected dynamically by Spring Cloud Pipelines. You can run this locally by providing these values manually as system properties in the maven command. ===== 3.5 Push changes to GitHub All changes in Stage 3 thus far are in `fortune-service`. At this point, you should be pushing the following new or modified files: * pom.xml * src/test/resources/contracts/greeting-ui/shouldReturnAFortune.groovy * src/test/java/io/pivotal/fortune/BaseClass.java ===== 3.6 Re-run the fortune-service pipeline Run through the `fortune-service` pipeline to generate stubs. The following output from the `build-and-upload` job shows the auto-generation of tests and stubs: image::{cf-migration-root-docs}/fortune_service_build_and_upload_test_and_stub_generation.png[title=""fortune-service build-and-upload Test and Stub Generation""] You will also see output in the `build-and-upload` job showing the execution of these tests against the code. Additionally, you will see the stub jar uploaded to Bintray along with the usual app jar. Finally, as you run through the pipeline a second time, you will see the contract tests from the latest prod version run against the new code in the output of the `build-api-compatibility-check` job. In this case there is no API change, but nonetheless the tests confirm that the latest prod version of the API can be used with the current code base. ===== 3.7 Enable stubs for integration tests We are in the home stretch! Let's turn our attention to `greeting-ui`. The following image compares the path of a request through `greeting-ui` in the build phase, both with and without stubs. image::{cf-migration-root-docs}/greeting_ui_build_flow.png[title=""greeting-ui Build Flow""] Without stubs, we expect the response to be the hystrix fallback response that is hard-coded in `greeting-ui`. With stubs, however, we can expect the response that was declared in the contract. In this case, the stubs are loaded into the `greeting-ui` process. This leads us to our next task: load the stubs produced by `fortune-service`. *Enable in-process stub runner* To load the stubs into the `greeting-ui` process, we must enable the Spring Cloud Contract Stub Runner dependency. This dependency will start an in-process stub runner that automatically configures Wiremock. Add the following to the `greeting-ui` `pom.xml` file: ```xml org.springframework.cloud spring-cloud-starter-contract-stub-runner test ``` *Add integration tests aligned with the contract* Next, we add integration tests to `greeting-ui` that test for the expected response declared in the contract. Add the following class to the test package in `greeting-ui`: ```java package io.pivotal.fortune; import io.pivotal.GreetingUIApplication; import org.assertj.core.api.BDDAssertions; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.contract.stubrunner.spring.AutoConfigureStubRunner; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(classes = GreetingUIApplication.class, webEnvironment = SpringBootTest.WebEnvironment.NONE, properties = {""spring.application.name=greeting-ui"", ""spring.cloud.circuit.breaker.enabled=false"", ""hystrix.stream.queue.enabled=false""}) @AutoConfigureStubRunner(ids = {""io.pivotal:fortune-service:1.0.0.M1-20180102_203542-VERSION""}, repositoryRoot = ""${REPO_WITH_BINARIES}"" //workOffline = true ) public class FortuneServiceTests { @Autowired FortuneService fortuneService; @Test public void shouldSendRequestToFortune() { // when String fortune = fortuneService.getFortune(); // then BDDAssertions.then(fortune).isEqualTo(""foo fortune""); } } ``` At this point, we can get through the build phase for `greeting-ui`, and the integration tests will be executed against the `fortune-service` stubs running in the `greeting-ui` process on the Concourse worker. TIP: Notice the configuration of `@AutoConfigureStubRunner` - you can replace the version with a `+` sign if using Artifactory or Nexus and it will automatically choose the latest available version on the maven repo. TIP: Setting `workOffline=true` (commented out but shown for informational purposes above) would make the stub runner get the stubs from the local maven repo. This is useful for local testing. Alternatively, set the `$REPO_WITH_BINARIES` environment variable to the value used in the credentials file before doing a local maven build, and the local build will download the stubs from your remote maven repo (e.g. Bintray). ===== 3.8 Enable stubs for smoke tests The following image compares the path of a request through `greeting-ui` in the test phase, both with and without stubs. Note that in the build phase, where the app process is running on the Concourse worker, we ran the stubs in the same process. In the test environment (Cloud Foundry), we will run the stubs in a separate process using a standalone stub runner application. image::{cf-migration-root-docs}/greeting_ui_test_flow.png[title=""greeting-ui Test Flow""] As in the build phase, without stubs we expect the response to be the hystrix fallback response that is hard-coded in `greeting-ui`. With stubs, however, we can expect the response that was declared in the contract. We will rely on Spring Cloud Pipelines to: * Deploy a stub runner application * Provide the stub runner application the necessary information to download the stubs * Open a port on the stub runner application for each stub We will rely on the stub runner application to: * Download the stubs from our maven repo (Bintray) * Expose each stub on a separate port * Register each stub in the Service Discovery server The following steps describe how to configure this. *Provide standalone stub runner app jar* In the Prep step for this tutorial, you cloned the https://github.com/spring-cloud-samples/cloudfoundry-stub-runner-boot[cloudfoundry-stub-runner-boot] repo to your local machine. The next step is to build this app and upload it to Bintray to make the jar available to Spring Cloud Pipelines. As mentioned in Stage 1 of this tutorial, Bintray requires that a package exist before any app artifacts can be uploaded. Log into the Bintray UI and create a package for `cloudfoundry-stub-runner-boot`. If you forked this repo, you can use the `Import from GitHub` option. Otherwise, create the package manually and choose any license (e.g. Apache 2.0). Now you are ready to build and upload this app to Bintray. The following script shows cloning, building and uploading. Edit as appropriate to match your Bintray URL, the Bintray ID in your `~/.m2/settings/xml` file, and the `cloudfoundry-stub-runner-boot` repo URL if you chose to fork it. ```bash # Edit to match your Bintray URL and M2 repo ID setting (check your ~/.m2/settings.xml file) MAVEN_REPO_URL=https://api.bintray.com/maven/ciberkleid/maven-repo/cloudfoundry-stub-runner-boot MAVEN_REPO_ID=bintray # Clone cloudfoundry-stub-runner-boot git clone https://github.com/spring-cloud-samples/cloudfoundry-stub-runner-boot.git cd cloudfoundry-stub-runner-boot # Build and upload ./mvnw clean deploy -Ddistribution.management.release.url=""${MAVEN_REPO_URL}"" -Ddistribution.management.release.id=""${MAVEN_REPO_ID}"" ``` You should now see the `cloudfoundry-stub-runner-boot` artifacts uploaded on Bintray. *Provide standalone stub runner app manifest* Next, we add a manifest file for the stub runner app for deployment to Cloud Foundry. We will place this file in the `greeting-ui` repo. The file name and location can be your choice. For this example, we will use `sc-pipelines/manifest-stubrunner.yml`: image::{cf-migration-root-docs}/greeting_ui_stubrunner_manifest.png[title=""greeting-ui Stub Runner Manifest""] We populate this `manifest-stubrunner.yml` with the content shown below so that the stub runner binds to `service-registry`. The stub runner will register the `fortune-service` stub there so that `greeting-ui` can discover it in the same way it will discover the actual `fortune-service` app endpoint in stage and prod. From the `greeting-ui` perspective, there is no difference in how it interacts with Eureka and the stub runner app in test and the way it will interact with Eureka and the `fortune-service` app in stage and prod. ```yml --- applications: - name: stubrunner timeout: 120 services: - service-registry env: JAVA_OPTS: -Djava.security.egd=file:///dev/urandom TRUST_CERTS: api.run.pivotal.io ``` *Provide stub runner jar and manifest info to the pipeline* Now that we have a jar file and manifest file for our stub runner app, we need to provide this information to our `greeting-ui` pipeline so that the pipeline downloads the jar from Bintray and deploys it to Cloud Foundry. We do this through the `greeting-ui` `sc-pipelines.yml` file. We add an entry to the list of services in the `test` section, as follows: ```yml - name: stubrunner type: stubrunner coordinates: io.pivotal:cloudfoundry-stub-runner-boot:0.0.1.M1 pathToManifest: sc-pipelines/manifest-stubrunner.yml ``` Notice that `name` matches the name of the app in `manifest-stubrunner.yml`, `coordinates` corresponds to the jar coordinates on the maven repo, and `pathToManifest` matches our chosen fie name for the stub runner app manifest. Note also the `type` is set to `stubrunner`, which Spring Cloud Pipelines will recognize as a stanalone stub runner app and treat accordingly. *Provide stub configuration for stub runner app* The final steps in the configuration of the standalone stub runner app are: * Enable the stub runner app to download the `fortune-service` stub from Bintray * Open a second port on the container to receive requests for this stub To accomplish this, we put stub and port configuration information into the properties section of the `greeting-ui` `pom.xml` file, using a property called `stubrunner.ids`. This property can accept a list of stubrunner ids, but for this tutorial, we only have one: ```xml ... io.pivotal:fortune-service:1.0.0.M1-20180102_203542-VERSION:stubs:10000 ``` Spring Cloud Pipelines will use this information in two ways: . It will provide this information to the stub runner app via the app's environment variables - Spring Cloud Pipelines will aslo provide the `$REPO_WITH_BINARIES` as an env var for the stub runner app - The stub runner app will use this information to download the stub from Bintray and expose it on the specified port . It will open the additional port specified on the stub runner app and map a new route to it - The format for each route will be `----.` - In our example, this would be `stubrunner-cyi-test-greeting-ui-10000.cfapps.io` Since we bound our stub runner app to `service-registry` (Eureka), the stub runner app will register the stub URL under the application name `FORTUNE-SERVICE` on Eureka: image::{cf-migration-root-docs}/greeting_ui_stub_runner_eureka_registration.png[title=""greeting-ui Stub Runner Eureka Registration""] This completes the process of configuring the standalone stub runner application. NOTE: The port configuration may be automated by Spring Cloud Pipelines in the future, such that it will not be necessary to include the port in the `stubrunner.ids`, but for the moment, we are required to specify the port each stub should use. *Edit smoke tests to align with the contract* Finally, we edit our smoke tests for `greeting-ui` to ensure the response does *not* contain the hystrix fallback, since we are noe expecting a response from the stub. ```java package smoke; import org.assertj.core.api.BDDAssertions; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestTemplate; @RunWith(SpringRunner.class) @SpringBootTest(classes = SmokeTests.class, webEnvironment = SpringBootTest.WebEnvironment.NONE) @EnableAutoConfiguration public class SmokeTests { @Value(""${application.url}"") String applicationUrl; RestTemplate restTemplate = new RestTemplate(); @Test public void should_return_a_fortune() { ResponseEntity response = this.restTemplate .getForEntity(""http://"" + this.applicationUrl + ""/"", String.class); BDDAssertions.then(response.getStatusCodeValue()).isEqualTo(200); // Filter out the known Hystrix fallback response BDDAssertions.then(response.getBody()).doesNotContain(""This fortune is no good. Try another.""); } } ``` In this case, in contrast to the integration test we created earlier for `greeting-ui`, we do not include `@AutoConfigureStubRunner` since we are using a standalone stub runner application. ===== 3.9 Push changes to GitHub Push contract-based changes for `greeting-ui`. You should be pushing the following new or modified files: * pom.xml * sc-pipelines.yml * sc-pipelines/manifest-stubrunner.yml * src/test/java/io/pivotal/fortune/FortuneServiceTests.java * src/test/java/smoke/SmokeTests.java At this point, we can run through the full pipeline for `greeting-ui` and leverage the contract-based stub in both the build and test environments. ===== Stage 3 Recap What have we accomplished? By implementing a contract-driven approach with auto-generation of tests and stubs, we have introduced a clean, structured, and reliable way to define, communicate, document, manage and test APIs * Inter-team communication will be simpler - Consumer and producer teams can now communicate requirements through codified contracts - The inventory of contracts serves as a record and reference for the agreed upon APIs * Developer productivity will increase - Producers can quickly and easily generate contract-based stubs - Consumers no longer have to manually stub out APIs and write tests with arbitrary hard-coded responses - instead they can use the auto-generated stubs and test for contract-based responses - Both producers and consumers can validate they are compliant with the contract - Producers can verify backward compatibility of API changes - Troubleshooting will be easier - Failure and feedback will be faster === Conclusion This concludes the tutorial on migrating apps for Spring Cloud Pipelines for Cloud Foundry. Moving forward, the refactoring work needed here can be incorporated into your and/or your team's standard practices. In short: *Good:* * Use maven or gradle wrappers * Include a Cloud Foundry manifest file in your app repo * Include a pipeline descriptor (`sc-manifest.yml`) in your app repo * Create an empty `version` branch in your app repo * Include artifact repository configuration in the pom.xml file * Align your Cloud Foundry spaces with Spring Cloud Pipelines model (isolated test space, shared stage and prod) *Better* * Include default, apicompatibility, smoke, and e2e profiles in the pom.xml file * Organize tests accordingly in your app repo *Best* * Use a database migration tool like flyway * Use contract-based API programming Implementing all the *""good""* practices above already positions you to instantly create pipelines for your apps usign Spring Cloud Pipelines. This is a huge win in terms of consistency and productivity, and standardization across development teams. Of course, this is an open source project, so it can be modified to meet your needs. Implementing the *""better""* practices will ensure the proper tests get run at the proper time. At that point you can add as much test coverage as you need to have high confidence in your pipelines. Implementing the *""best""* practices will give you additional confidence in your pipeline and encourage better programming practices for database version and API management across development teams. It will also give you higher confidence in your pipelines and enable you to avoid the cumbersome business of rolling back a database. Happy coding! ",16208,True,2809.148711728697,median "= Microsoft Service Bus Connector 2.2 Reference - Mule 4 :page-aliases: connectors::ms-service-bus/ms-service-bus-connector-reference.adoc Support Category: https://www.mulesoft.com/legal/versioning-back-support-policy#anypoint-connectors[Select] Release Notes: xref:release-notes::connector/ms-service-bus-connector-release-notes-mule-4.adoc[Microsoft Service Bus Connector Release Notes] NOTE: This connector supports connecting only to the Microsoft Windows Service Bus on-premises solution. To connect to Microsoft Azure Service Bus, use https://www.mulesoft.com/exchange/com.mulesoft.connectors/mule-azure-service-bus-connector[Anypoint Connector for Azure Service Bus]. == Configurations --- [[config]] === Default Configuration ==== Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required |Name | String | Name for this configuration. Connectors reference the configuration with this name. | | x | Connection a| * <> * <> * <> | Connection types to provide to this configuration | | x | Encoding a| String | Default encoding of the Message body to use if the message doesn't communicate it | | | Content Type a| String | Default contentType of the Message body to use if the message doesn't communicate it | `/` | | Expiration Policy a| <> | Configures the minimum amount of time that a dynamic configuration instance can remain idle before Mule considers it eligible for expiration. This does not mean that the instance expires at the exact moment that it becomes eligible. Mule purges the instances as appropriate. | | | Ack Mode a| Enumeration, one of: ** IMMEDIATE ** AUTO ** MANUAL ** DUPS_OK | The `org.mule.jms.commons.api.config.ConsumerAckMode` to use when consuming a message. Override this setting at the message source level. This attribute must be `IMMEDIATE` if `transactionType` is `LOCAL` or `MULTI` | `AUTO` | | Consumer Type a| One of: * <> * <> | The ConsumerType to use by default when consuming a Message. Override this setting at the message source level. | | | Persistent Delivery a| Boolean | Sets the default value for the Message#getJMSDeliveryMode. If true, the DeliveryMode#PERSISTENT mode is used, which instructs the JMS provider to take extra care to insure the message is not lost in transit due to a JMS provider failure. | false | | Priority a| Number | Defines the default Message#getJMSPriority to use when sending messages | 4 | | Time To Live a| Number | Defines the default time the message is in the broker before it expires and is discarded | 0 | | Time To Live Unit a| Enumeration, one of: ** NANOSECONDS ** MICROSECONDS ** MILLISECONDS ** SECONDS ** MINUTES ** HOURS ** DAYS | A TimeUnit which qualifies the #timeToLive attribute. Defaults to MILLISECONDS | MILLISECONDS | | Disable Message Id a| Boolean | Defines the default value to use when producing messages, for disabling the Message#getJMSMessageID generation in the broker. Depending on the provider it may or may not have effect | false | | Disable Message Timestamp a| Boolean | Defines the default value to use, when producing messages, for disable Message#getJMSTimestamp generation in the broker. Depending on the provider it may or may not have effect. | false | | Delivery Delay a| Number | Determines the Message delivery delay time which is calculated by adding the deliveryDelay value specified on the send method to the time the message was sent. Only used in JMS_2_0 | | | Delivery Delay Unit a| Enumeration, one of: ** NANOSECONDS ** MICROSECONDS ** MILLISECONDS ** SECONDS ** MINUTES ** HOURS ** DAYS | A TimeUnit which qualifies the #deliveryDelay attribute. Defaults to MILLISECONDS | MILLISECONDS | | Jms Type a| String | A message JMSType identifier supplied by a client when a message is sent. | | |=== ==== Connection Types [[config_shared-access-signature]] ===== Shared Access Signature (Deprecated) ====== Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Skip connectivity test a| Boolean | (Optional) Skips the connectivity test at connector startup (use this if your access policy is restricted). | false | | Max Connections a| Number | Maximum number of connections to keep in pool for the producer to reuse. If set to `-1`, a new connection is created every time. | -1 | | Caching Strategy a| One of: * no-caching * <> | Strategy to use for caching sessions and connections | | | Service Namespace a| String | | | x | Storage Account Name a| String | (Optional) The account name of the Blob Storage to use to store large messages. | | | Storage Access Key a| String | (Optional) The account key of the Blob Storage to use to store large messages. | | | Container Name a| String | (Optional) The container name in the Blob Storage to use to store large messages. If this parameter is not provided, a default container is created. | | | Shared Access Signature a| String | | | | SAS tokens provider a| SharedAccessSignatureProvider | Provider instance that provides SAS tokens when required. | | | SAS tokens list a| Array of String | List of SAS tokens to use when required. | | | Max redeliveries a| Number | Controls when an incoming message is rejected based on the number of times it was redelivered. The default value is -1 (disabled). A value of `0` means that no message redeliveries are accepted. A value of `5` means that a message is redelivered five times, and so forth. | -1 | | Outcome a| Enumeration, one of: ** ACCEPTED ** REJECTED ** RELEASED ** MODIFIED_FAILED ** MODIFIED_FAILED_UNDELIVERABLE | Controls the outcome to apply to a message that is rejected due to exceeding the configured maxRedeliveries value. | MODIFIED_FAILED_UNDELIVERABLE | | Reconnection a| <> | When the application is deployed, a connectivity test is performed on all connectors. If set to `true`, deployment fails if the test doesn't pass after exhausting the associated reconnection strategy. | `true` | |=== [[config_username-password]] ===== Username Password (Deprecated) ====== Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Skip connectivity test a| Boolean | (Optional) Skips the connectivity test at connector startup (use this if your access policy is restricted). | false | | Max Connections a| Number | Maximum number of connections to keep in pool for the producer to reuse. If set to `-1`, a new connection is created every time. | -1 | | Caching Strategy a| One of: * no-caching * <> | The strategy to use for caching sessions and connections | | | Service Namespace a| String | | | x | Storage Account Name a| String | (Optional) The account name of the Blob Storage to use to store large messages | | | Storage Access Key a| String | (Optional) The account key of the Blob Storage to use to store large messages. | | | Container Name a| String | (Optional) The container name in the Blob Storage to use to store large messages. If this parameter is not provided, a default container is created. | | | Shared Access Key Name a| String | | | x | Shared Access Key a| String | | | x | Proxy a| <> | | | | Security a| <> | | | | Advanced a| <> | | | | Max redeliveries a| Number | Controls when an incoming message is rejected based on the number of times it was redelivered. The default value is -1 (disabled). A value of `0` means that no message redeliveries are accepted. A value of `5` means that a message is redelivered five times, and so forth. | -1 | | Outcome a| Enumeration, one of: ** ACCEPTED ** REJECTED ** RELEASED ** MODIFIED_FAILED ** MODIFIED_FAILED_UNDELIVERABLE | Controls the outcome to apply to a message that is rejected due to exceeding the configured maxRedeliveries value. | MODIFIED_FAILED_UNDELIVERABLE | | Reconnection a| <> | When the application is deployed, a connectivity test is performed on all connectors. If set to `true`, deployment fails if the test doesn't pass after exhausting the associated reconnection strategy. | `true` | |=== [[config_windows]] ===== Windows ====== Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Skip connectivity test a| Boolean | (Optional) Skips the connectivity test at connector startup (use this if your access policy is restricted). | false | | Max Connections a| Number | Maximum number of connections to keep in pool for the producer to reuse. If set to `-1`, a new connection is created every time. | -1 | | Caching Strategy a| One of: * no-caching * <> | The strategy to use for caching sessions and connections | | | Service Namespace a| String | | | x | Username a| String | | | x | Password a| String | | | x | Fully Qualified Domain Name a| String | | | x | Port a| String | | 9355 | | Disable SSL certificate validation a| Boolean | | false | | Idle timeout a| Number | The idle timeout in milliseconds after which the connection fails if the peer sends no AMQP frames. | 60000 | | Proxy a| <> | | | | Security a| <> | | | | Advanced a| <> | | | | Max redeliveries a| Number | Controls when an incoming message is rejected based on the number of times it was redelivered. The default value is -1 (disabled). A value of `0` means that no message redeliveries are accepted. A value of `5` means that a message is redelivered five times, and so forth. | -1 | | Outcome a| Enumeration, one of: ** ACCEPTED ** REJECTED ** RELEASED ** MODIFIED_FAILED ** MODIFIED_FAILED_UNDELIVERABLE | Controls the outcome to apply to a message that is rejected due to exceeding the configured maxRedeliveries value. | MODIFIED_FAILED_UNDELIVERABLE | | Reconnection a| <> | When the application is deployed, a connectivity test is performed on all connectors. If set to `true`, deployment fails if the test doesn't pass after exhausting the associated reconnection strategy. | `true` | |=== == Operations * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> === Associated Sources * <> [[ack]] === Ack `` Allows the user to perform an ACK when the JmsAckMode#MANUAL mode is elected while consuming the Message. As per JMS Spec, performing an ACK over a single Message automatically works as an ACK for all the Messages produced in the same JmsSession. ==== Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | Name of the configuration to use | | x | Ack Id a| String | The AckId of the Message to ACK | `#[payload]` | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== === For Configurations * <> ==== Throws * SERVICEBUS:INVALID_TOKEN * SERVICEBUS:RETRY_EXHAUSTED * SERVICEBUS:CONNECTION_EXCEPTION * SERVICEBUS:UNKNOWN * SERVICEBUS:AMQP_ERROR * SERVICEBUS:CONNECTIVITY * SERVICEBUS:REST_ERROR == Types [[Proxy]] === Proxy [%header,cols=""20s,25a,30a,15a,10a""] |=== | Field | Type | Description | Default Value | Required | Host a| String | Host of the proxy | | | Port a| String | Port of the proxy | | | Username a| String | Username of the proxy | | | Password a| String | Password for the proxy | | |=== [[Advanced]] === Advanced [%header,cols=""20s,25a,30a,15a,10a""] |=== | Name | Type | Description | Default Value | Required | Read Timeout a| Number | Amount of time that the client waits for a response before it times out. Zero (`0`) specifies that the client waits indefinitely. | 60000 | | Read Timeout Unit a| Enumeration, one of: ** NANOSECONDS ** MICROSECONDS ** MILLISECONDS ** SECONDS ** MINUTES ** HOURS ** DAYS | Time unit for Read Timeout. | MILLISECONDS | {nbsp} | Connection Timeout a| Number | The amount of time that the client attempts to establish a connection before it times out. Zero (`0`) specifies that the client continues to attempt to open a connection indefinitely. | 60000 | {nbsp} | Connection Timeout Unit a| Enumeration, one of: ** NANOSECONDS ** MICROSECONDS ** MILLISECONDS ** SECONDS ** MINUTES ** HOURS ** DAYS | Time unit for Connection Timeout | MILLISECONDS | {nbsp} | | | |=== [[Tls]] === TLS [%header,cols=""20s,25a,30a,15a,10a""] |=== | Field | Type | Description | Default Value | Required | Enabled Protocols a| String | A comma-separated list of protocols enabled for this context | | | Enabled Cipher Suites a| String | A comma-separated list of cipher suites enabled for this context | | | Trust Store a| <> | | | | Key Store a| <> | | | | Revocation Check a| * <> * <> * <> | | | |=== [[TrustStore]] === Trust Store [%header,cols=""20s,25a,30a,15a,10a""] |=== | Field | Type | Description | Default Value | Required | Path a| String | Location, which is resolved relative to the current classpath and file system if possible, of the truststore | | | Password a| String | Password used to protect the truststore | | | Type a| String | Type of store used | | | Algorithm a| String | Algorithm used by the truststore | | | Insecure a| Boolean | If `true`, no certificate validations are performed, rendering connections vulnerable to attacks. Use at your own risk. | | |=== [[KeyStore]] === Key Store [%header,cols=""20s,25a,30a,15a,10a""] |=== | Field | Type | Description | Default Value | Required | Path a| String | Location, which is resolved relative to the current classpath and file system, if possible, of the keystore | | | Type a| String | Type of store used | | | Alias a| String | When the keystore contains many private keys, this attribute indicates the alias of the key to use. If not defined, the first key in the file is used by default. | | | Key Password a| String | Password used to protect the private key | | | Password a| String | Password used to protect the keystore | | | Algorithm a| String | Algorithm used by the keystore | | |=== [[standard-revocation-check]] === Standard Revocation Check [%header,cols=""20s,25a,30a,15a,10a""] |=== | Field | Type | Description | Default Value | Required | Only End Entities a| Boolean | Only verify the last element of the certificate chain. | | | Prefer Crls a| Boolean | Try CRL instead of OCSP first. | | | No Fallback a| Boolean | Do not use the secondary checking method (the one not previously selected). | | | Soft Fail a| Boolean | Avoid verification failure when the revocation server can't be reached or is busy. | | |=== [[queueCreate]] === Queue Create `` Creates a queue in the service bus instance ==== Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use | | x | Queue Path a| String | The name of the queue | | x | Queue Description a| <> | An InternalQueueDescription object containing the desired values of the queue's properties to create | `#[payload]` | | Target Variable a| String | Name of a variable that stores the operation's output | | | Target Value a| String | An expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors | | |=== ==== Output [%autowidth.spread] |=== |Type |<> |=== === For Configurations * <> ==== Throws * SERVICEBUS:INVALID_TOKEN * SERVICEBUS:RETRY_EXHAUSTED * SERVICEBUS:CONNECTION_EXCEPTION * SERVICEBUS:UNKNOWN * SERVICEBUS:AMQP_ERROR * SERVICEBUS:CONNECTIVITY * SERVICEBUS:REST_ERROR [[queueDelete]] === Queue Delete `` Deletes the specified queue in the service bus instance ==== Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | Name of the configuration to use | | x | Queue Path a| String | Name of the queue | `#[payload]` | | Reconnection Strategy a| * <> * <> | Retry strategy in case of connectivity errors | | |=== === For Configurations * <> ==== Throws * SERVICEBUS:INVALID_TOKEN * SERVICEBUS:RETRY_EXHAUSTED * SERVICEBUS:CONNECTION_EXCEPTION * SERVICEBUS:UNKNOWN * SERVICEBUS:AMQP_ERROR * SERVICEBUS:CONNECTIVITY * SERVICEBUS:REST_ERROR [[queueGet]] === Queue Get `` This operation retrieves the specified queue from the Service Bus instance. ==== Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | Name of the configuration to use | | x | Queue Path a| String | Name of the queue | `#[payload]` | | Target Variable a| String | Name of a variable that stores the operation's output | | | Target Value a| String | An expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` | | Reconnection Strategy a| * <> * <> | Retry strategy in case of connectivity errors | | |=== ==== Output [%autowidth.spread] |=== |Type |<> |=== === For Configurations * <> ==== Throws * SERVICEBUS:INVALID_TOKEN * SERVICEBUS:RETRY_EXHAUSTED * SERVICEBUS:CONNECTION_EXCEPTION * SERVICEBUS:UNKNOWN * SERVICEBUS:AMQP_ERROR * SERVICEBUS:CONNECTIVITY * SERVICEBUS:REST_ERROR [[queueSend]] === Queue Send `` This operation sends a message to a queue. ==== Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Destination Queue a| String | The name of the queue. | | x | Transactional Action a| Enumeration, one of: ** ALWAYS_JOIN ** JOIN_IF_POSSIBLE ** NOT_SUPPORTED | Type of transactional action. | NOT_SUPPORTED | | Send Correlation Id a| Enumeration, one of: ** AUTO ** ALWAYS ** NEVER | Correlation strategy id for operation. | AUTO | | Body a| Any | The body of the Message | `#[payload]` | | JMS Type a| String | The JMSType identifier header of the Message | | | Correlation ID a| String | The JMSCorrelationID header of the Message | | | Send Content Type a| Boolean | Whether or not the body content type should be sent as a property | true | | Content Type a| String | The content type of the message's body | | | Send Encoding a| Boolean | Whether or not the body outboundEncoding should be sent as a Message property | true | | Encoding a| String | The encoding of the message's body | | | Reply To a| <> | The destination where a reply to this Message should be sent | | | User Properties a| Object | The custom user properties to set for this message | | | JMSX Properties a| <> | The JMSX properties to set for this message | | | Persistent Delivery a| Boolean | If true, the Message is sent using the PERSISTENT JMSDeliveryMode. | | | Priority a| Number | The default JMSPriority value to use when sending the message. | | | Time To Live a| Number | Defines the default time the message is in the broker before it expires and is discarded. | | | Time To Live Unit a| Enumeration, one of: ** NANOSECONDS ** MICROSECONDS ** MILLISECONDS ** SECONDS ** MINUTES ** HOURS ** DAYS | Time unit to use in the timeToLive configurations. | | | Disable Message Id a| Boolean | If true, flags the message to avoid generating its MessageID. | | | Disable Message Timestamp a| Boolean | If true, flags the message to avoid generating its sent Timestamp. | | | Delivery Delay a| Number | Only used by JMS 2.0. Sets the delivery delay to apply to postpone the message delivery. | | | Delivery Delay Unit a| Enumeration, one of: ** NANOSECONDS ** MICROSECONDS ** MILLISECONDS ** SECONDS ** MINUTES ** HOURS ** DAYS | Time unit to use in the deliveryDelay configurations. | | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== === For Configurations * <> ==== Throws * SERVICEBUS:INVALID_TOKEN * SERVICEBUS:RETRY_EXHAUSTED * SERVICEBUS:CONNECTION_EXCEPTION * SERVICEBUS:UNKNOWN * SERVICEBUS:AMQP_ERROR * SERVICEBUS:CONNECTIVITY * SERVICEBUS:REST_ERROR [[queueUpdate]] === Queue Update `` This operation updates the specified queue in the Service Bus instance. ==== Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Queue Path a| String | The name of the queue | | x | Queue Description a| <> | An InternalQueueDescription oject containing the desired values of the queue's properties that will be updated | `#[payload]` | | Target Variable a| String | The name of a variable that stores the operation's output. | | | Target Value a| String | An expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== ==== Output [%autowidth.spread] |=== |Type |<> |=== === For Configurations * <> ==== Throws * SERVICEBUS:INVALID_TOKEN * SERVICEBUS:RETRY_EXHAUSTED * SERVICEBUS:CONNECTION_EXCEPTION * SERVICEBUS:UNKNOWN * SERVICEBUS:AMQP_ERROR * SERVICEBUS:CONNECTIVITY * SERVICEBUS:REST_ERROR [[queues]] === Queues `` This operation retrieves all existing queues from the Service Bus instance. ==== Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Target Variable a| String | The name of a variable that stores the operation's output. | | | Target Value a| String | An expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== ==== Output [%autowidth.spread] |=== |Type |Array of <> |=== === For Configurations * <> ==== Throws * SERVICEBUS:INVALID_TOKEN * SERVICEBUS:RETRY_EXHAUSTED * SERVICEBUS:CONNECTION_EXCEPTION * SERVICEBUS:UNKNOWN * SERVICEBUS:AMQP_ERROR * SERVICEBUS:CONNECTIVITY * SERVICEBUS:REST_ERROR [[recoverSession]] === Recover Session `` Allows the user to recover a session when the JmsAckMode#MANUAL mode is elected while consuming the message. Per the JMS Spec, performing a session recover automatically redelivers all the consumed messages that were not acknowledged before the recover. ==== Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use | | x | Ack Id a| String | The AckId of the Message Session to recover | `#[payload]` | | Reconnection Strategy a| * <> * <> | Retry strategy in case of connectivity errors | | |=== === For Configurations * <> ==== Throws * SERVICEBUS:INVALID_TOKEN * SERVICEBUS:RETRY_EXHAUSTED * SERVICEBUS:CONNECTION_EXCEPTION * SERVICEBUS:UNKNOWN * SERVICEBUS:AMQP_ERROR * SERVICEBUS:CONNECTIVITY * SERVICEBUS:REST_ERROR [[ruleCreate]] === Rule Create `` This operation creates a rule for the specified topic and subscription. ==== Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | Name of the configuration to use | | x | Rule Path a| String | Name of the rule to create | | x | Rule Description a| <> | An InternalRuleDescription object containing the desired values of the new rule's properties | `#[payload]` | | Topic Path a| String | Name of the topic that contains the subscription for which to create a rule | | x | Subscription Path a| String | Name of the subscription that contains the new rule | | | Target Variable a| String | Name of a variable that stores the operation's output | | | Target Value a| String | Expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors | | |=== ==== Output [%autowidth.spread] |=== |Type |<> |=== === For Configurations * <> ==== Throws * SERVICEBUS:INVALID_TOKEN * SERVICEBUS:RETRY_EXHAUSTED * SERVICEBUS:CONNECTION_EXCEPTION * SERVICEBUS:UNKNOWN * SERVICEBUS:AMQP_ERROR * SERVICEBUS:CONNECTIVITY * SERVICEBUS:REST_ERROR [[ruleDelete]] === Rule Delete `` This operation deletes a rule from the specified topic and subscription. ==== Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | Name of the configuration to use | | x | Topic Path a| String | Name of the topic that contains the subscription from which to delete the rule | | x | Subscription Path a| String | Name of the subscription from which to delete the rule | | x | Rule Path a| String | Name of the rule to delete | | x | Reconnection Strategy a| * <> * <> | Retry strategy in case of connectivity errors | | |=== === For Configurations * <> ==== Throws * SERVICEBUS:INVALID_TOKEN * SERVICEBUS:RETRY_EXHAUSTED * SERVICEBUS:CONNECTION_EXCEPTION * SERVICEBUS:UNKNOWN * SERVICEBUS:AMQP_ERROR * SERVICEBUS:CONNECTIVITY * SERVICEBUS:REST_ERROR [[ruleGet]] === Rule Get `` This operation retrieves a rule from the specified topic and subscription. ==== Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | Name of the configuration to use | | x | Topic Path a| String | Name of the topic that contains the subscription from which to retrieve the rule || x | Subscription Path a| String | Name of the subscription from which to retrieve the rule | | x | Rule Path a| String | Name of the rule to retrieve | | x | Target Variable a| String | Name of a variable that stores the operation's output | | | Target Value a| String | An expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors | | |=== ==== Output [%autowidth.spread] |=== |Type |<> |=== === For Configurations * <> ==== Throws * SERVICEBUS:INVALID_TOKEN * SERVICEBUS:RETRY_EXHAUSTED * SERVICEBUS:CONNECTION_EXCEPTION * SERVICEBUS:UNKNOWN * SERVICEBUS:AMQP_ERROR * SERVICEBUS:CONNECTIVITY * SERVICEBUS:REST_ERROR [[ruleUpdate]] === Rule Update `` This operation updates a rule from the specified topic and subscription. ==== Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use | | x | Rule Description a| <> | An InternalRuleDescription object containing the desired values for the rule's updated properties | `#[payload]` | | Topic Path a| String | The name of the topic that contains the subscription for which to update the rule | | x | Subscription Path a| String | The name of the subscription for which to update the rule | | x | Rule Path a| String | The name of the rule to update | | x | Target Variable a| String | The name of a variable that stores the operation's output | | | Target Value a| String | An expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors | | |=== ==== Output [%autowidth.spread] |=== |Type |<> |=== === For Configurations * <> ==== Throws * SERVICEBUS:INVALID_TOKEN * SERVICEBUS:RETRY_EXHAUSTED * SERVICEBUS:CONNECTION_EXCEPTION * SERVICEBUS:UNKNOWN * SERVICEBUS:AMQP_ERROR * SERVICEBUS:CONNECTIVITY * SERVICEBUS:REST_ERROR [[rules]] === Rules `` Retrieves all rules from the specified topic and subscription ==== Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use | | x | Topic Path a| String | The name of the topic that contains the subscription from which to retrieve all rules | | x | Subscription Path a| String | The name of the subscription from which to retrieve all rules | | | Target Variable a| String | The name of a variable that stores the operation's output | | | Target Value a| String | An expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors | | |=== ==== Output [%autowidth.spread] |=== |Type |Array of <> |=== === For Configurations * <> ==== Throws * SERVICEBUS:INVALID_TOKEN * SERVICEBUS:RETRY_EXHAUSTED * SERVICEBUS:CONNECTION_EXCEPTION * SERVICEBUS:UNKNOWN * SERVICEBUS:AMQP_ERROR * SERVICEBUS:CONNECTIVITY * SERVICEBUS:REST_ERROR [[subscriptionCreate]] === Subscription Create `` Creates a subscription in the specified topic ==== Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use | | x | Topic Path a| String | The name of the topic to contain the new subscription | | x | Subscription Path a| String | The name of the subscription to create | | x | Subscription Description a| <> | An InternalSubscriptionDescription object containing the desired values of the new subscription's properties | `#[payload]` | | Target Variable a| String | The name of a variable that stores the operation's output | | | Target Value a| String | An expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors | | |=== ==== Output [%autowidth.spread] |=== |Type |<> |=== === For Configurations * <> ==== Throws * SERVICEBUS:INVALID_TOKEN * SERVICEBUS:RETRY_EXHAUSTED * SERVICEBUS:CONNECTION_EXCEPTION * SERVICEBUS:UNKNOWN * SERVICEBUS:AMQP_ERROR * SERVICEBUS:CONNECTIVITY * SERVICEBUS:REST_ERROR [[subscriptionDelete]] === Subscription Delete `` Deletes a subscription from the specified topic ==== Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use | | x | Topic Path a| String | The name of the topic from which to delete the subscription | | x | Subscription Path a| String | The name of the subscription to delete | | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors | | |=== === For Configurations * <> ==== Throws * SERVICEBUS:INVALID_TOKEN * SERVICEBUS:RETRY_EXHAUSTED * SERVICEBUS:CONNECTION_EXCEPTION * SERVICEBUS:UNKNOWN * SERVICEBUS:AMQP_ERROR * SERVICEBUS:CONNECTIVITY * SERVICEBUS:REST_ERROR [[subscriptionGet]] === Subscription Get `` Retrieves a subscription from the specified topic ==== Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use | | x | Topic Path a| String | The name of the topic from which to retrieve the subscription | | x | Subscription Path a| String | The name of the subscription to retrieve | | | Target Variable a| String | The name of a variable that stores the operation's output | | | Target Value a| String | An expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors | | |=== ==== Output [%autowidth.spread] |=== |Type |<> |=== === For Configurations * <> ==== Throws * SERVICEBUS:INVALID_TOKEN * SERVICEBUS:RETRY_EXHAUSTED * SERVICEBUS:CONNECTION_EXCEPTION * SERVICEBUS:UNKNOWN * SERVICEBUS:AMQP_ERROR * SERVICEBUS:CONNECTIVITY * SERVICEBUS:REST_ERROR [[subscriptionUpdate]] === Subscription Update `` Updates a subscription from the specified topic ==== Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use | | x | Subscription Description a| <> | An InternalSubscriptionDescription object containing the desired values of the subscription's updated properties| `#[payload]` | | Topic Path a| String | The name of the topic from which to update the subscription | | x | Subscription Path a| String | The name of the subscription to update | | | Target Variable a| String | The name of a variable that stores the operation's output | | | Target Value a| String | An expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors | | |=== ==== Output [%autowidth.spread] |=== |Type |<> |=== === For Configurations * <> ==== Throws * SERVICEBUS:INVALID_TOKEN * SERVICEBUS:RETRY_EXHAUSTED * SERVICEBUS:CONNECTION_EXCEPTION * SERVICEBUS:UNKNOWN * SERVICEBUS:AMQP_ERROR * SERVICEBUS:CONNECTIVITY * SERVICEBUS:REST_ERROR [[subscriptions]] === Subscriptions `` Retrieves all subscriptions from the specified topic ==== Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use | | x | Topic Path a| String | The name of the topic from which to retrieve all subscriptions | `#[payload]` | | Target Variable a| String | The name of a variable that stores the operation's output | | | Target Value a| String | An expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== ==== Output [%autowidth.spread] |=== |Type |Array of <> |=== === For Configurations * <> ==== Throws * SERVICEBUS:INVALID_TOKEN * SERVICEBUS:RETRY_EXHAUSTED * SERVICEBUS:CONNECTION_EXCEPTION * SERVICEBUS:UNKNOWN * SERVICEBUS:AMQP_ERROR * SERVICEBUS:CONNECTIVITY * SERVICEBUS:REST_ERROR [[topicCreate]] === Topic Create `` Creates a topic in the service bus instance ==== Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Topic Path a| String | The name of the topic | | x | Topic Description a| <> | An InternalTopicDescription object containing the desired values of the topic's properties that will be created. | `#[payload]` | | Target Variable a| String | The name of a variable that stores the operation's output. | | | Target Value a| String | An expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== ==== Output [%autowidth.spread] |=== |Type |<> |=== === For Configurations * <> ==== Throws * SERVICEBUS:INVALID_TOKEN * SERVICEBUS:RETRY_EXHAUSTED * SERVICEBUS:CONNECTION_EXCEPTION * SERVICEBUS:UNKNOWN * SERVICEBUS:AMQP_ERROR * SERVICEBUS:CONNECTIVITY * SERVICEBUS:REST_ERROR [[topicDelete]] === Topic Delete `` Deletes the specified topic from the service bus instance ==== Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Topic Path a| String | The name of the topic | `#[payload]` | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== === For Configurations * <> ==== Throws * SERVICEBUS:INVALID_TOKEN * SERVICEBUS:RETRY_EXHAUSTED * SERVICEBUS:CONNECTION_EXCEPTION * SERVICEBUS:UNKNOWN * SERVICEBUS:AMQP_ERROR * SERVICEBUS:CONNECTIVITY * SERVICEBUS:REST_ERROR [[topicGet]] === Topic Get `` Retrieves the specified topic from the service bus instance ==== Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Topic Path a| String | The name of the topic | `#[payload]` | | Target Variable a| String | The name of a variable that stores the operation's output. | | | Target Value a| String | An expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== ==== Output [%autowidth.spread] |=== |Type |<> |=== === For Configurations * <> ==== Throws * SERVICEBUS:INVALID_TOKEN * SERVICEBUS:RETRY_EXHAUSTED * SERVICEBUS:CONNECTION_EXCEPTION * SERVICEBUS:UNKNOWN * SERVICEBUS:AMQP_ERROR * SERVICEBUS:CONNECTIVITY * SERVICEBUS:REST_ERROR [[topicSend]] === Topic Send `` Sends a message to a Topic ==== Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Destination Topic a| String | The name of the topic. | | x | Transactional Action a| Enumeration, one of: ** ALWAYS_JOIN ** JOIN_IF_POSSIBLE ** NOT_SUPPORTED | Type of transactional action. | | x | Send Correlation Id a| Enumeration, one of: ** AUTO ** ALWAYS ** NEVER | Correlation strategy id for operation. | | x | Body a| Any | The body of the Message | `#[payload]` | | JMS Type a| String | The JMSType identifier header of the Message | | | Correlation ID a| String | The JMSCorrelationID header of the Message | | | Send Content Type a| Boolean | Whether or not the body content type should be sent as a property | true | | Content Type a| String | The content type of the message's body | | | Send Encoding a| Boolean | Whether or not the body outboundEncoding should be sent as a Message property | true | | Encoding a| String | The encoding of the message's body | | | Reply To a| <> | The destination where a reply to this Message should be sent | | | User Properties a| Object | The custom user properties to set for this message | | | JMSX Properties a| <> | The JMSX properties to set for this message | | | Persistent Delivery a| Boolean | If true, the Message is sent using the PERSISTENT JMSDeliveryMode. | | | Priority a| Number | The default JMSPriority value to use when sending the message. | | | Time To Live a| Number | Defines the default time the message is in the broker before it expires and is discarded. | | | Time To Live Unit a| Enumeration, one of: ** NANOSECONDS ** MICROSECONDS ** MILLISECONDS ** SECONDS ** MINUTES ** HOURS ** DAYS | Time unit to use in the timeToLive configurations. | | | Disable Message Id a| Boolean | If true, flags the message to avoid generating its MessageID. | | | Disable Message Timestamp a| Boolean | If true, flags the message to avoid generating its sent Timestamp. | | | Delivery Delay a| Number | Only used by JMS 2.0. Sets the delivery delay to apply to postpone the message delivery. | | | Delivery Delay Unit a| Enumeration, one of: ** NANOSECONDS ** MICROSECONDS ** MILLISECONDS ** SECONDS ** MINUTES ** HOURS ** DAYS | Time unit to use in the deliveryDelay configurations. | | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== === For Configurations * <> ==== Throws * SERVICEBUS:INVALID_TOKEN * SERVICEBUS:RETRY_EXHAUSTED * SERVICEBUS:CONNECTION_EXCEPTION * SERVICEBUS:UNKNOWN * SERVICEBUS:AMQP_ERROR * SERVICEBUS:CONNECTIVITY * SERVICEBUS:REST_ERROR [[topicUpdate]] === Topic Update `` Updates the specified topic from the service bus instance ==== Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Topic Path a| String | The name of the topic | | x | Topic Description a| <> | An InternalTopicDescription object containing the desired values of the topic's properties that will be updated. | `#[payload]` | | Target Variable a| String | The name of a variable that stores the operation's output. | | | Target Value a| String | An expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== ==== Output [%autowidth.spread] |=== |Type |<> |=== === For Configurations * <> ==== Throws * SERVICEBUS:INVALID_TOKEN * SERVICEBUS:RETRY_EXHAUSTED * SERVICEBUS:CONNECTION_EXCEPTION * SERVICEBUS:UNKNOWN * SERVICEBUS:AMQP_ERROR * SERVICEBUS:CONNECTIVITY * SERVICEBUS:REST_ERROR [[topics]] === Topics `` Retrieves all existing topics from the service bus instance ==== Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Target Variable a| String | The name of a variable that stores the operation's output. | | | Target Value a| String | An expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== ==== Output [%autowidth.spread] |=== |Type |Array of <> |=== === For Configurations * <> ==== Throws * SERVICEBUS:INVALID_TOKEN * SERVICEBUS:RETRY_EXHAUSTED * SERVICEBUS:CONNECTION_EXCEPTION * SERVICEBUS:UNKNOWN * SERVICEBUS:AMQP_ERROR * SERVICEBUS:CONNECTIVITY * SERVICEBUS:REST_ERROR == Sources [[listener]] === Listener `` ==== Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Ack Mode a| Enumeration, one of: ** IMMEDIATE ** AUTO ** MANUAL ** DUPS_OK | The Session ACK mode to use when consuming a message | | | Number Of Consumers a| Number | The number of concurrent consumers to use to receive JMS Messages | 1 | | Primary Node Only a| Boolean | Whether this source should be executed only on the primary node when running in a cluster | | | Redelivery Policy a| <> | Defines a policy for processing the redelivery of the same message | | | Source Type a| String | | | x | Destination a| String | | | x | Subscription a| String | | | x | Content Type a| String | | | | Encoding a| String | | | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | | Body a| Any | The body of the Message | `#[payload]` | | JMS Type a| String | The JMSType identifier header of the Message | | | Correlation ID a| String | The JMSCorrelationID header of the Message | | | Send Content Type a| Boolean | Whether or not the body content type should be sent as a property | true | | Content Type a| String | The content type of the message's body | | | Send Encoding a| Boolean | Whether or not the body outboundEncoding should be sent as a Message property | true | | Encoding a| String | The encoding of the message's body | | | Reply To a| <> | The destination where a reply to this Message should be sent | | | User Properties a| Object | The custom user properties to set for this message | | | JMSX Properties a| <> | The JMSX properties to set for this message | | | Persistent Delivery a| Boolean | Whether or not the delivery should be done with a persistent configuration | | | Priority a| Number | The default JMSPriority value to use when sending the message | | | Time To Live a| Number | Defines the default time the message is in the broker before it expires and is discarded | | | Time To Live Unit a| Enumeration, one of: ** NANOSECONDS ** MICROSECONDS ** MILLISECONDS ** SECONDS ** MINUTES ** HOURS ** DAYS | Time unit to use in the timeToLive configurations | | | Disable Message Id a| Boolean | If true, flags the message to avoid generating its MessageID | | | Disable Message Timestamp a| Boolean | If true, flags the message to avoid generating its sent Timestamp | | | Delivery Delay a| Number | Only used by JMS 2.0. Sets the delivery delay to apply to postpone the message delivery. | | | Delivery Delay Unit a| Enumeration, one of: ** NANOSECONDS ** MICROSECONDS ** MILLISECONDS ** SECONDS ** MINUTES ** HOURS ** DAYS | Time unit to use in the deliveryDelay configurations | | |=== ==== Output [%autowidth.spread] |=== |Type |Message | Attributes Type a| <> |=== === For Configurations * <> == Types [[Reconnection]] === Reconnection [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Fails Deployment a| Boolean | When the application is deployed, a connectivity test is performed on all connectors. If set to true, deployment fails if the test doesn't pass after exhausting the associated reconnection strategy. | | | Reconnection Strategy a| * <> * <> | The reconnection strategy to use. | | |=== [[reconnect]] === Reconnect [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Frequency a| Number | How often in milliseconds to reconnect. | | | Count a| Number | How many reconnection attempts to make. | | | blocking |Boolean |If false, the reconnection strategy runs in a separate, non-blocking thread. |true | |=== [[reconnect-forever]] === Reconnect Forever [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Frequency a| Number | How often in milliseconds to reconnect. | | | blocking |Boolean |If false, the reconnection strategy runs in a separate, non-blocking thread. |true | |=== [[ExpirationPolicy]] === Expiration Policy [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Max Idle Time a| Number | A scalar time value for the maximum amount of time a dynamic configuration instance should be allowed to be idle before it's considered eligible for expiration | | | Time Unit a| Enumeration, one of: ** NANOSECONDS ** MICROSECONDS ** MILLISECONDS ** SECONDS ** MINUTES ** HOURS ** DAYS | A time unit that qualifies the maxIdleTime attribute | | |=== [[ServiceBusJmsAttributes]] === Service Bus JMS Attributes [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Properties a| <> | | | x | Headers a| <> | | | x | Ack Id a| String | | | |=== [[JmsMessageProperties]] === JMS Message Properties [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | All a| Object | | | x | User Properties a| Object | | | x | Jms Properties a| Object | | | x | Jmsx Properties a| <> | | | x |=== [[JmsxProperties]] === JMSX Properties [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Jmsx User ID a| String | | | | Jmsx App ID a| String | | | | Jmsx Delivery Count a| Number | | | | Jmsx Group ID a| String | | | | Jmsx Group Seq a| Number | | | | Jmsx Producer TXID a| String | | | | Jmsx Consumer TXID a| String | | | | Jmsx Rcv Timestamp a| Number | | | |=== [[JmsHeaders]] === JMS Headers [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Destination a| <> | | | x | Delivery Mode a| Number | | | x | Expiration a| Number | | | x | Priority a| Number | | | x | Message Id a| String | | | | Timestamp a| Number | | | x | Correlation Id a| String | | | | Reply To a| <> | | | | Type a| String | | | x | Redelivered a| Boolean | | false | | Delivery Time a| Number | | | |=== [[RedeliveryPolicy]] === Redelivery Policy [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Max Redelivery Count a| Number | The maximum number of times a message can be redelivered and processed unsuccessfully before triggering process-failed-message | | | Use Secure Hash a| Boolean | Whether to use a secure hash algorithm to identify a redelivered message. | | | Message Digest Algorithm a| String | The secure hashing algorithm to use. | SHA-256 | | Id Expression a| String | Defines one or more expressions used to determine when a message has been redelivered. This property can be set only when useSecureHash is false. | | | Object Store a| Object Store | The object store where the redelivery counter for each message is going to be stored. | | |=== [[ServiceBusJmsDestination]] === Service Bus JMS Destination [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Destination a| String | | | x | Destination Type a| Enumeration, one of: ** QUEUE ** TOPIC | | QUEUE | |=== [[ServiceBusQueue]] === Service Bus Queue [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Author a| String | | | | Id a| String | | | | Link a| String | | | | Published a| Date | | | | Queue Description a| <> | | | | Title a| String | | | | Updated a| Date | | | |=== [[ServiceBusQueueDescription]] === Service Bus Queue Description [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Lock Duration a| String | Determines the amount of time in seconds in which a message should be locked for processing by a receiver. After this period, the message is unlocked and available for consumption by the next receiver. Settable only at queue creation time. Valid values: Range: 0 - 5 minutes. 0 means that the message is not locked. Format: PTx3Mx4S, where x1 number of days, x2 number of hours, x3 number of minutes, x4 number of seconds (Examples: PT5M (5 minutes), PT1M30S (1 minute, 30 seconds)). | PT1M | | Max Size In Megabytes a| Number | Specifies the maximum queue size in megabytes. Any attempt to enqueue a message that causes the queue to exceed this value fails. Valid values are: 1024, 2048, 3072, 4096, 5120 | 1024 | | Requires Duplicate Detection a| Boolean | Settable only at queue creation time. | false | | Requires Session a| Boolean | Settable only at queue creation time. If set to true, the queue will be session-aware and only SessionReceiver will be supported. Session-aware queues are not supported through REST. | false | | Dead Lettering On Message Expiration a| Boolean | This field controls how the Service Bus handles a message with an expired TTL. If it is enabled and a message expires, Service Bus moves the message from the queue into the queue's dead-letter sub-queue. If disabled, message is permanently deleted from the queue. Settable only at queue creation time. | false | | Enable Batched Operations a| Boolean | Enables or disables service-side batching behavior when performing operations for the specific queue. When enabled, Service Bus collects or batches multiple operations to the back end, to be more efficient with the connection. If you want lower operation latency, you can disable this feature. | true | | Default Message Time To Live a| String | Depending on whether DeadLettering is enabled, a message is automatically moved to the DeadLetterQueue or deleted if it has been stored in the queue for longer than the specified time. This value is overwritten by a TTL specified on the message if and only if the message TTL is smaller than the TTL set on the queue. This value is immutable after the queue has been created. Format: Px1DTx2Hx3Mx4S, where x1 number of days, x2 number of hours, x3 number of minutes, x4 number of seconds (Examples: PT10M (10 minutes), P1DT2H (1 day, 2 hours) | P10675199DT2H48M5.4775807S | | Duplicate Detection History Time Window a| String | Specifies the time span during which Service Bus detects message duplication Valid values: Range: 1 second - 7 days. Format: Px1DTx2Hx3Mx4S, where x1 number of days, x2 number of hours, x3 number of minutes, x4 number of seconds (Examples: PT10M (10 minutes), P1DT2H (1 day, 2 hours)). | PT10M | | Max Delivery Count a| Number | The maximum number of times Service Bus tries to deliver a message before being dead-lettered or discarded. | 10 | |=== [[ServiceBusRule]] === Service Bus Rule [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Id a| String | | | | Link a| String | | | | Published a| Date | | | | Rule Description a| <> | | | | Title a| String | | | | Updated a| Date | | | |=== [[ServiceBusRuleDescription]] === Service Bus Rule Description [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Action a| <> | The action that the rule performs | | | Filter a| <> | The filter for the associated subscription | | |=== [[ServiceBusRuleAction]] === Service Bus Rule Action [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Sql Expression a| String | The SQL expression for the action to perform | | | Type a| Enumeration, one of: ** SqlRuleAction ** EmptyRuleAction | | | |=== [[ServiceBusRuleFilter]] === Service Bus Rule Filter [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Correlation Id a| String | The ID to match if this filter is a correlation filter | | | Sql Expression a| String | The SQL expression for the action to perform | | | Type a| Enumeration, one of: ** SqlFilter ** TrueFilter ** FalseFilter ** CorrelationFilter | | | |=== [[ServiceBusSubscription]] === Service Bus Subscription [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Id a| String | | | | Link a| String | | | | Published a| Date | | | | Subscription Description a| <> | | | | Title a| String | | | | Updated a| Date | | | |=== [[ServiceBusSubscriptionDescription]] === Service Bus Subscription Description [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Lock Duration a| String | The default lock duration is applied to subscriptions that do not define a lock duration. You can only set this property at subscription creation time. Valid values: Range: 0 - 5 minutes. 0 means that the message is not locked. Format: PTx3Mx4S, where x1 number of days, x2 number of hours, x3 number of minutes, x4 number of seconds (Examples: PT5M (5 minutes), PT1M30S (1 minute, 30 seconds)). | PT1M | | Requires Session a| Boolean | You can only set this property at subscription creation time. If set to true, the subscription will be session-aware and only SessionReceiver will be supported. Session-aware subscriptions are not supported through REST. | false | | Dead Lettering On Message Expiration a| Boolean | This field controls how Service Bus handles a message with an expired TTL. If it is enabled and a message expires, Service Bus moves the message from the queue into the subscription's dead-letter sub-queue. If disabled, message is permanently deleted from the subscription's main queue. Settable only at subscription creation time. | false | | Dead Lettering On Filter Evaluation Exceptions a| Boolean | Determines how Service Bus handles a message that causes an exception during a subscription's filter evaluation. If the value is set to true, the message that caused the exception is moved to the subscription's dead-letter queue. Otherwise, it is discarded. By default, this parameter is set to true, enabling you to investigate the cause of the exception. It can occur from a malformed message or some incorrect assumptions being made in the filter about the form of the message. Settable only at subscription creation time. | false | | Enable Batched Operations a| Boolean | Enables or disables service-side batching behavior when performing operations for the specific queue. When enabled, Service Bus will collect/batch multiple operations to the backend to be more connection efficient. If you want lower operation latency, then you can disable this feature. | false | | Default Message Time To Live a| String | Determines how long a message lives in the subscription. Based on whether dead-lettering is enabled, a message whose Time To Live (TTL) has expired is either moved to the subscription's associated DeadLetterQueue, or permanently deleted. If the topic specifies a smaller TTL than the subscription, the topic TTL is applied. Format: Px1DTx2Hx3Mx4S, where x1 number of days, x2 number of hours, x3 number of minutes, x4 number of seconds (Examples: PT10M (10 minutes), P1DT2H (1 day, 2 hours) | P10675199DT2H48M5.4775807S | | Max Delivery Count a| Number | The maximum number of times Service Bus tries to deliver a message before that message is dead lettered or discarded. | 10 | |=== [[ServiceBusTopic]] === Service Bus Topic [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Author a| String | | | | Id a| String | | | | Link a| String | | | | Published a| Date | | | | Title a| String | | | | Topic Description a| <> | | | | Updated a| Date | | | |=== [[ServiceBusTopicDescription]] === Service Bus Topic Description [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Max Size In Megabytes a| Number | Specifies the maximum queue size in megabytes. Any attempt to enqueue a message that will cause the queue to exceed this value fails. Valid values are: 1024, 2048, 3072, 4096, 5120 | 1024 | | Requires Duplicate Detection a| Boolean | If enabled, the topic detects duplicate messages within the time span specified by the DuplicateDetectionHistoryTimeWindow property. Settable only at topic creation time. | false | | Enable Batched Operations a| Boolean | Enables or disables service side batching behavior when performing operations for the specific queue. When enabled, Service Bus collects/batches multiple operations to the back end to be more connection efficient. If you want lower operation latency, you can disable this feature. | true | | Default Message Time To Live a| String | Determines how long a message lives in the associated subscriptions. Subscriptions inherit the TTL from the topic unless they are created explicitly with a smaller TTL. Based on whether dead-lettering is enabled, a message whose TTL has expired will either be moved to the subscription's associated DeadLetterQueue or will be permanently deleted. Format: Px1DTx2Hx3Mx4S, where x1 number of days, x2 number of hours, x3 number of minutes, x4 number of seconds (Examples: PT10M (10 minutes), P1DT2H (1 day, 2 hours)). | P10675199DT2H48M5.4775807S | | Duplicate Detection History Time Window a| String | Specifies the time span during which Service Bus detects message duplication Valid values: Range: 1 second - 7 days. Format: Px1DTx2Hx3Mx4S, where x1 number of days, x2 number of hours, x3 number of minutes, x4 number of seconds (Examples: PT10M (10 minutes), P1DT2H (1 day, 2 hours)). | PT10M | |=== [[default-caching]] === Default Caching [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Session Cache Size a| Number | Number of sessions to cache. | | | Cache Producers a| Boolean | true if the ConnectionFactory should cache the MessageProducers | true | | Cache Consumers a| Boolean | true if the ConnectionFactory should cache the MessageConsumers | true | |=== [[topic-consumer]] === Topic Consumer [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Topic Consumer a| <> | | | x | Topic Subscription a| <> | | | x |=== [[TopicSubscription]] === Topic Subscription [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Topic Path a| String | | | x | Subscription Path a| String | | | |=== [[ServiceBusQueueConsumer]] === Service Bus Queue Consumer [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Queue Consumer a| queue-consumer | | | | Source Queue a| String | | | | Number Of Consumers a| Number | The number of concurrent consumers to use to receive JMS Messages | 4 | |=== == See Also https://help.mulesoft.com[MuleSoft Help Center] ",16204,True,3804.1296479619614,median "= bpftrace(8) :doctype: manpage :toc: true //// Style guide: - one sentence per line //// == Name bpftrace - a high-level tracing language == Synopsis *bpftrace* [_OPTIONS_] _FILENAME_ + *bpftrace* [_OPTIONS_] -e 'program code' == Description bpftrace is a high-level tracing language and runtime for Linux based on BPF. It supports static and dynamic tracing for both the kernel and user-space. When _FILENAME_ is ""_-_"", read from stdin. == Examples List all probes with ""sleep"" in their name:: ---- # bpftrace -l '*sleep*' ---- Trace processes calling sleep:: ---- # bpftrace -e 'kprobe:do_nanosleep { printf(""%d sleeping\\n"", pid); }' ---- Trace processes calling sleep while spawning `sleep 5` as a child process:: ---- # bpftrace -e 'kprobe:do_nanosleep { printf(""%d sleeping\\n"", pid); }' -c 'sleep 5' ---- == Supported architectures x86_64, arm64 and s390x == Options //// Custom prefix to easily link section //// :idprefix: flags_ === Output format *-B* _MODE_:: Set the buffer mode for stdout. Valid values are:: *none* No buffering. Each I/O is written as soon as possible + *line* Data is written on the first newline or when the buffer is full. This is the default mode. + *full* Data is written once the buffer is full. *-f* _FORMAT_:: Set the output format. Valid values are:: *json* + *text* *-o* _FILENAME_:: Write bpftrace tracing output to _FILENAME_ instead of stdout. This doesn't include child process (*-c* option) output. Errors are still written to stderr. *--no-warnings*:: Suppress all warning messages created by bpftrace. === Tracing *-e* _PROGRAM_:: Execute _PROGRAM_ instead of reading the program from a file *-I* _DIR_:: Add the directory _DIR_ to the search path for C headers. This option can be used multiple times. *--include* _FILENAME_:: Add _FILENAME_ as an include for the pre-processor. This is equal to adding '#include _FILENAME_' to the start bpftrace program. This option can be used multiple times. *-l* [_SEARCH_]:: List all probes that match the _SEARCH_ pattern. If the pattern is omitted all probes will be listed. This pattern supports wildcards in the same way that probes do. E.g. '-l kprobe:*file*' to list all 'kprobes' with 'file' in the name. For more details see the <> section. *--unsafe*:: Some calls, like 'system', are marked as unsafe as they can have dangerous side effects ('system(""rm -rf"")') and are disabled by default. This flag allows their use. *-k*:: Errors from bpf-helpers(7) are silently ignored by default which can lead to strange results. This flag enables the detection of errors (except for errors from 'probe_read_*'). When errors occurs bpftrace will log an error containing the source location and the error code: ---- stdin:48-57: WARNING: Failed to probe_read_user_str: Bad address (-14) u:lib.so:""fn(char const*)"" { printf(""arg0:%s\\n"", str(arg0));} ~~~~~~~~~ ---- *-kk*:: Same as '-k' but also includes the errors from 'probe_read_*' helpers. === Process management *-p* _PID_:: Attach to the process with _PID_. If the process terminates, bpftrace will also terminate. When using USDT probes they will be attached to only this process. *-c* _COMMAND_:: Run _COMMAND_ as a child process. When the child terminates bpftrace stops as well, as if 'exit()' has been called. If bpftrace terminates before the child process does the child process will be terminated with a SIGTERM. If used, 'USDT' probes these will only be attached to the child process. To avoid a race condition when using 'USDTs' the child is stopped after 'execve' using 'ptrace(2)' and continued when all 'USDT' probes are attached. + The child PID is available to programs as the 'cpid' builtin. + The child process runs with the same privileges as bpftrace itself (usually root). *--usdt-file-activation*:: activate usdt semaphores based on file path === Miscellaneous *--info*:: Print detailed information about features supported by the kernel and the bpftrace build. *-h, --help*:: Print the help summary *-V, --version*:: Print bpftrace version information *-v*:: verbose messages *-d*:: debug mode *-dd*:: verbose debug mode //// ! ! ! This prefix reset must be at the end of the section, else cross references break ! ! //// == Environment Variables Some behavior can only be controlled through environment variables. This section lists all those variables. //// Custom prefix to easily link section //// :idprefix: envvar_ === BPFTRACE_STRLEN Default: 64 Number of bytes allocated on the BPF stack for the string returned by `str()`. Make this larger if you wish to read bigger strings with str(). Beware that the BPF stack is small (512 bytes). Support for even larger strings is [being discussed](https://github.com/iovisor/bpftrace/issues/305). === BPFTRACE_NO_CPP_DEMANGLE Default: 0 C++ symbol demangling in user space stack traces is enabled by default. This feature can be turned off by setting the value of this environment variable to `1`. === BPFTRACE_MAP_KEYS_MAX Default: 4096 This is the maximum number of keys that can be stored in a map. Increasing the value will consume more memory and increase startup times. There are some cases where you will want to: for example, sampling stack traces, recording timestamps for each page, etc. === BPFTRACE_MAX_PROBES Default: 512 This is the maximum number of probes that bpftrace can attach to. Increasing the value will consume more memory, increase startup times and can incur high performance overhead or even freeze or crash the system. === BPFTRACE_CACHE_USER_SYMBOLS Default: 0 if ASLR is enabled on system and `-c` option is not given; otherwise 1 By default, bpftrace caches the results of symbols resolutions only when ASLR (Address Space Layout Randomization) is disabled. This is because the symbol addresses change with each execution with ASLR. However, disabling caching may incur some performance penalty. Set this env variable to 1 to force bpftrace to cache. === BPFTRACE_VMLINUX Default: None This specifies the vmlinux path used for kernel symbol resolution when attaching kprobe to offset. If this value is not given, bpftrace searches vmlinux from pre defined locations. See src/attached_probe.cpp:find_vmlinux() for details. === BPFTRACE_BTF Default: None The path to a BTF file. By default, bpftrace searches several locations to find a BTF file. See src/btf.cpp for the details. === BPFTRACE_PERF_RB_PAGES Default: 64 Number of pages to allocate per CPU for perf ring buffer. The value must be a power of 2. If you're getting a lot of dropped events bpftrace may not be processing events in the ring buffer fast enough. It may be useful to bump the value higher so more events can be queued up. The tradeoff is that bpftrace will use more memory. === BPFTRACE_MAX_BPF_PROGS Default: 512 This is the maximum number of BPF programs (functions) that bpftrace can generate. The main purpose of this limit is to prevent bpftrace from hanging since generating a lot of probes takes a lot of resources (and it should not happen often). //// ! ! ! This prefix reset must be at the end of the section, else cross references break ! ! //// :idprefix: _ //// Custom prefix to easily link to a section //// :idprefix: language_ == bpftrace Language === Overview The `bpftrace` (`bt`) language is inspired by the D language used by `dtrace` and uses the same program structure. Each script consists of an preamble and one or more action blocks. ---- preamble actionblock1 actionblock2 ---- Preprocessor and type definitions take place in the preamble: ---- #include #define RED ""\\033[31m"" struct S { int x; } ---- Each action block consists of three parts: ---- probe[,probe] /predicate/ { action } ---- Probes:: A probe specifies the event and event type to attach too. Predicate:: The predicate is optional condition that must be met for the action to be executed. Action:: Actions are the programs that run when an event fires (and the predicate is met). An action is a semicolon (`;`) separated list of statements and always enclosed by brackets `{}` A basic script that traces the `open(2)` and `openat(2)` system calls can be written as follows: ---- BEGIN { printf(""Tracing open syscalls... Hit Ctrl-C to end.\\n""); } tracepoint:syscalls:sys_enter_open, tracepoint:syscalls:sys_enter_openat { printf(""%-6d %-16s %s\\n"", pid, comm, str(args->filename)); } ---- This script has two action blocks and a total of 3 probes. The first action block uses the special `BEGIN` probe, which fires once during `bpftrace` startup. This probe is used to print a header, indicating that the tracing has started. The second action block uses two probes, one for `open` and one for `openat`, and defines an action that prints the file being `open` ed as well as the `pid` and `comm` of the process that execute the syscall. See the <> section for details on the available probe types. === Identifiers Identifiers must match the following regular expression: `[_a-zA-Z][_a-zA-Z0-9]*` === Comments Both single line and multi line comments are supported. ---- // A single line comment i:s:1 { // can also be used to comment inline /* a multi line comment */ print(/* inline comment block */ 1); } ---- === Data Types The following fundamental integer types are provided by the language. [cols=""~,~""] |=== |*Type* |*Description* |uint8 |Unsigned 8 bit integer |int8 |Signed 8 bit integer |uint16 |Unsigned 16 bit integer |int16 |Signed 16 bit integer |uint32 |Unsigned 32 bit integer |int32 |Signed 32 bit integer |uint64 |Unsigned 64 bit integer |int64 |Signed 64 bit integer |=== ==== Floating-point Floating-point numbers are not supported by BPF and therefore not by bpftrace. === Constants Integers constants can be defined in the following formats: - decimal (base 10) - octal (base 8) - hexadecimal (base 16) - scientific (base 10) Octal constants have to be prefixed with a `0`, e.g. `0123`. Hexadecimal constants start with either `0x` or `0X`, e.g. `0x10`. Scientific are written in the `e` format which is a shorthand for `m*10^n`, e.g. `$i = 2e3;`. Note that scientific literals are integer only due to the lack of floating point support, `1e-3` is not valid. To improve the readability of big literals a underscore `_` can be used as field separator, e.g. 1_000_123_000. Integer suffixes as found in the C language are parsed by bpftrace to ensure compatibility with C headers/definitions but they're not used as size specifiers. `123UL`, `123U` and `123LL` all result in the same integer type with a value of `123`. Character constants can be defined by enclosing the character in single quotes, e.g. `$c = 'c';`. String constants can be defined by enclosing the character string in double quotes, e.g. `$str = ""Hello world"";`. Characters and strings support the following escape sequences: [cols=""~,~""] |=== | \\n |Newline | \\t |Tab | \\0nn |Octal value nn | \\xnn |Hexadecimal value nn |=== === Type conversion Integer and pointer types can be converted using explicit type conversion with an expression like: ---- $y = (uint32) $z; $py = (int16 *) $pz; ---- Integer casts to a higher rank are sign extended. Conversion to a lower rank is done by zeroing leading bits. === Operators and Expressions ==== Arithmetic Operators The following operators are available for integer arithmetic: [cols=""~,~""] |=== | + |integer addition | - |integer subtraction | * |integer multiplication | / |integer division | % |integer modulo |=== // TODO: Words about integer conversion when types mismatch ==== Logical Operators [cols=""~,~""] |=== | && | Logical AND | \\|\\| | Logical OR | ! | Logical NOT |=== ==== Bitwise Operators [cols=""~,~""] |=== | & | AND | \\| | OR | ^ | XOR | << | Left shift the left-hand operand by the number of bits specified by the right-hand expression value | >> | Right shift the left-hand operand by the number of bits specified by the right-hand expression value |=== ==== Relational Operators The following relational operators are defined for integers and pointers. [cols=""~,~""] |=== | < | left-hand expression is less than right-hand | \\<= | left-hand expression is less than or equal to right-hand | > | left-hand expression is bigger than right-hand | >= | left-hand expression is bigger or equal to than right-hand | == | left-hand expression equal to right-hand | != | left-hand expression not equal to right-hand |=== The following relation operators are available for comparing strings. [cols=""~,~""] |=== | == | left-hand string equal to right-hand | != | left-hand string not equal to right-hand |=== ==== Assignment Operators The following assignment operators can be used on both `map` and `scratch` variables: [cols=""~,~""] |=== | = | Assignment, assign the right-hand expression to the left-hand variable | <\\<= | Update the variable with its value left shifted by the number of bits specified by the right-hand expression value | >>= | Update the variable with its value right shifted by the number of bits specified by the right-hand expression value | += | Increment the variable by the right-hand expression value | -= | Decrement the variable by the right-hand expression value | *= | Multiple the variable by the right-hand expression value | /= | Divide the variable by the right-hand expression value | %= | Modulo the variable by the right-hand expression value | &= | Bitwise AND the variable by the right-hand expression value | \\|= | Bitwise OR the variable by the right-hand expression value | ^= | Bitwise XOR the variable by the right-hand expression value |=== All these operators are syntactic sugar for combining assignment with the specified operator. `@ -= 5` is equal to `@ = @ - 5`. ==== Increment and Decrement Operators The increment (`\\++`) and decrement (`--`) operators can be used on integer and pointer variables to increment their value by one. They can only be used on variables and can either be applied as prefix or suffix. The difference is that the expression `x++` returns the original value of `x`, before it got incremented while `++x` returns the value of `x` post increment. E.g. ---- $x = 10; $y = $x--; // y = 10; x = 9 $a = 10; $b = --$a; // a = 9; b = 9 ---- Note that maps will be implicitly declared and initialized to 0 if not already declared or defined. Scratch variables must be initialized before using these operators. === Variables and Maps bpftrace knows two types of variables, `scratch` and `map`. 'scratch' variables are kept on the BPF stack and only exists during the execution of the action block and cannot be accessed outside of the program. Scratch variable names always start with a `$`, e.g. `$myvar`. 'map' variables use BPF 'maps'. These exist for the lifetime of `bpftrace` itself and can be accessed from all action blocks and user-space. Map names always start with a `@`, e.g. `@mymap`. All valid identifiers can be used as `name`. The data type of a variable is automatically determined during first assignment and cannot be changed afterwards. ==== Associative Arrays Associative arrays are a collection of elements indexed by a key, similar to the hash tables found in languages like C++ (`std::map`) and Python (`dict`). They're a variant of 'map' variables. ---- @name[key] = expression @name[key1,key2] = expression ---- Just like with any variable the type is determined on first use and cannot be modified afterwards. This applies to both the key(s) and the value type. The following snippet creates a map with key signature `[int64, string[16]]` and a value type of `int64`: ---- @[pid, comm]++ ---- === Variable scoping // TODO === Pointers Pointers in bpftrace are similar to those found in `C`. // TODO, not true yet === Tuples bpftrace has support for immutable N-tuples (`n > 1`). A tuple is a sequence type (like an array) where, unlike an array, every element can have a different type. Tuples are a comma separated list of expressions, enclosed in brackets, `(1,2)` Individual fields can be accessed with the `.` operator. Tuples are zero indexed like arrays are. ---- i:s:1 { $a = (1,2); $b = (3,4, $a); print($a); print($b); print($b.0); } ---- Prints: ---- (1, 2) (3, 4, (1, 2)) 3 ---- ==== Arrays bpftrace supports accessing one-dimensional arrays like those found in `C`. Constructing arrays from scratch, like `int a[] = {1,2,3}` in `C`, is not supported. They can only be read into a variable from a pointer. The `[]` operator is used to access elements. ---- struct MyStruct { int y[4]; } kprobe:dummy { $s = (struct MyStruct *) arg0; print($s->y[0]); } ---- === Structs `C` like structs are supported by bpftrace. Fields are accessed with the `.` operator. Fields of a pointer to a struct can be accessed with the `\\->` operator. Custom struct can be defined in the preamble Constructing structs from scratch, like `struct X var = {.f1 = 1}` in `C`, is not supported. They can only be read into a variable from a pointer. ---- struct MyStruct { int a; } kprobe:dummy { $ptr = (struct MyStruct *) arg0; $st = *$ptr; print($st.a); print($ptr->a); } ---- === Conditionals Conditional expressions are supported in the form of if/else statements and the ternary operator. The ternary operator consists of three operands: a condition followed by a `?`, the expression to execute when the condition is true followed by a `:` and the expression to execute if the condition is false. ---- condition ? ifTrue : ifFalse ---- Both the `ifTrue` and `ifFalse` expressions must be of the same type, mixing types is not allowed. The ternary operator can be used as part of an assignment. ---- $a == 1 ? print(""true"") : print(""false""); $b = $a > 0 ? $a : -1; ---- If/else statements, like the one in `C`, are supported. ---- if (condition) { ifblock } else if (condition) { if2block } else { elseblock } ---- === Loops Since kernel 5.3 BPF supports loops as long as the verifier can prove they're bounded and fit within the instruction limit. In bpftrace loops are available through the `while` statement. ---- while (condition) { block; } ---- Within a while-loop the following control flow statements can be used: [cols=""~,~""] |=== | continue | skip processing of the rest of the block and jump back to the evaluation of the conditional | break | Terminate the loop |=== ---- i:s:1 { $i = 0; while ($i <= 100) { printf(""%d "", $i); if ($i > 5) { break; } $i++ } printf(""\\n""); } ---- Loop unrolling is also supported with the `unroll` statement. ---- unroll(n) { block; } ---- The compiler will evaluate the block `n` times and generate the BPF code for the block `n` times. As this happens at compile time `n` must be a constant greater than 0 (`n > 0`). The following two probes compile into the same code: ---- i:s:1 { unroll(3) { print(""Unrolled"") } } i:s:1 { print(""Unrolled"") print(""Unrolled"") print(""Unrolled"") } ---- //// ! ! ! This prefix reset must be at the end of the section, else cross references break ! ! //// :idprefix: _ == Sync and Async While BPF in the kernel can do a lot there are still things that can only be done from user space, like the outputting (printing) of data. The way bpftrace handles this is by sending events from the BPF program which user-space will pick up some time in the future (usually in milliseconds). Operations that happen in the kernel are 'synchronous' ('sync') and those that are handled in user space are 'asynchronous' ('async') The async behaviour can lead to some unexpected behavior as updates can happen before user space had time to process the event. One example is updating a map value in a tight loop: ---- BEGIN { @=0; unroll(10) { print(@); @++; } exit() } ---- Maps are printed by reference not by value and as the value gets updated right after the print user-space will likely only see the final value once it processes the event: ---- @: 10 @: 10 @: 10 @: 10 @: 10 @: 10 @: 10 @: 10 @: 10 @: 10 ---- == Address-spaces Kernel and user pointers live in different address spaces which, depending on the CPU architecture, might overlap. Trying to read a pointer that is in the wrong address space results in a runtime error. This error is hidden by default but can be enabled with the `-kk` flag: ---- stdin:1:9-12: WARNING: Failed to probe_read_user: Bad address (-14) BEGIN { @=*uptr(kaddr(""do_poweroff"")) } ~~~ ---- bpftrace tries to automatically set the correct address space for a pointer based on the probe type, but might fail in cases where it is unclear. The address space can be changed with the `kptr()` and `uptr()` functions. == Builtins Builtins are special variables built into the language. Unlike the scratch and map variable they don't need a `$` or `@` as prefix (except for the positional parameters). [%header,cols=""~,~,~,~,~""] |=== | Variable | Type | Kernel | BPF Helper | Description | `$1`, `$2`, `...$n` | int64 | n/a | n/a | The nth positional parameter passed to the bpftrace program. If less than n parameters are passed this evaluates to `0`. For string arguments use the `str()` call to retrieve the value. | `$#` | int64 | n/a | n/a | Total amount of positional parameters passed. | `arg0`, `arg1`, `...argn` | int64 | n/a | n/a | nth argument passed to the function being traced. These are extracted from the CPU registers. The amount of args passed in registers depends on the CPU architecture. (kprobes, uprobes, usdt). | cgroup | uint64 | 4.18 | get_current_cgroup_id | ID of the cgroup the current task is in. Only works with cgroupv2. | comm | string[16] | 4.2 | get_current_com | `comm` of the current task. Equal to the value in `/proc//comm` | cpid | uint32 | n/a | n/a | PID of the child process | cpu | uint32 | 4.1 | raw_smp_processor_id | ID of the processor executing the BPF program | curtask | uint64 | 4.8 | get_current_task | Pointer to `struct task_struct` of the current task | elapsed | uint64 | (see nsec) | ktime_get_ns / ktime_get_boot_ns | Nanoseconds elapsed since bpftrace initialization, based on `nsecs` | func | string | n/a | n/a | Name of the current function being traced (kprobes,uprobes) | gid | uint64 | 4.2 | get_current_uid_gid | GID of current task | kstack | kstack | | get_stackid | Kernel stack trace | nsecs | uint64 | 4.1 / 5.7 | ktime_get_ns / ktime_get_boot_ns | nanoseconds since kernel boot. On kernels that support `ktime_get_boot_ns` this includes the time spent suspended, on older kernels it does not. | pid | uint64 | 4.2 | get_current_pid_tgid | Process ID (or thread group ID) of the current task. | probe | string | n/na | n/a | Name of the current probe | rand | uint32 | 4.1 | get_prandom_u32 | Random number | retval | int64 | n/a | n/a | Value returned by the function being traced (kretprobe, uretprobe, kretfunc) | `sarg0`, `sarg1`, `...sargn` | int64 | n/a | n/a | nth stack value of the function being traced. (kprobes, uprobes). | tid | uint64 | 4.2 | get_current_pid_tgid | Thread ID of the current task. | uid | uint64 | 4.2 | get_current_uid_gid | UID of current task | ustack | ustack | 4.6 | get_stackid | Userspace stack trace |=== //// Custom prefix to easily link to a function //// :idprefix: functions_ == Map Functions Map functions are built-in functions who's return value can only be assigned to maps. The data type associated with these functions are only for internal use and are not compatible with the (integer) operators. Functions that are marked *async* are asynchronous which can lead to unexpected behavior, see the <> section for more information. === avg .variants * `avg(int64 n)` Calculate the running average of `n` between consecutive calls. ---- i:s:1 { @x++; @y = avg(@x); print(@x); print(@y); } ---- Internally this keeps two values in the map: value count and running total. The average is computed in user-space when printing by dividing the total by the count. === clear .variants * `clear(map m)` *async* Clear all keys/values from map `m`. ---- i:ms:100 { @[rand % 10] = count(); } i:s:10 { print(@); clear(@); } ---- === count .variants * `count()` Count how often this function is called. Using `@=count()` is conceptually similar to `@++`. The difference is that the `count()` function uses a map type optimized for this (PER_CPU), increasing performance. Due to this the map cannot be accessed as a regular integer. ---- i:ms:100 { @ = count(); } i:s:10 { print(@); clear(@); } ---- === delete .variants * `delete(mapkey k)` Delete a single key from a map. For a single value map this deletes the only element. For an associative-array the key to delete has to be specified. ``` k:dummy { @scalar = 1; @associative[1,2] = 1; delete(@scalar); delete(@associative[1,2]); delete(@associative); // error } ``` === hist .variants * `hist(int64 n)` Create a log2 histogram of `n`. ---- kretprobe:vfs_read { @bytes = hist(retval); } ---- Results in: ---- @: [1M, 2M) 3 | | [2M, 4M) 2 | | [4M, 8M) 2 | | [8M, 16M) 6 | | [16M, 32M) 16 | | [32M, 64M) 27 | | [64M, 128M) 48 |@ | [128M, 256M) 98 |@@@ | [256M, 512M) 191 |@@@@@@ | [512M, 1G) 394 |@@@@@@@@@@@@@ | [1G, 2G) 820 |@@@@@@@@@@@@@@@@@@@@@@@@@@@ | ---- === lhist .variants * `lhist(int64 n, int64 min, int64 max, int64 step)` Create a linear histogram of `n`. `lhist` creates `M` (`(max - min) / step`) buckets in the range `[min,max)` where each bucket is `step` in size. Values in the range `(-inf, min)` and `(max, inf)` get their get their own bucket too, bringing the total amount of buckets created to `M+2`. ---- i:ms:1 { @ = lhist(rand %10, 0, 10, 1); } i:s:5 { exit(); } ---- Prints: ---- @: [0, 1) 306 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ | [1, 2) 284 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ | [2, 3) 294 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ | [3, 4) 318 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ | [4, 5) 311 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ | [5, 6) 362 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@| [6, 7) 336 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ | [7, 8) 326 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ | [8, 9) 328 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ | [9, 10) 318 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ | ---- === max .variants * `max(int64 n)` Update the map with `n` if `n` is bigger than the current value held. === min .variants * `min(int64 n)` Update the map with `n` if `n` is smaller than the current value held. === stats .variants * `stats(int64 n)` `stats` combines the `count`, `avg` and `sum` calls into one. ---- kprobe:vfs_read { @bytes[comm] = stats(arg2); } ---- ---- @bytes[bash]: count 7, average 1, total 7 @bytes[sleep]: count 5, average 832, total 4160 @bytes[ls]: count 7, average 886, total 6208 @ ---- === sum .variants * `sum(int64 n)` Calculate the sum of all `n` passed. === zero .variants * `zero(map m)` *async* Set all values for all keys to zero. == Functions Functions that are marked *async* are asynchronous which can lead to unexpected behaviour, see the <> section for more information. *compile time* functions are evaluated at compile time, a static value will be compiled into the program. *unsafe* functions can have dangerous side effects and should be used with care, the `--unsafe` flag is required for use. === bswap .variants * `uint8 bswap(uint8 n)` * `uint16 bswap(uint16 n)` * `uint32 bswap(uint32 n)` * `uint64 bswap(uint64 n)` `bswap` reverses the order of the bytes in integer `n`. In case of 8 bit integers, `n` is returned without being modified. The return type is an unsigned integer of the same width as `n`. === buf .variants * `buf_t buf(void * data, [int64 length])` `buf` reads `length` amount of bytes from address `data`. The maximum value of `length` is limited to the `BPFTRACE_STRLEN` variable. For arrays the `length` is optional, it is automatically inferred from the signature. `buf` is address space aware and will call the correct helper based on the address space associated with `data`. The `buf_t` object returned by `buf` can safely be printed as a hex encoded string with the `%r` format specifier. Bytes with values >=32 and \\<=126 are printed using their ASCII character, other bytes are printed in hex form (e.g. `\\x00`). ---- i:s:1 { printf(""%r\\n"", buf(kaddr(""avenrun""), 8)); } ---- ---- \\x00\\x03\\x00\\x00\\x00\\x00\\x00\\x00 \\xc2\\x02\\x00\\x00\\x00\\x00\\x00\\x00 ---- === cat .variants * `void cat(string namefmt, [...args])` *async* Dump the contents of the named file to stdout. `cat` supports the same format string and arguments that `printf` does. If the file cannot be opened or read an error is printed to stderr. ---- t:syscalls:sys_enter_execve { cat(""/proc/%d/maps"", pid); } ---- ---- 55f683ebd000-55f683ec1000 r--p 00000000 08:01 1843399 /usr/bin/ls 55f683ec1000-55f683ed6000 r-xp 00004000 08:01 1843399 /usr/bin/ls 55f683ed6000-55f683edf000 r--p 00019000 08:01 1843399 /usr/bin/ls 55f683edf000-55f683ee2000 rw-p 00021000 08:01 1843399 /usr/bin/ls 55f683ee2000-55f683ee3000 rw-p 00000000 00:00 0 ---- === cgroup_path .variants * `cgroup_path cgroup_path(int cgroupid, string filter)` Convert cgroup id to cgroup path. This is done asynchronously in userspace when the cgroup_path value is printed, therefore it can resolve to a different value if the cgroup id gets reassigned. This also means that the returned value can only be used for printing. A string literal may be passed as an optional second argument to filter cgroup hierarchies in which the cgroup id is looked up by a wildcard expression (cgroup2 is always represented by ""unified"", regardless of where it is mounted). The currently mounted hierarchy at /sys/fs/cgroup is used to do the lookup. If the cgroup with the given id isn't present here (e.g. when running in a Docker container), the cgroup path won't be found (unlike when looking up the cgroup path of a process via /proc/.../cgroup). ---- BEGIN { $cgroup_path = cgroup_path(3436); print($cgroup_path); print($cgroup_path); /* This may print a different path */ printf(""%s %s"", $cgroup_path, $cgroup_path); /* This may print two different paths */ } ---- === cgroupid .variants * `uint64 cgroupid(const string path)` *compile time* `cgroupid` retrieves the cgroupv2 ID of the cgroup available at `path`. ---- BEGIN { print(cgroupid(""/sys/fs/cgroup/system.slice"")); } ---- === exit .variants * `void exit()` *async* Terminate bpftrace, as if a `SIGTERM` was received. The `END` probe will still trigger (if specified) and maps will be printed. === join .variants * `void join(char *arr[], [char * sep = ' '])` *async* `join` joins all the string array `arr` with `sep` as separator into one string. This string will be printed to stdout directly, it cannot be used as string value. The concatenation of the array members is done in BPF and the printing happens in userspace. ---- tracepoint:syscalls:sys_enter_execve { join(args->argv); } ---- === kaddr .variants * `uint64 kaddr(const string name)` *compile time* Get the address of the kernel symbol `name`. The following script: === kptr .variants * `T * kptr(T * ptr)` Marks `ptr` as a kernel address space pointer. See the address-spaces section for more information on address-spaces. The pointer type is left unchanged. === ksym .variants * `ksym_t ksym(uint64 addr)` *async* Retrieve the name of the function that contains address `addr`. The address to name mapping happens in user-space. The `ksym_t` type can be printed with the `%s` format specifier. ---- kprobe:do_nanosleep { printf(""%s\\n"", ksym(reg(""ip""))); } ---- Prints: ---- do_nanosleep ---- === macaddr .variants * `macaddr_t macaddr(char [6] mac)` Create a buffer that holds a macaddress as read from `mac` This buffer can be printed in the canonical string format using the `%s` format specifier. ---- kprobe:arp_create { printf(""SRC %s, DST %s\\n"", macaddr(sarg0), macaddr(sarg1)); } ---- Prints: ---- SRC 18:C0:4D:08:2E:BB, DST 74:83:C2:7F:8C:FF ---- === ntop .variants * `inet_t ntop([int64 af, ] int addr)` * `inet_t ntop([int64 af, ] char addr[4])` * `inet_t ntop([int64 af, ] char addr[16])` `ntop` returns the string representation of an IPv4 or IPv6 address. `ntop` will infer the address type (IPv4 or IPv6) based on the `addr` type and size. If an integer or `char[4]` is given, ntop assumes IPv4, if a `char[16]` is given, ntop assumes IPv6. You can also pass the address type (e.g. AF_INET) explicitly as the first parameter. === override .variants * `override(uint64 rc)` *unsafe* *Kernel* 4.16 *Helper* `bpf_override` .Supported probes * kprobe When using `override` the probed function will not be executed and instead `rc` will be returned. ---- k:__x64_sys_getuid /comm == ""id""/ { override(2<<21); } ---- ---- uid=4194304 gid=0(root) euid=0(root) groups=0(root) ---- This feature only works on kernels compiled with `CONFIG_BPF_KPROBE_OVERRIDE` and only works on functions tagged `ALLOW_ERROR_INJECTION`. bpftrace does not test whether error injection is allowed for the probed function, instead if will fail to load the program into the kernel: ---- ioctl(PERF_EVENT_IOC_SET_BPF): Invalid argument Error attaching probe: 'kprobe:vfs_read' ---- === reg .variants * `reg(const string name)` .Supported probes * kprobe * uprobe Get the contents of the register identified by `name`. Valid names depend on the CPU architecture. === signal .variants * `signal(const string sig)` * `signal(uint32 signum)` *unsafe* *Kernel* 5.3 *Helper* `bpf_send_signal` Probe types: k(ret)probe, u(ret)probe, USDT, profile Send a signal to the process being traced. The signal can either be identified by name, e.g. `SIGSTOP` or by ID, e.g. `19` as found in `kill -l`. ---- kprobe:__x64_sys_execve /comm == ""bash""/ { signal(5); } ---- ---- $ ls Trace/breakpoint trap (core dumped) ---- === sizeof .variants * `sizeof(TYPE)` * `sizeof(EXPRESSION)` *compile time* Returns size of the argument in bytes. Similar to C/C++ `sizeof` operator. Note that the expression does not get evaluated. === str .variants * `str(char * data [, uint32 length)` *Helper* `probe_read_str, probe_read_{kernel,user}_str` `str` reads a NULL terminated (`\\0`) string from `data`. The maximum string length is limited by the `BPFTRACE_STR_LEN` env variable, unless `length` is specified and shorter than the maximum. In case the string is longer than the specified length only `length - 1` bytes are copied and a NULL byte is appended at the end. When available (starting from kernel 5.5, see the `--info` flag) bpftrace will automatically use the `kernel` or `user` variant of `probe_read_{kernel,user}_str` based on the address space of `data`, see <> for more information. === strftime .variants * `strtime_t strftime(const string fmt, int64 timestamp_ns)` *async* Format the nanoseconds since boot timestamp `timestamp_ns` according to the format specified by `fmt`. The time conversion and formatting happens in user space, therefore the `timestr_t` value returned can only be used for printing using the `%s` format specifier. bpftrace uses the `strftime(3)` function for formatting time and supports the same format specifiers. ---- i:s:1 { printf(""%s\\n"", strftime(""%H:%M:%S"", nsecs)); } ---- bpftrace also supports the following format string extensions: [%header,cols=""~,~""] |=== | Specifier | Description | `%f` | Microsecond as a decimal number, zero-padded on the left |=== === strncmp .variants * `int64 strncmp(char * s1, char * s2, int64 n)` `strncmp` compares up to `n` characters string `s1` and string `s2`. If they're equal `0` is returned, else a non-zero value is returned. bpftrace doesn't read past the length of the shortest string. The use of the `==` and `!=` operators is recommended over calling `strncmp` directly. === system .variants * `void system(string namefmt [, ...args])` *unsafe* *async* `system` lets bpftrace run the specified command (`fork` and `exec`) until it completes and print its stdout. The `command` is run with the same privileges as bpftrace and it blocks execution of the processing threads which can lead to missed events and delays processing of async events. ---- i:s:1 { time(""%H:%M:%S: ""); printf(""%d\\n"", @++); } i:s:10 { system(""/bin/sleep 10""); } i:s:30 { exit(); } ---- Note how the async `time` and `printf` first print every second until the `i:s:10` probe hits, then they print every 10 seconds due to bpftrace blocking on `sleep`. ---- Attaching 3 probes... 08:50:37: 0 08:50:38: 1 08:50:39: 2 08:50:40: 3 08:50:41: 4 08:50:42: 5 08:50:43: 6 08:50:44: 7 08:50:45: 8 08:50:46: 9 08:50:56: 10 08:50:56: 11 08:50:56: 12 08:50:56: 13 08:50:56: 14 08:50:56: 15 08:50:56: 16 08:50:56: 17 08:50:56: 18 08:50:56: 19 ---- `system` supports the same format string and arguments that `printf` does. ---- t:syscalls:sys_enter_execve { system(""/bin/grep %s /proc/%d/status"", ""vmswap"", pid); } ---- === time .variants * `void time(const string fmt)` *async* Format the current wall time according to the format specifier `fmt` and print it to stdout. Unlike `strftime()` `time()` doesn't send a timestamp from the probe, instead it is the time at which user-space processes the event. bpftrace uses the `strftime(3)` function for formatting time and supports the same format specifiers. === uaddr .variants * `T * uaddr(const string sym)` .Supported probes * uprobes * uretprobes * USDT **Does not work with ASLR, see issue link:https://github.com/iovisor/bpftrace/issues/75[#75]** The `uaddr` function returns the address of the specified symbol. This lookup happens during program compilation and cannot be used dynamically. The default return type is `uint64*`. If the ELF object size matches a known integer size (1, 2, 4 or 8 bytes) the return type is modified to match the width (`uint8*`, `uint16*`, `uint32*` or `uint64*` resp.). As ELF does not contain type info the type is always assumed to be unsigned. ---- uprobe:/bin/bash:readline { printf(""PS1: %s\\n"", str(*uaddr(""ps1_prompt""))); } ---- === uptr .variants * `T * uptr(T * ptr)` Marks `ptr` as a user address space pointer. See the address-spaces section for more information on address-spaces. The pointer type is left unchanged. === usym .variants * `usym_t usym(uint64 * addr)` *async* .Supported probes * uprobes * uretprobes Equal to <> but resolves user space symbols ---- uprobe:/bin/bash:readline { printf(""%s\\n"", usym(reg(""ip""))); } ---- Prints: ---- readline ---- === path .variants * `char * path(struct path * path)` *Kernel* 5.10 *Helper* bpf_d_path Return full path referenced by struct path pointer in argument. This function can only be used by functions that are allowed to, these functions are contained in the `btf_allowlist_d_path` set in the kernel. === unwatch .variants * `void unwatch(void * addr)` *async* Removes a watchpoint == Output formatting === print .variants * `void print(T val)` *async* .variants * `void print(T val)` * `void print(@map)` * `void print(@map, uint64 top)` * `void print(@map, uint64 top, uint64 div)` `print` prints a the value, which can be a map or a scalar value, with the default formatting for the type. ---- i:ms:10 { @=hist(rand); } i:s:1 { print(@); print(123); print(""abc""); exit(); } ---- Prints: ---- @: [16M, 32M) 3 |@@@ | [32M, 64M) 2 |@@ | [64M, 128M) 1 |@ | [128M, 256M) 4 |@@@@ | [256M, 512M) 3 |@@@ | [512M, 1G) 14 |@@@@@@@@@@@@@@ | [1G, 2G) 22 |@@@@@@@@@@@@@@@@@@@@@@ | [2G, 4G) 51 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@| 123 abc ---- Note that maps are printed by reference while scalar values are copied. This means that updating and printing maps in a fast loop will likely result in bogus map values as the map will be updated before userspace gets the time to dump and print it. The printing of maps supports the optional `top` and `div` arguments. `top` limits the printing to the top N entries with the highest integer values ---- BEGIN { $i = 11; while($i) { @[$i] = --$i; } print(@, 2); clear(@); exit() } ---- ---- @[9]: 9 @[10]: 10 ---- The `div` argument scales the values prior to printing them. Scaling values before storing them can result in rounding errors. Consider the following program: ---- k:f { @[func] += arg0/10; } ---- With the following sequence as numbers for arg0: `134, 377, 111, 99`. The total is `721` which rounds to `72` when scaled by 10 but the program would print `70` due to the rounding of individual values. Changing the print call to `print(@, 5, 2)` will take the top 5 values and scale them by 2: ---- @[6]: 3 @[7]: 3 @[8]: 4 @[9]: 4 @[10]: 5 ---- === printf .variants * `void printf(const string fmt, args...)` *async* `printf()` formats and prints data. It behaves similar to `printf()` found in `C` and many other languages. The format string has to be a constant, it cannot be modified at runtime. The formatting of the string happens in user space. Values are copied and passed by value. bpftrace supports all the typical format specifiers like `%llx` and `%hhu`. The non-standard ones can be found in the table below: [%header,cols=""~,~,~""] |=== | Specifier | Type | Description | r | buffer | Hex-formatted string to print arbitrary binary content returned by the buf (<>) function. |=== Supported escape sequences Colors are supported too, using standard terminal escape sequences: ---- print(""\\033[31mRed\\t\\033[33mYellow\\033[0m\\n"") ---- //// ! ! ! This prefix reset must be at the end of the section, else cross references break ! ! //// :idprefix: _ == Probes bpftrace supports various probe types which allow the user to attach BPF programs to different types of events. Each probe starts with a provider (e.g. `kprobe`) followed by a colon (`:`) separated list of options. The amount of options and their meaning depend on the provider and are detailed below. The valid values for options can depend on the system or binary being traced, e.g. for uprobes it depends on the binary. Also see <> It is possible to associate multiple probes with a single action as long as the action is valid for all specified probes. Multiple probes can be specified as a comma (`,`) separated list: ---- kprobe:tcp_reset,kprobe:tcp_v4_rcv { printf(""Entered: %s\\n"", probe); } ---- Wildcards are supported too: ---- kprobe:tcp_* { printf(""Entered: %s\\n"", probe); } ---- Both can be combined: ---- kprobe:tcp_reset,kprobe:*socket* { printf(""Entered: %s\\n"", probe); } ---- Most providers also support a short name which can be used instead of the full name, e.g. `kprobe:f` and `k:f` are identical. [#probes-begin-end] === BEGIN and END These are special built-in events provided by the bpftrace runtime. `BEGIN` is triggered before all other probes are attached. `END` is triggered after all other probes are detached. Note that specifying an `END` probe doesn't override the printing of 'non-empty' maps at exit. To prevent the printing all used maps need be cleared, which can be done in the `END` probe: ---- END { clear(@map1); clear(@map2); } ---- [#probes-hardware] === hardware .variants * `hardware:event_name:` * `hardware:event_name:count` .shortname * `h` The `hardware` probe attaches to pre-defined hardware events provided by the kernel. They are implemented using performance monitoring counters (PMCs): hardware resources on the processor. There are about ten of these, and they are documented in the `perf_event_open(2)` man page. The event names are: - `cpu-cycles` or `cycles` - `instructions` - `cache-references` - `cache-misses` - `branch-instructions` or `branches` - `branch-misses` - `bus-cycles` - `frontend-stalls` - `backend-stalls` - `ref-cycles` The `count` option specifies how many events must happen before the probe fires. If `count` is left unspecified a default value is used. ---- hardware:cache-misses:1e6 { @[pid] = count(); } ---- [#probes-interval] === interval .variants * `interval:us:count` * `interval:ms:count` * `interval:s:count` * `interval:hz:rate` .shortnames * `i` The interval probe fires at a fixed interval as specified by its time spec. Interval fire on one CPU at the time, unlike <> probes. [#probes-iterator] === iterator .variants * `iter:task` * `iter:task:pin` * `iter:task_file` * `iter:task_file:pin` .shortnames * `it` These are eBPF iterator probes, that allow iteration over kernel objects. Iterator probe can't be mixed with any other probe, not even other iterator. Each iterator probe provides set of fields that could be accessed with ctx pointer. User can display set of available fields for iterator via -lv options as described below. Examples: ``` # bpftrace -e 'iter:task { printf(""%s:%d\\n"", ctx->task->comm, ctx->task->pid); }' Attaching 1 probe... systemd:1 kthreadd:2 rcu_gp:3 rcu_par_gp:4 kworker/0:0H:6 mm_percpu_wq:8 ... # bpftrace -e 'iter:task_file { printf(""%s:%d %d:%s\\n"", ctx->task->comm, ctx->task->pid, ctx->fd, path(ctx->file->f_path)); }' Attaching 1 probe... systemd:1 1:/dev/null systemd:1 2:/dev/null systemd:1 3:/dev/kmsg ... su:1622 1:/dev/pts/1 su:1622 2:/dev/pts/1 su:1622 3:/var/lib/sss/mc/passwd ... bpftrace:1892 1:pipe:[35124] bpftrace:1892 2:/dev/pts/1 bpftrace:1892 3:anon_inode:bpf-map bpftrace:1892 4:anon_inode:bpf-map bpftrace:1892 5:anon_inode:bpf_link bpftrace:1892 6:anon_inode:bpf-prog bpftrace:1892 7:anon_inode:bpf_iter ``` It's possible to pin iterator with specifying optional probe ':pin' part, that defines the pin file. It can be specified as absolute path or relative to /sys/fs/bpf. .relative pin ---- # bpftrace -e 'iter:task:list { printf(""%s:%d\\n"", ctx->task->comm, ctx->task->pid); }' Program pinned to /sys/fs/bpf/list ---- ---- # cat /sys/fs/bpf/list systemd:1 kthreadd:2 rcu_gp:3 rcu_par_gp:4 kworker/0:0H:6 mm_percpu_wq:8 rcu_tasks_kthre:9 ... ---- Examples with absolute pin file: .absolute pin ---- # bpftrace -e ' iter:task_file:/sys/fs/bpf/files { printf(""%s:%d %s\\n"", ctx->task->comm, ctx->task->pid, path(ctx->file->f_path)); }' Program pinned to /sys/fs/bpf/files ---- ---- # cat /sys/fs/bpf/files systemd:1 anon_inode:inotify systemd:1 anon_inode:[timerfd] ... systemd-journal:849 /dev/kmsg systemd-journal:849 anon_inode:[eventpoll] ... sssd:1146 /var/log/sssd/sssd.log sssd:1146 anon_inode:[eventpoll] ... NetworkManager:1155 anon_inode:[eventfd] NetworkManager:1155 /var/lib/sss/mc/passwd (deleted) ---- [#probes-kfunc] === kfunc and kretfunc .variants * `kfunc:fn` * `kretfunc:fn` .shortnames * `f` (`kfunc`) * `fr` (`kretfunc`) .requires (`--info`) * Kernel features:BTF * Probe types:kfunc ``kfunc``s attach to kernel function similar to <>. They make use of eBPF trampolines which allows kernel code to call into BPF programs with near zero overhead. `kfunc` s make use of BTF type information to derive the type of function arguments at compile time. This removes the need for manual type casting and makes the code more resilient against small signature changes in the kernel. The function arguments are available in the `args` struct which can be inspected by doing verbose listing (see <>). These arguments are also available in the return probe (`kretfunc`). ---- # bpftrace -lv 'kfunc:tcp_reset' kfunc:tcp_reset struct sock * sk struct sk_buff * skb ---- ---- kfunc:x86_pmu_stop { printf(""pmu %s stop\\n"", str(args->event->pmu->name)); } ---- ---- kretfunc:fget { printf(""fd %d name %s\\n"", args->fd, str(retval->f_path.dentry->d_name.name)); } ---- ---- fd 3 name ld.so.cache fd 3 name libselinux.so.1 fd 3 name libselinux.so.1 ... ---- [#probes-kprobe] === kprobe and kretprobe .variants * `kprobe:fn` * `kprobe:fn+offset` * `kretprobe:fn` .shortnames * `k` * `kr` `kprobe` s allow for dynamic instrumentation of kernel functions. Each time the specified kernel function is executed the attached BPF programs are ran. ---- kprobe:tcp_reset { @tcp_resets = count() } ---- Function arguments are available through the `argX` and `sargX` builtins, for register args and stack args respectively. Whether arguments passed on stack or in a register depends on the architecture and the number or arguments in used, e.g. on x86_64 the first non-floating point 6 arguments are passed in registers, all following arguments are passed on the stack. Note that floating point arguments are typically passed in special registers which don't count as `argX` arguments which can cause confusion. Consider a function with the following signature: ---- void func(int a, double d, int x) ---- Due to `d` being a floating point `x` is accessed through `arg1` where one might expect `arg2`. bpftrace does not detect the function signature so it is not aware of the argument count or their type. It is up to the user to perform <> when needed, e.g. ---- kprobe:tcp_connect { $sk = ((struct sock *) arg0); ... } ---- `kprobe` s are not limited to function entry, they can be attached to any instruction in a function by specifying an offset from the start of the function. `kretprobe` s trigger on the return from a kernel function. Return probes do not have access to the function (input) arguments, only to the return value (through `retval`). A common pattern to work around this is by storing the arguments in a map on function entry and retrieving in the return probe: ---- kprobe:d_lookup { $name = (struct qstr *)arg1; @fname[tid] = $name->name; } kretprobe:d_lookup /@fname[tid]/ { printf(""%-8d %-6d %-16s M %s\\n"", elapsed / 1e6, pid, comm, str(@fname[tid])); } ---- [#probes-profile] === profile .variants * `profile:us:count` * `profile:ms:count` * `profile:s:count` * `profile:hz:rate` .shortnames * `p` Profile probes fire on each CPU on the specified interval. [#probes-software] === software .variants * `software:event:` * `software:event:count` .shortnames * `s` The `software` probe attaches to pre-defined software events provided by the kernel. Event details can be found in the `perf_event_open(2)` man page. The event names are: - `cpu-clock` or `cpu` - `task-clock` - `page-faults` or `faults` - `context-switches` or `cs` - `cpu-migrations` - `minor-faults` - `major-faults` - `alignment-faults` - `emulation-faults` - `dummy` - `bpf-output` [#probes-tracepoint] === tracepoint .variants * `tracepoint:subsys:event` .shortnames * `t` Tracepoints are hooks into events in the kernel. Tracepoints are defined in the kernel source and compiled into the kernel binary which makes them a form of static tracing. Which means that unlike `kprobe` s new tracepoints cannot be added without modifying the kernel. The advantage of tracepoints is that they generally provide a more stable interface than `kprobe` s do, they do not depend on the existence of a kernel function. Tracepoint arguments are available in the `args` struct which can be inspected with verbose listing, see the <> section for more details. ---- tracepoint:syscalls:sys_enter_openat { printf(""%s %s\\n"", comm, str(args->filename)); } ---- ---- irqbalance /proc/interrupts irqbalance /proc/stat snmpd /proc/diskstats snmpd /proc/stat snmpd /proc/vmstat snmpd /proc/net/dev [...] ---- .Additional information * https://www.kernel.org/doc/html/latest/trace/tracepoints.html [#probes-uprobe] === uprobe, uretprobe .variants * `uprobe:binary:func` * `uprobe:binary:func+offset` * `uretprobe:binary:func` .shortnames * `u` * `ur` `uprobe` s or user-space probes are the user-space equivalent of `kprobe` s. The same limitations that apply <> also apply to `uprobe` s and `uretprobe` s. When tracing libraries, it is sufficient to specify the library name instead of a full path. The path will be then automatically resolved using `/etc/ld.so.cache`: ---- # bpftrace -e 'uprobe:libc:malloc { printf(""Allocated %d bytes\\n"", arg0); }' Allocated 4 bytes ... ---- If the traced binary has DWARF included, function arguments are available in the `args` struct which can be inspected with verbose listing, see the <> section for more details. It is important to note that for `uretprobe` s to work the kernel runs a special helper on user-space function entry which overrides the return address on the stack. This can cause issues with languages that have their own runtime like Golang: .example.go ---- func myprint(s string) { fmt.Printf(""Input: %s\\n"", s) } func main() { ss := []string{""a"", ""b"", ""c""} for _, s := range ss { go myprint(s) } time.Sleep(1*time.Second) } ---- .bpftrace ---- # bpftrace -e 'uretprobe:./test:main.myprint { @=count(); }' -c ./test runtime: unexpected return pc for main.myprint called from 0x7fffffffe000 stack: frame={sp:0xc00008cf60, fp:0xc00008cfd0} stack=[0xc00008c000,0xc00008d000) fatal error: unknown caller pc ---- [#probes-usdt] === usdt .variants * `usdt:binary:name` .shortnames * `U` [#probes-watchpoint] === watchpoint and asyncwatchpoint .variants * `watchpoint:absolute_address:length:mode` * `watchpoint:function+argN:length:mode` .shortnames * `w` * `aw` These are memory watchpoints provided by the kernel. Whenever a memory address is written to (`w`), read from (`r`), or executed (`x`), the kernel can generate an event. In the first form, an absolute address is monitored. If a pid (`-p`) or a command (`-c`) is provided, bpftrace takes the address as a userspace address and monitors the appropriate process. If not, bpftrace takes the address as a kernel space address. In the second form, the address present in `argN` when `function` is entered is monitored. A pid or command must be provided for this form. If synchronous (`watchpoint`), a `SIGSTOP` is sent to the tracee upon function entry. The tracee will be ``SIGCONT``ed after the watchpoint is attached. This is to ensure events are not missed. If you want to avoid the `SIGSTOP` + `SIGCONT` use `asyncwatchpoint`. Note that on most architectures you may not monitor for execution while monitoring read or write. Examples Print `hit` when a read from or write to `0x10000000` happens: ``` # bpftrace -e 'watchpoint:0x10000000:8:rw { printf(""hit!\\n""); exit(); }' -c ./testprogs/watchpoint ``` Print the call stack every time the `jiffies` variable is updated: ``` # bpftrace -e ""watchpoint:0x$(awk '$3 == ""jiffies"" {print $1}' /proc/kallsyms):8:w { @[kstack] = count(); } i:s:1 { exit(); }"" ...... @[ do_timer+12 tick_do_update_jiffies64.part.22+89 tick_sched_do_timer+103 tick_sched_timer+39 __hrtimer_run_queues+256 hrtimer_interrupt+256 smp_apic_timer_interrupt+106 apic_timer_interrupt+15 cpuidle_enter_state+188 cpuidle_enter+41 do_idle+536 cpu_startup_entry+25 start_secondary+355 secondary_startup_64+164 ]: 319 ``` ""hit"" and exit when the memory pointed to by `arg1` of `increment` is written to. ``` # cat wpfunc.c #include #include #include __attribute__((noinline)) void increment(__attribute__((unused)) int _, int *i) { (*i)++; } int main() { int *i = malloc(sizeof(int)); while (1) { increment(0, i); (*i)++; usleep(1000); } } # bpftrace -e 'watchpoint:increment+arg1:4:w { printf(""hit!\\n""); exit() }' -c ./wpfunc ``` == Listing Probes Probe listing is the method to discover which probes are supported by the current system. Listing supports the same syntax as normal attachment does: ---- # bpftrace -l 'kprobe:*' # bpftrace -l 't:syscalls:*openat* # bpftrace -l 'kprobe:tcp*,trace # bpftrace -l 'k:*socket*,tracepoint:syscalls:*tcp*' ---- The verbose flag (`-v`) can be specified to inspect arguments (`args`) for providers that support it: ---- # bpftrace -l 'fr:tcp_reset,t:syscalls:sys_enter_openat' -v kretfunc:tcp_reset struct sock * sk struct sk_buff * skb tracepoint:syscalls:sys_enter_openat int __syscall_nr int dfd const char * filename int flags umode_t mode # bpftrace -l 'uprobe:/bin/bash:rl_set_prompt' -v # works only if /bin/bash has DWARF uprobe:/bin/bash:rl_set_prompt const char *prompt ---- ",16217,True,2910.3516571349455,median " 23 255 0 blau 0 221 212 blaugrau 175 192 192 hellgrau 192 255 0 kamesinrot 255 0 200 orange 255 255 247 pastell-blau 211 186 245 pastell-gelb 255 234 255 pastell-gr&uuml;n 211 255 211 pastell-lila 244 191 165 pastell-rot 244 175 175 pink 255 0 0 rot 255 61 125 braun 170 0 0 schwarz 0 255 255 t&uuml;rkis 0 255 255 wei&szlig; 255 64 64 dunkelgrau 64 84 132 dunkelgr&uuml;n 94 0 255 gelb 255 0 225 goldgelb 255 128 128 grau 128 0 255 gr&uuml;n 0 255 212 hellblau 191 0 false false 2 POSTGRESQL org.postgresql.Driver Test-DB (Postgre) "" false true true jdbc:postgresql://mykene/TEST_OLI_ISIS_2 op1 HSQL org.hsqldb.jdbcDriver Test-DB (HSQL) "" false true true jdbc:hsqldb:unittests/db/tst sa 0 5 -5 NULL 0 0 Ident 12 NULL 500 0 LongName 12 NULL 200 0 Name 2 NULL 10 2 Price 2 NULL 10 3 Price2 archimedes.legacy.scheme.DefaultObjectFactory 5 10 false &lt;null&gt; .\\ &lt;null&gt; TST 0 false true hellgrau schwarz TST 12 24 12 &lt;null&gt; false false 1 08.12.2015 &lt;null&gt; 2 200 AuthorId 50 25 BookIds 100 0 5 false 0 0 0 0 0 0 0 0 false wei&szlig; schwarz false @changed OLI - Added. false false Book 0 1 0 1 1.Daten Hier können Sie die Daten des Objekt warten 6 false . true true false Author & Title false false true false Ident false 0 0 keine false false false false @changed OLI - Added. false false false false false false Id false 0 true false false false false false false false false false Ident false 0 0 keine true false false false @changed OLI - Added. false false false false false false Author true 0 false RIGHT LEFT 25 25 Id Author 1 RIGHT LEFT Main 25 25 0 false false false false false false false false false Ident false 0 0 keine true false false false @changed OLI - Added. false false false false false false Publisher true 0 false DOWN UP 25 25 Id Publisher 1 DOWN UP Main 25 25 0 false false false false false false false false false Price false 0 0 keine false false false false @changed OLI - Added. false false 8.99 false false false false Price true 0 false false false false false false false false false false Price2 false 0 0 keine false false false false @changed OLI - Added. false false false false false false RecommendedRetailPrice true 0 false false false false false false false false false false Name false 0 0 keine false false false false @changed OLI - Added. false false false false false false Title false 0 false false false false false false 0 1 Main 125 125 false 0 0 0 0 0 0 0 0 false wei&szlig; schwarz false @changed OLI - Added.$BR$@changed OLI - Added column: Id. false false Author 0 1 0 1 1.Daten Hier können Sie die Daten des Objekt warten 2 false . true true false false false true false Ident false 0 0 keine false false false false @changed OLI - Added. false false false false false false Id false 0 true false false false false false false false false false Name false 0 0 keine false false false false @changed OLI - Added. false false false false false false Name true 0 false false false false false false 0 1 Main 525 125 false 0 0 0 0 0 0 0 0 false wei&szlig; schwarz false @changed OLI - Added. false false Publisher 0 1 0 1 1.Daten Hier können Sie die Daten des Objekt warten 2 false . true true false false false true false Ident false 0 0 keine false false false false @changed OLI - Added. false false false false false false Id false 0 true false false false false false false false false false Name false 0 0 keine false false false false @changed OLI - Added. false true 'Penguin' false false false false Name false 0 false false false false false true 0 1 Main 125 375 false 0 0 0 0 0 0 0 0 false wei&szlig; schwarz false @changed OLI - Added. false true AuthorPublisher 0 1 0 1 1.Daten Hier können Sie die Daten des Objekt warten 2 false . true true false false false true false Ident false 0 0 keine true false false false @changed OLI - Added. false false false false false false Author true 0 true UP DOWN 25 25 Id Author 1 UP DOWN Main 25 25 0 false false false false false false false true false Ident false 0 0 keine true false false false @changed OLI - Added. false false false false false false Publisher true 0 true LEFT RIGHT 25 25 Id Publisher 1 LEFT RIGHT Main 25 25 0 false false false false false 0 1 Main 525 375 false 0 0 0 0 0 0 0 0 false wei&szlig; schwarz false @changed OLI - Added. false false OldTestTable 0 1 0 1 1.Daten Hier können Sie die Daten des Objekt warten 2 false . true true false false false true false Ident false 0 0 keine false false false false @changed OLI - Added. false false false false false false Id false 0 true false false false false false false false false false Ident false 0 0 keine true false false false @changed OLI - Added. false false false false false false Author true 0 false UP RIGHT 25 25 Id Author 1 UP RIGHT Main 25 25 1 800 150 false false false false false 0 1 Main 775 375 1 Diese Sicht beinhaltet alle Tabellen des Schemas Main true Book Author Publisher AuthorPublisher OldTestTable 5 false ",12173,True,2896.384666785781,median "= Vert.x Core Manual :toc: left At the heart of Vert.x is a set of Java APIs that we call *Vert.x Core* https://github.com/eclipse/vert.x[Repository]. Vert.x core provides functionality for things like: * Writing TCP clients and servers * Writing HTTP clients and servers including support for WebSockets * The Event bus * Shared data - local maps and clustered distributed maps * Periodic and delayed actions * Deploying and undeploying Verticles * Datagram Sockets * DNS client * File system access * High availability * Native transports * Clustering The functionality in core is fairly low level - you won't find stuff like database access, authorisation or high level web functionality here - that kind of stuff you'll find in *Vert.x ext* (extensions). Vert.x core is small and lightweight. You just use the parts you want. It's also entirely embeddable in your existing applications - we don't force you to structure your applications in a special way just so you can use Vert.x. You can use core from any of the other languages that Vert.x supports. But here'a a cool bit - we don't force you to use the Java API directly from, say, JavaScript or Ruby - after all, different languages have different conventions and idioms, and it would be odd to force Java idioms on Ruby developers (for example). Instead, we automatically generate an *idiomatic* equivalent of the core Java APIs for each language. From now on we'll just use the word *core* to refer to Vert.x core. include::override/dependencies.adoc[] Let's discuss the different concepts and features in core. == In the beginning there was Vert.x //// TODO Much of this is Java specific - need someway of swapping in language specific parts //// You can't do much in Vert.x-land unless you can communicate with a {@link io.vertx.core.Vertx} object! It's the control centre of Vert.x and is how you do pretty much everything, including creating clients and servers, getting a reference to the event bus, setting timers, as well as many other things. So how do you get an instance? If you're embedding Vert.x then you simply create an instance as follows: [source,$lang] ---- {@link examples.CoreExamples#example1} ---- NOTE: Most applications will only need a single Vert.x instance, but it's possible to create multiple Vert.x instances if you require, for example, isolation between the event bus or different groups of servers and clients. === Specifying options when creating a Vertx object When creating a Vertx object you can also specify options if the defaults aren't right for you: [source,$lang] ---- {@link examples.CoreExamples#example2} ---- The {@link io.vertx.core.VertxOptions} object has many settings and allows you to configure things like clustering, high availability, pool sizes and various other settings. The Javadoc describes all the settings in detail. === Creating a clustered Vert.x object If you're creating a *clustered Vert.x* (See the section on the <> for more information on clustering the event bus), then you will normally use the asynchronous variant to create the Vertx object. This is because it usually takes some time (maybe a few seconds) for the different Vert.x instances in a cluster to group together. During that time, we don't want to block the calling thread, so we give the result to you asynchronously. == Are you fluent? You may have noticed that in the previous examples a *fluent* API was used. A fluent API is where multiple methods calls can be chained together. For example: [source,$lang] ---- {@link examples.CoreExamples#example3} ---- This is a common pattern throughout Vert.x APIs, so get used to it. Chaining calls like this allows you to write code that's a little bit less verbose. Of course, if you don't like the fluent approach *we don't force you* to do it that way, you can happily ignore it if you prefer and write your code like this: [source,$lang] ---- {@link examples.CoreExamples#example4} ---- == Don't call us, we'll call you. The Vert.x APIs are largely _event driven_. This means that when things happen in Vert.x that you are interested in, Vert.x will call you by sending you events. Some example events are: * a timer has fired * some data has arrived on a socket, * some data has been read from disk * an exception has occurred * an HTTP server has received a request You handle events by providing _handlers_ to the Vert.x APIs. For example to receive a timer event every second you would do: [source,$lang] ---- {@link examples.CoreExamples#example5} ---- Or to receive an HTTP request: [source,$lang] ---- {@link examples.CoreExamples#example6} ---- Some time later when Vert.x has an event to pass to your handler Vert.x will call it *asynchronously*. This leads us to some important concepts in Vert.x: == Don't block me! With very few exceptions (i.e. some file system operations ending in 'Sync'), none of the APIs in Vert.x block the calling thread. If a result can be provided immediately, it will be returned immediately, otherwise you will usually provide a handler to receive events some time later. Because none of the Vert.x APIs block threads that means you can use Vert.x to handle a lot of concurrency using just a small number of threads. With a conventional blocking API the calling thread might block when: * Reading data from a socket * Writing data to disk * Sending a message to a recipient and waiting for a reply. * ... Many other situations In all the above cases, when your thread is waiting for a result it can't do anything else - it's effectively useless. This means that if you want a lot of concurrency using blocking APIs then you need a lot of threads to prevent your application grinding to a halt. Threads have overhead in terms of the memory they require (e.g. for their stack) and in context switching. For the levels of concurrency required in many modern applications, a blocking approach just doesn't scale. == Reactor and Multi-Reactor We mentioned before that Vert.x APIs are event driven - Vert.x passes events to handlers when they are available. In most cases Vert.x calls your handlers using a thread called an *event loop*. As nothing in Vert.x or your application blocks, the event loop can merrily run around delivering events to different handlers in succession as they arrive. Because nothing blocks, an event loop can potentially deliver huge amounts of events in a short amount of time. For example a single event loop can handle many thousands of HTTP requests very quickly. We call this the http://en.wikipedia.org/wiki/Reactor_pattern[Reactor Pattern]. You may have heard of this before - for example Node.js implements this pattern. In a standard reactor implementation there is a *single event loop* thread which runs around in a loop delivering all events to all handlers as they arrive. The trouble with a single thread is it can only run on a single core at any one time, so if you want your single threaded reactor application (e.g. your Node.js application) to scale over your multi-core server you have to start up and manage many different processes. Vert.x works differently here. Instead of a single event loop, each Vertx instance maintains *several event loops*. By default we choose the number based on the number of available cores on the machine, but this can be overridden. This means a single Vertx process can scale across your server, unlike Node.js. We call this pattern the *Multi-Reactor Pattern* to distinguish it from the single threaded reactor pattern. NOTE: Even though a Vertx instance maintains multiple event loops, any particular handler will never be executed concurrently, and in most cases (with the exception of <>) will always be called using the *exact same event loop*. [[golden_rule]] == The Golden Rule - Don't Block the Event Loop We already know that the Vert.x APIs are non blocking and won't block the event loop, but that's not much help if you block the event loop *yourself* in a handler. If you do that, then that event loop will not be able to do anything else while it's blocked. If you block all of the event loops in Vertx instance then your application will grind to a complete halt! So don't do it! *You have been warned*. Examples of blocking include: * +Thread.sleep()+ * Waiting on a lock * Waiting on a mutex or monitor (e.g. synchronized section) * Doing a long lived database operation and waiting for a result * Doing a complex calculation that takes some significant time. * Spinning in a loop If any of the above stop the event loop from doing anything else for a *significant amount of time* then you should go immediately to the naughty step, and await further instructions. So... what is a *significant amount of time*? How long is a piece of string? It really depends on your application and the amount of concurrency you require. If you have a single event loop, and you want to handle 10000 http requests per second, then it's clear that each request can't take more than 0.1 ms to process, so you can't block for any more time than that. *The maths is not hard and shall be left as an exercise for the reader.* If your application is not responsive it might be a sign that you are blocking an event loop somewhere. To help you diagnose such issues, Vert.x will automatically log warnings if it detects an event loop hasn't returned for some time. If you see warnings like these in your logs, then you should investigate. ---- Thread vertx-eventloop-thread-3 has been blocked for 20458 ms ---- Vert.x will also provide stack traces to pinpoint exactly where the blocking is occurring. If you want to turn off these warnings or change the settings, you can do that in the {@link io.vertx.core.VertxOptions} object before creating the Vertx object. [[blocking_code]] == Running blocking code In a perfect world, there will be no war or hunger, all APIs will be written asynchronously and bunny rabbits will skip hand-in-hand with baby lambs across sunny green meadows. *But... the real world is not like that. (Have you watched the news lately?)* Fact is, many, if not most libraries, especially in the JVM ecosystem have synchronous APIs and many of the methods are likely to block. A good example is the JDBC API - it's inherently synchronous, and no matter how hard it tries, Vert.x cannot sprinkle magic pixie dust on it to make it asynchronous. We're not going to rewrite everything to be asynchronous overnight so we need to provide you a way to use ""traditional"" blocking APIs safely within a Vert.x application. As discussed before, you can't call blocking operations directly from an event loop, as that would prevent it from doing any other useful work. So how can you do this? It's done by calling {@link io.vertx.core.Vertx#executeBlocking} specifying both the blocking code to execute and a result handler to be called back asynchronous when the blocking code has been executed. [source,$lang] ---- {@link examples.CoreExamples#example7} ---- By default, if executeBlocking is called several times from the same context (e.g. the same verticle instance) then the different executeBlocking are executed _serially_ (i.e. one after another). If you don't care about ordering you can call {@link io.vertx.core.Vertx#executeBlocking(io.vertx.core.Handler,boolean,io.vertx.core.Handler)} specifying `false` as the argument to `ordered`. In this case any executeBlocking may be executed in parallel on the worker pool. An alternative way to run blocking code is to use a <> A worker verticle is always executed with a thread from the worker pool. By default blocking code is executed on the Vert.x worker pool, configured with {@link io.vertx.core.VertxOptions#setWorkerPoolSize(int)}. Additional pools can be created for different purposes: [source,$lang] ---- {@link examples.CoreExamples#workerExecutor1} ---- The worker executor must be closed when it's not necessary anymore: [source,$lang] ---- {@link examples.CoreExamples#workerExecutor2} ---- When several workers are created with the same name, they will share the same pool. The worker pool is destroyed when all the worker executors using it are closed. When an executor is created in a Verticle, Vert.x will close it automatically for you when the Verticle is undeployed. Worker executors can be configured when created: [source,$lang] ---- {@link examples.CoreExamples#workerExecutor3} ---- NOTE: the configuration is set when the worker pool is created == Async coordination Coordination of multiple asynchronous results can be achieved with Vert.x {@link io.vertx.core.Future futures}. It supports concurrent composition (run several async operations in parallel) and sequential composition (chain async operations). === Concurrent composition {@link io.vertx.core.CompositeFuture#all} takes several futures arguments (up to 6) and returns a future that is _succeeded_ when all the futures are and _failed_ when at least one of the futures is failed: [source,$lang] ---- {@link examples.CoreExamples#exampleFutureAll1} ---- The operations run concurrently, the {@link io.vertx.core.Handler} attached to the returned future is invoked upon completion of the composition. When one of the operation fails (one of the passed future is marked as a failure), the resulting future is marked as failed too. When all the operations succeed, the resulting future is completed with a success. Alternatively, you can pass a list (potentially empty) of futures: [source,$lang] ---- {@link examples.CoreExamples#exampleFutureAll2} ---- While the `all` composition _waits_ until all futures are successful (or one fails), the `any` composition _waits_ for the first succeeded future. {@link io.vertx.core.CompositeFuture#any} takes several futures arguments (up to 6) and returns a future that is succeeded when one of the futures is, and failed when all the futures are failed: [source,$lang] ---- {@link examples.CoreExamples#exampleFutureAny1} ---- A list of futures can be used also: [source,$lang] ---- {@link examples.CoreExamples#exampleFutureAny2} ---- The `join` composition _waits_ until all futures are completed, either with a success or a failure. {@link io.vertx.core.CompositeFuture#join} takes several futures arguments (up to 6) and returns a future that is succeeded when all the futures are succeeded, and failed when all the futures are completed and at least one of them is failed: [source,$lang] ---- {@link examples.CoreExamples#exampleFutureJoin1} ---- A list of futures can be used also: [source,$lang] ---- {@link examples.CoreExamples#exampleFutureJoin2} ---- === Sequential composition While `all` and `any` are implementing concurrent composition, {@link io.vertx.core.Future#compose} can be used for chaining futures (so sequential composition). [source,$lang] ---- {@link examples.CoreExamples#exampleFuture6} ---- In this example, 3 operations are chained: 1. a file is created (`fut1`) 2. something is written in the file (`fut2`) 3. the file is moved (`startFuture`) When these 3 steps are successful, the final future (`startFuture`) is succeeded. However, if one of the steps fails, the final future is failed. This example uses: * {@link io.vertx.core.Future#compose(java.util.function.Function)}: when the current future completes, run the given function, that returns a future. When this returned future completes, it completes the composition. * {@link io.vertx.core.Future#compose(io.vertx.core.Handler,io.vertx.core.Future)}: when the current future completes, run the given handler that completes the given `future` (next). In this second case, the {@link io.vertx.core.Handler} should complete the `next` future to report its success or failure. You can use {@link io.vertx.core.Future#completer()} that completes a future with the operation result or failure. It avoids having to write the _traditional_: `if success then complete the future else fail the future`. == Verticles Vert.x comes with a simple, scalable, _actor-like_ deployment and concurrency model out of the box that you can use to save you writing your own. *This model is entirely optional and Vert.x does not force you to create your applications in this way if you don't want to.*. The model does not claim to be a strict actor-model implementation, but it does share similarities especially with respect to concurrency, scaling and deployment. To use this model, you write your code as set of *verticles*. Verticles are chunks of code that get deployed and run by Vert.x. A Vert.x instance maintains N event loop threads (where N by default is core*2) by default. Verticles can be written in any of the languages that Vert.x supports and a single application can include verticles written in multiple languages. You can think of a verticle as a bit like an actor in the http://en.wikipedia.org/wiki/Actor_model[Actor Model]. An application would typically be composed of many verticle instances running in the same Vert.x instance at the same time. The different verticle instances communicate with each other by sending messages on the <>. include::override/verticles.adoc[] === Verticle Types There are three different types of verticles: Standard Verticles:: These are the most common and useful type - they are always executed using an event loop thread. We'll discuss this more in the next section. Worker Verticles:: These run using a thread from the worker pool. An instance is never executed concurrently by more than one thread. Multi-threaded worker verticles:: These run using a thread from the worker pool. An instance can be executed concurrently by more than one thread. === Standard verticles Standard verticles are assigned an event loop thread when they are created and the +start+ method is called with that event loop. When you call any other methods that takes a handler on a core API from an event loop then Vert.x will guarantee that those handlers, when called, will be executed on the same event loop. This means we can guarantee that all the code in your verticle instance is always executed on the same event loop (as long as you don't create your own threads and call it!). This means you can write all the code in your application as single threaded and let Vert.x worry about the threading and scaling. No more worrying about +synchronized+ and +volatile+ any more, and you also avoid many other cases of race conditions and deadlock so prevalent when doing hand-rolled 'traditional' multi-threaded application development. [[worker_verticles]] === Worker verticles A worker verticle is just like a standard verticle but it's executed using a thread from the Vert.x worker thread pool, rather than using an event loop. Worker verticles are designed for calling blocking code, as they won't block any event loops. If you don't want to use a worker verticle to run blocking code, you can also run <> directly while on an event loop. If you want to deploy a verticle as a worker verticle you do that with {@link io.vertx.core.DeploymentOptions#setWorker}. [source,$lang] ---- {@link examples.CoreExamples#example7_1} ---- Worker verticle instances are never executed concurrently by Vert.x by more than one thread, but can executed by different threads at different times. ==== Multi-threaded worker verticles A multi-threaded worker verticle is just like a normal worker verticle but it *can* be executed concurrently by different threads. WARNING: Multi-threaded worker verticles are an advanced feature and most applications will have no need for them. Because of the concurrency in these verticles you have to be very careful to keep the verticle in a consistent state using standard Java techniques for multi-threaded programming. === Deploying verticles programmatically You can deploy a verticle using one of the {@link io.vertx.core.Vertx#deployVerticle} method, specifying a verticle name or you can pass in a verticle instance you have already created yourself. NOTE: Deploying Verticle *instances* is Java only. [source,java] ---- {@link examples.CoreExamples#example8} ---- You can also deploy verticles by specifying the verticle *name*. The verticle name is used to look up the specific {@link io.vertx.core.spi.VerticleFactory} that will be used to instantiate the actual verticle instance(s). Different verticle factories are available for instantiating verticles in different languages and for various other reasons such as loading services and getting verticles from Maven at run-time. This allows you to deploy verticles written in any language from any other language that Vert.x supports. Here's an example of deploying some different types of verticles: [source,$lang] ---- {@link examples.CoreExamples#example9} ---- === Rules for mapping a verticle name to a verticle factory When deploying verticle(s) using a name, the name is used to select the actual verticle factory that will instantiate the verticle(s). Verticle names can have a prefix - which is a string followed by a colon, which if present will be used to look-up the factory, e.g. js:foo.js // Use the JavaScript verticle factory groovy:com.mycompany.SomeGroovyCompiledVerticle // Use the Groovy verticle factory service:com.mycompany:myorderservice // Uses the service verticle factory If no prefix is present, Vert.x will look for a suffix and use that to lookup the factory, e.g. foo.js // Will also use the JavaScript verticle factory SomeScript.groovy // Will use the Groovy verticle factory If no prefix or suffix is present, Vert.x will assume it's a Java fully qualified class name (FQCN) and try and instantiate that. === How are Verticle Factories located? Most Verticle factories are loaded from the classpath and registered at Vert.x startup. You can also programmatically register and unregister verticle factories using {@link io.vertx.core.Vertx#registerVerticleFactory} and {@link io.vertx.core.Vertx#unregisterVerticleFactory} if you wish. === Waiting for deployment to complete Verticle deployment is asynchronous and may complete some time after the call to deploy has returned. If you want to be notified when deployment is complete you can deploy specifying a completion handler: [source,$lang] ---- {@link examples.CoreExamples#example10} ---- The completion handler will be passed a result containing the deployment ID string, if deployment succeeded. This deployment ID can be used later if you want to undeploy the deployment. === Undeploying verticle deployments Deployments can be undeployed with {@link io.vertx.core.Vertx#undeploy}. Un-deployment is itself asynchronous so if you want to be notified when un-deployment is complete you can deploy specifying a completion handler: [source,$lang] ---- {@link examples.CoreExamples#example11} ---- === Specifying number of verticle instances When deploying a verticle using a verticle name, you can specify the number of verticle instances that you want to deploy: [source,$lang] ---- {@link examples.CoreExamples#example12} ---- This is useful for scaling easily across multiple cores. For example you might have a web-server verticle to deploy and multiple cores on your machine, so you want to deploy multiple instances to utilise all the cores. include::override/verticle-configuration.adoc[] === Verticle Isolation Groups By default, Vert.x has a _flat classpath_. I.e, when Vert.x deploys verticles it does so with the current classloader - it doesn't create a new one. In the majority of cases this is the simplest, clearest, and sanest thing to do. However, in some cases you may want to deploy a verticle so the classes of that verticle are isolated from others in your application. This might be the case, for example, if you want to deploy two different versions of a verticle with the same class name in the same Vert.x instance, or if you have two different verticles which use different versions of the same jar library. When using an isolation group you provide a list of the class names that you want isolated using {@link io.vertx.core.DeploymentOptions#setIsolatedClasses(java.util.List)}- an entry can be a fully qualified classname such as `com.mycompany.myproject.engine.MyClass` or it can be a wildcard which will match any classes in a package and any sub-packages, e.g. `com.mycompany.myproject.*` would match any classes in the package `com.mycompany.myproject` or any sub-packages. Please note that _only_ the classes that match will be isolated - any other classes will be loaded by the current class loader. Extra classpath entries can also be provided with {@link io.vertx.core.DeploymentOptions#setExtraClasspath} so if you want to load classes or resources that aren't already present on the main classpath you can add this. WARNING: Use this feature with caution. Class-loaders can be a can of worms, and can make debugging difficult, amongst other things. Here's an example of using an isolation group to isolate a verticle deployment. [source,$lang] ---- {@link examples.CoreExamples#example14} ---- === High Availability Verticles can be deployed with High Availability (HA) enabled. In that context, when a verticle is deployed on a vert.x instance that dies abruptly, the verticle is redeployed on another vert.x instance from the cluster. To run an verticle with the high availability enabled, just append the `-ha` switch: [source] ---- vertx run my-verticle.js -ha ---- When enabling high availability, no need to add `-cluster`. More details about the high availability feature and configuration in the <> section. === Running Verticles from the command line You can use Vert.x directly in your Maven or Gradle projects in the normal way by adding a dependency to the Vert.x core library and hacking from there. However you can also run Vert.x verticles directly from the command line if you wish. To do this you need to download and install a Vert.x distribution, and add the `bin` directory of the installation to your `PATH` environment variable. Also make sure you have a Java 8 JDK on your `PATH`. NOTE: The JDK is required to support on the fly compilation of Java code. You can now run verticles by using the `vertx run` command. Here are some examples: ---- # Run a JavaScript verticle vertx run my_verticle.js # Run a Ruby verticle vertx run a_n_other_verticle.rb # Run a Groovy script verticle, clustered vertx run FooVerticle.groovy -cluster ---- You can even run Java source verticles without compiling them first! ---- vertx run SomeJavaSourceFile.java ---- Vert.x will compile the Java source file on the fly before running it. This is really useful for quickly prototyping verticles and great for demos. No need to set-up a Maven or Gradle build first to get going! For full information on the various options available when executing `vertx` on the command line, type `vertx` at the command line. === Causing Vert.x to exit Threads maintained by Vert.x instances are not daemon threads so they will prevent the JVM from exiting. If you are embedding Vert.x and you have finished with it, you can call {@link io.vertx.core.Vertx#close} to close it down. This will shut-down all internal thread pools and close other resources, and will allow the JVM to exit. === The Context object When Vert.x provides an event to a handler or calls the start or stop methods of a {@link io.vertx.core.Verticle}, the execution is associated with a `Context`. Usually a context is an *event-loop context* and is tied to a specific event loop thread. So executions for that context always occur on that exact same event loop thread. In the case of worker verticles and running inline blocking code a worker context will be associated with the execution which will use a thread from the worker thread pool. To retrieve the context, use the {@link io.vertx.core.Vertx#getOrCreateContext()} method: [source, $lang] ---- {@link examples.CoreExamples#retrieveContext(io.vertx.core.Vertx)} ---- If the current thread has a context associated with it, it reuses the context object. If not a new instance of context is created. You can test the _type_ of context you have retrieved: [source, $lang] ---- {@link examples.CoreExamples#retrieveContextType(io.vertx.core.Vertx)} ---- When you have retrieved the context object, you can run code in this context asynchronously. In other words, you submit a task that will be eventually run in the same context, but later: [source, $lang] ---- {@link examples.CoreExamples#runInContext(io.vertx.core.Vertx)} ---- When several handlers run in the same context, they may want to share data. The context object offers methods to store and retrieve data shared in the context. For instance, it lets you pass data to some action run with {@link io.vertx.core.Context#runOnContext(io.vertx.core.Handler)}: [source, $lang] ---- {@link examples.CoreExamples#runInContextWithData(io.vertx.core.Vertx)} ---- The context object also let you access verticle configuration using the {@link io.vertx.core.Context#config()} method. Check the <> section for more details about this configuration. === Executing periodic and delayed actions It's very common in Vert.x to want to perform an action after a delay, or periodically. In standard verticles you can't just make the thread sleep to introduce a delay, as that will block the event loop thread. Instead you use Vert.x timers. Timers can be *one-shot* or *periodic*. We'll discuss both ==== One-shot Timers A one shot timer calls an event handler after a certain delay, expressed in milliseconds. To set a timer to fire once you use {@link io.vertx.core.Vertx#setTimer} method passing in the delay and a handler [source,$lang] ---- {@link examples.CoreExamples#example15} ---- The return value is a unique timer id which can later be used to cancel the timer. The handler is also passed the timer id. ==== Periodic Timers You can also set a timer to fire periodically by using {@link io.vertx.core.Vertx#setPeriodic}. There will be an initial delay equal to the period. The return value of `setPeriodic` is a unique timer id (long). This can be later used if the timer needs to be cancelled. The argument passed into the timer event handler is also the unique timer id: Keep in mind that the timer will fire on a periodic basis. If your periodic treatment takes a long amount of time to proceed, your timer events could run continuously or even worse : stack up. In this case, you should consider using {@link io.vertx.core.Vertx#setTimer} instead. Once your treatment has finished, you can set the next timer. [source,$lang] ---- {@link examples.CoreExamples#example16} ---- ==== Cancelling timers To cancel a periodic timer, call {@link io.vertx.core.Vertx#cancelTimer} specifying the timer id. For example: [source,$lang] ---- {@link examples.CoreExamples#example17} ---- ==== Automatic clean-up in verticles If you're creating timers from inside verticles, those timers will be automatically closed when the verticle is undeployed. === Verticle worker pool Verticles use the Vert.x worker pool for executing blocking actions, i.e {@link io.vertx.core.Context#executeBlocking} or worker verticle. A different worker pool can be specified in deployment options: [source,$lang] ---- {@link examples.CoreExamples#deployVerticleWithDifferentWorkerPool} ---- [[event_bus]] include::eventbus.adoc[] include::override/json.adoc[] include::buffers.adoc[] include::net.adoc[] include::http.adoc[] include::shareddata.adoc[] include::filesystem.adoc[] include::datagrams.adoc[] include::dns.adoc[] [[streams]] include::streams.adoc[] include::parsetools.adoc[] == Thread safety Most Vert.x objects are safe to access from different threads. _However_ performance is optimised when they are accessed from the same context they were created from. For example if you have deployed a verticle which creates a {@link io.vertx.core.net.NetServer} which provides {@link io.vertx.core.net.NetSocket} instances in it's handler, then it's best to always access that socket instance from the event loop of the verticle. If you stick to the standard Vert.x verticle deployment model and avoid sharing objects between verticles then this should be the case without you having to think about it. == Metrics SPI By default Vert.x does not record any metrics. Instead it provides an SPI for others to implement which can be added to the classpath. The metrics SPI is an advanced feature which allows implementers to capture events from Vert.x in order to gather metrics. For more information on this, please consult the {@link io.vertx.core.spi.metrics.VertxMetrics API Documentation}. You can also specify a metrics factory programmatically if embedding Vert.x using {@link io.vertx.core.metrics.MetricsOptions#setFactory(io.vertx.core.spi.VertxMetricsFactory)}. == OSGi Vert.x Core is packaged as an OSGi bundle, so can be used in any OSGi R4.2+ environment such as Apache Felix or Eclipse Equinox. The bundle exports `io.vertx.core*`. However, the bundle has some dependencies on Jackson and Netty. To get the vert.x core bundle resolved deploy: * Jackson Annotation [2.6.0,3) * Jackson Core [2.6.2,3) * Jackson Databind [2.6.2,3) * Netty Buffer [4.0.31,5) * Netty Codec [4.0.31,5) * Netty Codec/Socks [4.0.31,5) * Netty Codec/Common [4.0.31,5) * Netty Codec/Handler [4.0.31,5) * Netty Codec/Transport [4.0.31,5) Here is a working deployment on Apache Felix 5.2.0: [source] ---- 14|Active | 1|Jackson-annotations (2.6.0) 15|Active | 1|Jackson-core (2.6.2) 16|Active | 1|jackson-databind (2.6.2) 18|Active | 1|Netty/Buffer (4.0.31.Final) 19|Active | 1|Netty/Codec (4.0.31.Final) 20|Active | 1|Netty/Codec/HTTP (4.0.31.Final) 21|Active | 1|Netty/Codec/Socks (4.0.31.Final) 22|Active | 1|Netty/Common (4.0.31.Final) 23|Active | 1|Netty/Handler (4.0.31.Final) 24|Active | 1|Netty/Transport (4.0.31.Final) 25|Active | 1|Netty/Transport/SCTP (4.0.31.Final) 26|Active | 1|Vert.x Core (3.1.0) ---- On Equinox, you may want to disable the `ContextFinder` with the following framework property: `eclipse.bundle.setTCCL=false` == The 'vertx' command line The `vertx` command is used to interact with Vert.x from the command line. It's main use is to run Vert.x verticles. To do this you need to download and install a Vert.x distribution, and add the `bin` directory of the installation to your `PATH` environment variable. Also make sure you have a Java 8 JDK on your `PATH`. NOTE: The JDK is required to support on the fly compilation of Java code. === Run verticles You can run raw Vert.x verticles directly from the command line using `vertx run`. Here is a couple of examples of the `run` _command_: [source] ---- vertx run my-verticle.js (1) vertx run my-verticle.groovy (2) vertx run my-verticle.rb (3) vertx run io.vertx.example.MyVerticle (4) vertx run io.vertx.example.MVerticle -cp my-verticle.jar (5) vertx run MyVerticle.java (6) ---- 1. Deploys a JavaScript verticle 2. Deploys a Groovy verticle 3. Deploys a Ruby verticle 4. Deploys an already compiled Java verticle. Classpath root is the current directory 5. Deploys a verticle packaged in a Jar, the jar need to be in the classpath 6. Compiles the Java source and deploys it As you can see in the case of Java, the name can either be the fully qualified class name of the verticle, or you can specify the Java Source file directly and Vert.x compiles it for you. You can also prefix the verticle with the name of the language implementation to use. For example if the verticle is a compiled Groovy class, you prefix it with `groovy:` so that Vert.x knows it's a Groovy class not a Java class. [source] ---- vertx run groovy:io.vertx.example.MyGroovyVerticle ---- The `vertx run` command can take a few optional parameters, they are: * `-conf ` - Provides some configuration to the verticle. `config_file` is the name of a text file containing a JSON object that represents the configuration for the verticle. This is optional. * `-cp ` - The path on which to search for the verticle and any other resources used by the verticle. This defaults to `.` (current directory). If your verticle references other scripts, classes or other resources (e.g. jar files) then make sure these are on this path. The path can contain multiple path entries separated by `:` (colon) or `;` (semi-colon) depending on the operating system. Each path entry can be an absolute or relative path to a directory containing scripts, or absolute or relative filenames for jar or zip files. An example path might be `-cp classes:lib/otherscripts:jars/myjar.jar:jars/otherjar.jar`. Always use the path to reference any resources that your verticle requires. Do **not** put them on the system classpath as this can cause isolation issues between deployed verticles. * `-instances ` - The number of instances of the verticle to instantiate. Each verticle instance is strictly single threaded so to scale your application across available cores you might want to deploy more than one instance. If omitted a single instance will be deployed. * `-worker` - This option determines whether the verticle is a worker verticle or not. * `-cluster` - This option determines whether the Vert.x instance will attempt to form a cluster with other Vert.x instances on the network. Clustering Vert.x instances allows Vert.x to form a distributed event bus with other nodes. Default is `false` (not clustered). * `-cluster-port` - If the cluster option has also been specified then this determines which port will be used for cluster communication with other Vert.x instances. Default is `0` - which means '_choose a free random port_'. You don't usually need to specify this parameter unless you really need to bind to a specific port. * `-cluster-host` - If the cluster option has also been specified then this determines which host address will be used for cluster communication with other Vert.x instances. By default it will try and pick one from the available interfaces. If you have more than one interface and you want to use a specific one, specify it here. * `-ha` - if specified the verticle will be deployed as high availability (HA) deployment. See related section for more details * `-quorum` - used in conjunction with `-ha`. It specifies the minimum number of nodes in the cluster for any _HA deploymentIDs_ to be active. Defaults to 0. * `-hagroup` - used in conjunction with `-ha`. It specifies the HA group this node will join. There can be multiple HA groups in a cluster. Nodes will only failover to other nodes in the same group. The default value is ` +++__DEFAULT__+++` You can also set system properties using: `-Dkey=value`. Here are some more examples: Run a JavaScript verticle server.js with default settings [source] ---- vertx run server.js ---- Run 10 instances of a pre-compiled Java verticle specifying classpath [source] ---- vertx run com.acme.MyVerticle -cp ""classes:lib/myjar.jar"" -instances 10 ---- Run 10 instances of a Java verticle by source _file_ [source] ---- vertx run MyVerticle.java -instances 10 ---- Run 20 instances of a ruby worker verticle [source] ---- vertx run order_worker.rb -instances 20 -worker ---- Run two JavaScript verticles on the same machine and let them cluster together with each other and any other servers on the network [source] ---- vertx run handler.js -cluster vertx run sender.js -cluster ---- Run a Ruby verticle passing it some config [source] ---- vertx run my_verticle.rb -conf my_verticle.conf ---- Where `my_verticle.conf` might contain something like: [source, json] ---- { ""name"": ""foo"", ""num_widgets"": 46 } ---- The config will be available inside the verticle via the core API. When using the high-availability feature of vert.x you may want to create a _bare_ instance of vert.x. This instance does not deploy any verticles when launched, but will receive a verticle if another node of the cluster dies. To create a _bare_ instance, launch: [source] ---- vertx bare ---- Depending on your cluster configuration, you may have to append the `cluster-host` and `cluster-port` parameters. === Executing a Vert.x application packaged as a fat jar A _fat jar_ is an executable jar embedding its dependencies. This means you don't have to have Vert.x pre-installed on the machine on which you execute the jar. Like any executable Java jar it can be executed with. [source] ---- java -jar my-application-fat.jar ---- There is nothing really Vert.x specific about this, you could do this with any Java application You can either create your own main class and specify that in the manifest, but it's recommended that you write your code as verticles and use the Vert.x {@link io.vertx.core.Launcher} class (`io.vertx.core.Launcher`) as your main class. This is the same main class used when running Vert.x at the command line and therefore allows you to specify command line arguments, such as `-instances` in order to scale your application more easily. To deploy your verticle in a _fatjar_ like this you must have a _manifest_ with: * `Main-Class` set to `io.vertx.core.Launcher` * `Main-Verticle` specifying the main verticle (fully qualified class name or script file name) You can also provide the usual command line arguments that you would pass to `vertx run`: [source] ---- java -jar my-verticle-fat.jar -cluster -conf myconf.json java -jar my-verticle-fat.jar -cluster -conf myconf.json -cp path/to/dir/conf/cluster_xml ---- NOTE: Please consult the Maven/Gradle simplest and Maven/Gradle verticle examples in the examples repository for examples of building applications as fatjars. A fat jar executes the `run` command, by default. === Displaying version of Vert.x To display the vert.x version, just launch: [source] ---- vertx version ---- === Other commands The `vertx` command line and the `Launcher` also provide other _commands_ in addition to `run` and `version`: You can create a `bare` instance using: [source] ---- vertx bare # or java -jar my-verticle-fat.jar bare ---- You can also start an application in background using: [source] ---- java -jar my-verticle-fat.jar start -Dvertx-id=my-app-name ---- If `my-app-name` is not set, a random id will be generated, and printed on the command prompt. You can pass `run` options to the `start` command: [source] ---- java -jar my-verticle-fat.jar start -Dvertx-id=my-app-name -cluster ---- Once launched in background, you can stop it with the `stop` command: [source] ---- java -jar my-verticle-fat.jar stop my-app-name ---- You can also list the vert.x application launched in background using: [source] ---- java -jar my-verticle-fat.jar list ---- The `start`, `stop` and `list` command are also available from the `vertx` tool. The start` command supports a couple of options: * `vertx-id` : the application id, uses a random UUID if not set * `java-opts` : the Java Virtual Machine options, uses the `JAVA_OPTS` environment variable if not set. * `redirect-output` : redirect the spawned process output and error streams to the parent process streams. If option values contain spaces, don't forget to wrap the value between {@code """"} (double-quotes). As the `start` command spawns a new process, the java options passed to the JVM are not propagated, so you **must** use `java-opts` to configure the JVM (`-X`, `-D`...). If you use the `CLASSPATH` environment variable, be sure it contains all the required jars (vertx-core, your jars and all the dependencies). The set of commands is extensible, refer to the <> section. === Live Redeploy When developing it may be convenient to automatically redeploy your application upon file changes. The `vertx` command line tool and more generally the {@link io.vertx.core.Launcher} class offers this feature. Here are some examples: [source] ---- vertx run MyVerticle.groovy --redeploy=""**/*.groovy"" --launcher-class=io.vertx.core.Launcher vertx run MyVerticle.groovy --redeploy=""**/*.groovy,**/*.rb"" --launcher-class=io.vertx.core.Launcher java io.vertx.core.Launcher run org.acme.MyVerticle --redeploy=""**/*.class"" --launcher-class=io.vertx.core .Launcher -cp ... ---- The redeployment process is implemented as follows. First your application is launched as a background application (with the `start` command). On matching file changes, the process is stopped and the application is restarted. This avoids leaks, as the process is restarted. To enable the live redeploy, pass the `--redeploy` option to the `run` command. The `--redeploy` indicates the set of file to _watch_. This set can use Ant-style patterns (with `\\**`, `*` and `?`). You can specify several sets by separating them using a comma (`,`). Patterns are relative to the current working directory. Parameters passed to the `run` command are passed to the application. Java Virtual Machine options can be configured using `--java-opts`. For instance, to pass the the `conf` parameter or a system property, you need to use: `--java-opts=""-conf=my-conf.json -Dkey=value""` The `--launcher-class` option determine with with _main_ class the application is launcher. It's generally {@link io.vertx.core.Launcher}, but you have use you own _main_. The redeploy feature can be used in your IDE: * Eclipse - create a _Run_ configuration, using the `io.vertx.core.Launcher` class a _main class_. In the _Program arguments_ area (in the _Arguments_ tab), write `run your-verticle-fully-qualified-name --redeploy=\\**/*.java --launcher-class=io.vertx.core.Launcher`. You can also add other parameters. The redeployment works smoothly as Eclipse incrementally compiles your files on save. * IntelliJ - create a _Run_ configuration (_Application_), set the _Main class_ to `io.vertx.core.Launcher`. In the Program arguments write: `run your-verticle-fully-qualified-name --redeploy=\\**/*.class --launcher-class=io.vertx.core.Launcher`. To trigger the redeployment, you need to _make_ the project or the module explicitly (_Build_ menu -> _Make project_). To debug your application, create your run configuration as a remote application and configure the debugger using `--java-opts`. However, don't forget to re-plug the debugger after every redeployment as a new process is created every time. You can also hook your build process in the redeploy cycle: [source] ---- java -jar target/my-fat-jar.jar --redeploy=""**/*.java"" --on-redeploy=""mvn package"" java -jar build/libs/my-fat-jar.jar --redeploy=""src/**/*.java"" --on-redeploy='./gradlew shadowJar' ---- The ""on-redeploy"" option specifies a command invoked after the shutdown of the application and before the restart. So you can hook your build tool if it updates some runtime artifacts. For instance, you can launch `gulp` or `grunt` to update your resources. Don't forget that passing parameters to your application requires the `--java-opts` param: [source] ---- java -jar target/my-fat-jar.jar --redeploy=""**/*.java"" --on-redeploy=""mvn package"" --java-opts=""-Dkey=val"" java -jar build/libs/my-fat-jar.jar --redeploy=""src/**/*.java"" --on-redeploy='./gradlew shadowJar' --java-opts=""-Dkey=val"" ---- The redeploy feature also supports the following settings: * `redeploy-scan-period` : the file system check period (in milliseconds), 250ms by default * `redeploy-grace-period` : the amount of time (in milliseconds) to wait between 2 re-deployments, 1000ms by default * `redeploy-termination-period` : the amount of time to wait after having stopped the application (before launching user command). This is useful on Windows, where the process is not killed immediately. The time is given in milliseconds. 0 ms by default. == Cluster Managers In Vert.x a cluster manager is used for various functions including: * Discovery and group membership of Vert.x nodes in a cluster * Maintaining cluster wide topic subscriber lists (so we know which nodes are interested in which event bus addresses) * Distributed Map support * Distributed Locks * Distributed Counters Cluster managers _do not_ handle the event bus inter-node transport, this is done directly by Vert.x with TCP connections. The default cluster manager used in the Vert.x distributions is one that uses http://hazelcast.com[Hazelcast] but this can be easily replaced by a different implementation as Vert.x cluster managers are pluggable. A cluster manager must implement the interface {@link io.vertx.core.spi.cluster.ClusterManager}. Vert.x locates cluster managers at run-time by using the Java https://docs.oracle.com/javase/8/docs/api/java/util/ServiceLoader.html[Service Loader] functionality to locate instances of {@link io.vertx.core.spi.cluster.ClusterManager} on the classpath. If you are using Vert.x at the command line and you want to use clustering you should make sure the `lib` directory of the Vert.x installation contains your cluster manager jar. If you are using Vert.x from a Maven or Gradle project just add the cluster manager jar as a dependency of your project. You can also specify cluster managers programmatically if embedding Vert.x using {@link io.vertx.core.VertxOptions#setClusterManager(io.vertx.core.spi.cluster.ClusterManager)}. == Logging Vert.x logs using it's in-built logging API. The default implementation uses the JDK (JUL) logging so no extra logging dependencies are needed. === Configuring JUL logging A JUL logging configuration file can be specified in the normal JUL way by providing a system property called: `java.util.logging.config.file` with the value being your configuration file. For more information on this and the structure of a JUL config file please consult the JUL logging documentation. Vert.x also provides a slightly more convenient way to specify a configuration file without having to set a system property. Just provide a JUL config file with the name `vertx-default-jul-logging.properties` on your classpath (e.g. inside your fatjar) and Vert.x will use that to configure JUL. === Using another logging framework If you don't want Vert.x to use JUL for it's own logging you can configure it to use another logging framework, e.g. Log4J or SLF4J. To do this you should set a system property called `vertx.logger-delegate-factory-class-name` with the name of a Java class which implements the interface {@link io.vertx.core.spi.logging.LogDelegateFactory}. We provide pre-built implementations for Log4J (version 1), Log4J 2 and SLF4J with the class names `io.vertx.core.logging.Log4jLogDelegateFactory`, `io.vertx.core.logging.Log4j2LogDelegateFactory` and `io.vertx.core.logging.SLF4JLogDelegateFactory` respectively. If you want to use these implementations you should also make sure the relevant Log4J or SLF4J jars are on your classpath. Notice that, the provided delegate for Log4J 1 does not support parameterized message. The delegate for Log4J 2 uses the `{}` syntax like the SLF4J delegate. JUL delegate uses the `{x}` syntax. === Logging from your application Vert.x itself is just a library and you can use whatever logging library you prefer to log from your own application, using that logging library's API. However, if you prefer you can use the Vert.x logging facility as described above to provide logging for your application too. To do that you use {@link io.vertx.core.logging.LoggerFactory} to get an instance of {@link io.vertx.core.logging.Logger} which you then use for logging, e.g. [source,$lang] ---- {@link examples.CoreExamples#example18} ---- CAUTION: Logging backends use different formats to represent replaceable tokens in parameterized messages. As a consequence, if you rely on Vert.x parameterized logging methods, you won't be able to switch backends without changing your code. [[netty-logging]] === Netty logging When configuring logging, you should care about configuring Netty logging as well. Netty does not rely on external logging configuration (e.g system properties) and instead implements a logging configuration based on the logging libraries visible from the Netty classes: - use `SLF4J` library if it is visible - otherwise use `Log4j` if it is visible - otherwise fallback `java.util.logging` The logger implementation can be forced to a specific implementation by setting Netty's internal logger implementation directly on `io.netty.util.internal.logging.InternalLoggerFactory`: [source,java] ---- // Force logging to Log4j InternalLoggerFactory.setDefaultFactory(Log4JLoggerFactory.INSTANCE); ---- === Troubleshooting ==== SLF4J warning at startup If, when you start your application, you see the following message: ---- SLF4J: Failed to load class ""org.slf4j.impl.StaticLoggerBinder"". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. ---- It means that you have SLF4J-API in your classpath but no actual binding. Messages logged with SLF4J will be dropped. You should add a binding to your classpath. Check https://www.slf4j.org/manual.html#swapping to pick a binding and configure it. Be aware that Netty looks for the SLF4-API jar and uses it by default. ==== Connection reset by peer If your logs show a bunch of: ---- io.vertx.core.net.impl.ConnectionBase SEVERE: java.io.IOException: Connection reset by peer ---- It means that the client is resetting the HTTP connection instead of closing it. This message also indicates that you may have not consumed the complete payload (the connection was cut before you were able to). == Host name resolution Vert.x uses an an address resolver for resolving host name into IP addresses instead of the JVM built-in blocking resolver. An host name resolves to an IP address using: - the _hosts_ file of the operating system - otherwise DNS queries against a list of servers By default it will use the list of the system DNS server addresses from the environment, if that list cannot be retrieved it will use Google's public DNS servers `""8.8.8.8""` and `""8.8.4.4""`. DNS servers can be also configured when creating a {@link io.vertx.core.Vertx} instance: [source,$lang] ---- {@link examples.CoreExamples#configureDNSServers} ---- The default port of a DNS server is `53`, when a server uses a different port, this port can be set using a colon delimiter: `192.168.0.2:40000`. NOTE: sometimes it can be desirable to use the JVM built-in resolver, the JVM system property _-Dvertx.disableDnsResolver=true_ activates this behavior === Failover When a server does not reply in a timely manner, the resolver will try the next one from the list, the search is limited by {@link io.vertx.core.dns.AddressResolverOptions#setMaxQueries(int)} (the default value is `4` queries). A DNS query is considered as failed when the resolver has not received a correct answer within {@link io.vertx.core.dns.AddressResolverOptions#getQueryTimeout()} milliseconds (the default value is `5` seconds). === Server list rotation By default the dns server selection uses the first one, the remaining servers are used for failover. You can configure {@link io.vertx.core.dns.AddressResolverOptions#setRotateServers(boolean)} to `true` to let the resolver perform a round-robin selection instead. It spreads the query load among the servers and avoids all lookup to hit the first server of the list. Failover still applies and will use the next server in the list. === Hosts mapping The _hosts_ file of the operating system is used to perform an hostname lookup for an ipaddress. An alternative _hosts_ file can be used instead: [source,$lang] ---- {@link examples.CoreExamples#configureHosts} ---- === Search domains By default the resolver will use the system DNS search domains from the environment. Alternatively an explicit search domain list can be provided: [source,$lang] ---- {@link examples.CoreExamples#configureSearchDomains()} ---- When a search domain list is used, the threshold for the number of dots is {@code 1} or loaded from `/etc/resolv.conf` on Linux, it can be configured to a specific value with {@link io.vertx.core.dns.AddressResolverOptions#setNdots(int)}. == High Availability and Fail-Over Vert.x allows you to run your verticles with high availability (HA) support. In that case, when a vert.x instance running a verticle dies abruptly, the verticle is migrated to another vertx instance. The vert.x instances must be in the same cluster. === Automatic failover When vert.x runs with _HA_ enabled, if a vert.x instance where a verticle runs fails or dies, the verticle is redeployed automatically on another vert.x instance of the cluster. We call this _verticle fail-over_. To run vert.x with the _HA_ enabled, just add the `-ha` flag to the command line: [source] ---- vertx run my-verticle.js -ha ---- Now for HA to work, you need more than one Vert.x instances in the cluster, so let's say you have another Vert.x instance that you have already started, for example: [source] ---- vertx run my-other-verticle.js -ha ---- If the Vert.x instance that is running `my-verticle.js` now dies (you can test this by killing the process with `kill -9`), the Vert.x instance that is running `my-other-verticle.js` will automatic deploy `my-verticle .js` so now that Vert.x instance is running both verticles. NOTE: the migration is only possible if the second vert.x instance has access to the verticle file (here `my-verticle.js`). IMPORTANT: Please note that cleanly closing a Vert.x instance will not cause failover to occur, e.g. `CTRL-C` or `kill -SIGINT` You can also start _bare_ Vert.x instances - i.e. instances that are not initially running any verticles, they will also failover for nodes in the cluster. To start a bare instance you simply do: [source] ---- vertx run -ha ---- When using the `-ha` switch you do not need to provide the `-cluster` switch, as a cluster is assumed if you want HA. NOTE: depending on your cluster configuration, you may need to customize the cluster manager configuration (Hazelcast by default), and/or add the `cluster-host` and `cluster-port` parameters. === HA groups When running a Vert.x instance with HA you can also optional specify a _HA group_. A HA group denotes a logical group of nodes in the cluster. Only nodes with the same HA group will failover onto one another. If you don't specify a HA group the default group `+++__DEFAULT__+++` is used. To specify an HA group you use the `-hagroup` switch when running the verticle, e.g. [source] ---- vertx run my-verticle.js -ha -hagroup my-group ---- Let's look at an example: In a first terminal: [source] ---- vertx run my-verticle.js -ha -hagroup g1 ---- In a second terminal, let's run another verticle using the same group: [source] ---- vertx run my-other-verticle.js -ha -hagroup g1 ---- Finally, in a third terminal, launch another verticle using a different group: [source] ---- vertx run yet-another-verticle.js -ha -hagroup g2 ---- If we kill the instance in terminal 1, it will fail over to the instance in terminal 2, not the instance in terminal 3 as that has a different group. If we kill the instance in terminal 3, it won't get failed over as there is no other vert.x instance in that group. === Dealing with network partitions - Quora The HA implementation also supports quora. A quorum is the minimum number of votes that a distributed transaction has to obtain in order to be allowed to perform an operation in a distributed system. When starting a Vert.x instance you can instruct it that it requires a `quorum` before any HA deployments will be deployed. In this context, a quorum is a minimum number of nodes for a particular group in the cluster. Typically you chose your quorum size to `Q = 1 + N/2` where `N` is the number of nodes in the group. If there are less than `Q` nodes in the cluster the HA deployments will undeploy. They will redeploy again if/when a quorum is re-attained. By doing this you can prevent against network partitions, a.k.a. _split brain_. There is more information on quora http://en.wikipedia.org/wiki/Quorum_(distributed_computing)[here]. To run vert.x instances with a quorum you specify `-quorum` on the command line, e.g. In a first terminal: [source] ---- vertx run my-verticle.js -ha -quorum 3 ---- At this point the Vert.x instance will start but not deploy the module (yet) because there is only one node in the cluster, not 3. In a second terminal: [source] ---- vertx run my-other-verticle.js -ha -quorum 3 ---- At this point the Vert.x instance will start but not deploy the module (yet) because there are only two nodes in the cluster, not 3. In a third console, you can start another instance of vert.x: [source] ---- vertx run yet-another-verticle.js -ha -quorum 3 ---- Yay! - we have three nodes, that's a quorum. At this point the modules will automatically deploy on all instances. If we now close or kill one of the nodes the modules will automatically undeploy on the other nodes, as there is no longer a quorum. Quora can also be used in conjunction with ha groups. In that case, quora are resolved for each particular group. == Native transports Vert.x can run with http://netty.io/wiki/native-transports.html[native transports] (when available) on BSD (OSX) and Linux: [source,$lang] ---- {@link examples.CoreExamples#configureNative()} ---- NOTE: preferring native transport will not prevent the application to execute, if your application requires native transport, you need to check {@link io.vertx.core.Vertx#isNativeTransportEnabled()}. === Native Linux Transport You need to add the following dependency in your classpath: [source,xml] ---- io.netty netty-transport-native-epoll 4.1.15.Final linux-x86_64 ---- Native on Linux gives you extra networking options: * SO_REUSEPORT * TCP_QUICKACK * TCP_CORK * TCP_FASTOPEN [source,$lang] ---- {@link examples.CoreExamples#configureLinuxOptions} ---- === Native BSD Transport You need to add the following dependency in your classpath: [source,xml] ---- io.netty netty-transport-native-epoll 4.1.15.Final osx-x86_64 ---- MacOS Sierra and above are supported. Native on BSD gives you extra networking options: * SO_REUSEPORT [source,$lang] ---- {@link examples.CoreExamples#configureBSDOptions} ---- === Domain sockets Natives provide support domain sockets for `NetServer`: [source,$lang] ---- {@link examples.CoreExamples#serverWithDomainSockets} ---- As well as `NetClient`: [source,$lang] ---- {@link examples.CoreExamples#clientWithDomainSockets} ---- NOTE: support for `HttpServer` and `HttpClient` can be expected in later versions of Vert.x == Security notes Vert.x is a toolkit, not an opinionated framework where we force you to do things in a certain way. This gives you great power as a developer but with that comes great responsibility. As with any toolkit, it's possible to write insecure applications, so you should always be careful when developing your application especially if it's exposed to the public (e.g. over the internet). === Web applications If writing a web application it's highly recommended that you use Vert.x-Web instead of Vert.x core directly for serving resources and handling file uploads. Vert.x-Web normalises the path in requests to prevent malicious clients from crafting URLs to access resources outside of the web root. Similarly for file uploads Vert.x-Web provides functionality for uploading to a known place on disk and does not rely on the filename provided by the client in the upload which could be crafted to upload to a different place on disk. Vert.x core itself does not provide such checks so it would be up to you as a developer to implement them yourself. === Clustered event bus traffic When clustering the event bus between different Vert.x nodes on a network, the traffic is sent un-encrypted across the wire, so do not use this if you have confidential data to send and your Vert.x nodes are not on a trusted network. === Standard security best practices Any service can have potentially vulnerabilities whether it's written using Vert.x or any other toolkit so always follow security best practice, especially if your service is public facing. For example you should always run them in a DMZ and with an user account that has limited rights in order to limit the extent of damage in case the service was compromised. == Vert.x Command Line Interface API include::cli.adoc[] == The vert.x Launcher The vert.x {@link io.vertx.core.Launcher} is used in _fat jar_ as main class, and by the `vertx` command line utility. It executes a set of _commands_ such as _run_, _bare_, _start_... === Extending the vert.x Launcher You can extend the set of command by implementing your own {@link io.vertx.core.spi.launcher.Command} (in Java only): [source, java] ---- @Name(""my-command"") @Summary(""A simple hello command."") public class MyCommand extends DefaultCommand { private String name; @Option(longName = ""name"", required = true) public void setName(String n) { this.name = n; } @Override public void run() throws CLIException { System.out.println(""Hello "" + name); } } ---- You also need an implementation of {@link io.vertx.core.spi.launcher.CommandFactory}: [source, java] ---- public class HelloCommandFactory extends DefaultCommandFactory { public HelloCommandFactory() { super(HelloCommand.class); } } ---- Then, create the `src/main/resources/META-INF/services/io.vertx.core.spi.launcher.CommandFactory` and add a line indicating the fully qualified name of the factory: ---- io.vertx.core.launcher.example.HelloCommandFactory ---- Builds the jar containing the command. Be sure to includes the SPI file (`META-INF/services/io.vertx.core.spi.launcher.CommandFactory`). Then, place the jar containing the command into the classpath of your fat-jar (or include it inside) or in the `lib` directory of your vert.x distribution, and you would be able to execute: [source] ---- vertx hello vert.x java -jar my-fat-jar.jar hello vert.x ---- === Using the Launcher in fat jars To use the {@link io.vertx.core.Launcher} class in a _fat-jar_ just set the `Main-Class` of the _MANIFEST_ to `io.vertx.core.Launcher`. In addition, set the `Main-Verticle` _MANIFEST_ entry to the name of your main verticle. By default, it executed the `run` command. However, you can configure the default command by setting the `Main-Command` _MANIFEST_ entry. The default command is used if the _fat jar_ is launched without a command. === Sub-classing the Launcher You can also create a sub-class of {@link io.vertx.core.Launcher} to start your application. The class has been designed to be easily extensible. A {@link io.vertx.core.Launcher} sub-class can: * customize the vert.x configuration in {@link io.vertx.core.Launcher#beforeStartingVertx(io.vertx.core.VertxOptions)} * retrieve the vert.x instance created by the ""run"" or ""bare"" command by overriding {@link io.vertx.core.Launcher#afterStartingVertx(io.vertx.core.Vertx)} * configure the default verticle and command with {@link io.vertx.core.impl.launcher.VertxCommandLauncher#getMainVerticle()} and {@link io.vertx.core.impl.launcher.VertxCommandLauncher#getDefaultCommand()} * add / remove commands using {@link io.vertx.core.impl.launcher.VertxCommandLauncher#register(java.lang.Class)} and {@link io.vertx.core.impl.launcher.VertxCommandLauncher#unregister(java.lang.String)} === Launcher and exit code When you use the {@link io.vertx.core.Launcher} class as main class, it uses the following exit code: * {@code 0} if the process ends smoothly, or if an uncaught error is thrown * {@code 1} for general purpose error * {@code 11} if Vert.x cannot be initialized * {@code 12} if a spawn process cannot be started, found or stopped. This error code is used by the `start` and `stop` command * {@code 14} if the system configuration is not meeting the system requirement (shc as java not found) * {@code 15} if the main verticle cannot be deployed == Configuring Vert.x cache When Vert.x needs to read a file from the classpath (embedded in a fat jar, in a jar form the classpath or a file that is on the classpath), it copies it to a cache directory. The reason behind this is simple: reading a file from a jar or from an input stream is blocking. So to avoid to pay the price every time, Vert.x copies the file to its cache directory and reads it from there every subsequent read. This behavior can be configured. First, by default, Vert.x uses `$CWD/.vertx` as cache directory. It creates a unique directory inside this one to avoid conflicts. This location can be configured by using the `vertx.cacheDirBase` system property. For instance if the current working directory is not writable (such as in an immutable container context), launch your application with: [source] ---- vertx run my.Verticle -Dvertx.cacheDirBase=/tmp/vertx-cache # or java -jar my-fat.jar vertx.cacheDirBase=/tmp/vertx-cache ---- IMPORTANT: the directory must be **writable**. When you are editing resources such as HTML, CSS or JavaScript, this cache mechanism can be annoying as it serves only the first version of the file (and so you won't see your edits if you reload your page). To avoid this behavior, launch your application with `-Dvertx.disableFileCaching=true`. With this setting, Vert.x still uses the cache, but always refresh the version stored in the cache with the original source. So if you edit a file served from the classpath and refresh your browser, Vert.x reads it from the classpath, copies it to the cache directory and serves it from there. Do not use this setting in production, it can kill your performances. Finally, you can disable completely the cache by using `-Dvertx.disableFileCPResolving=true`. This setting is not without consequences. Vert.x would be unable to read any files from the classpath (only from the file system). Be very careful when using this settings. ",16277,True,2618.810525788214,median "// tag::HeaderFullDisplayName[] = sqlparse.RepoObject_SqlModules_33_ObjectNormalized - 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[] 0090291C-9D61-EB11-84DC-A81E8446D5B0 // end::RepoObject_guid[] == RepoObject_FullDisplayName2 // tag::RepoObject_FullDisplayName2[] sqlparse.RepoObject_SqlModules_33_ObjectNormalized // 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[] 132911545 // end::SysObject_id[] == SysObject_modify_date // tag::SysObject_modify_date[] 2021-08-17 20:11:54 // end::SysObject_modify_date[] == AntoraColumnDetails // tag::AntoraColumnDetails[] [discrete] == _ [#column-repoobjectunderlineguid] === RepoObject_guid [cols=""d,8a,m,m,m""] |=== |1 |*RepoObject_guid* |uniqueidentifier |NOT NULL | |=== .Referenced Columns -- * xref:sqlparse.repoobject_sqlmodules_20_statement_children.adoc#column-repoobjectunderlineguid[+sqlparse.RepoObject_SqlModules_20_statement_children.RepoObject_guid+] -- [#column-normalized] === normalized [cols=""d,8a,m,m,m""] |=== |2 |*normalized* |nvarchar(max) |NULL | |=== .Referenced Columns -- * xref:sqlparse.repoobject_sqlmodules_20_statement_children.adoc#column-normalized[+sqlparse.RepoObject_SqlModules_20_statement_children.normalized+] -- [#column-minunderlinerownumberunderlineperunderlinenormalized] === Min_RowNumber_per_normalized [cols=""d,8a,m,m,m""] |=== | |Min_RowNumber_per_normalized |bigint |NULL | |=== .Referencing Columns -- * xref:sqlparse.repoobject_sqlmodules_39_object.adoc#column-minunderlinerownumberunderlinefrom[+sqlparse.RepoObject_SqlModules_39_object.Min_RowNumber_From+] * xref:sqlparse.repoobject_sqlmodules_39_object.adoc#column-minunderlinerownumberunderlinegroupby[+sqlparse.RepoObject_SqlModules_39_object.Min_RowNumber_GroupBy+] -- [#column-sysobjectunderlinefullname] === SysObject_fullname [cols=""d,8a,m,m,m""] |=== | |SysObject_fullname |nvarchar(261) |NULL | |=== .Description -- (concat('[',[SysObject_schema_name],'].[',[SysObject_name],']')) -- {empty} + .Referenced Columns -- * xref:sqlparse.repoobject_sqlmodules_20_statement_children.adoc#column-sysobjectunderlinefullname[+sqlparse.RepoObject_SqlModules_20_statement_children.SysObject_fullname+] -- // end::AntoraColumnDetails[] == AntoraPkColumnTableRows // tag::AntoraPkColumnTableRows[] |1 |*<>* |uniqueidentifier |NOT NULL | |2 |*<>* |nvarchar(max) |NULL | // end::AntoraPkColumnTableRows[] == AntoraNonPkColumnTableRows // tag::AntoraNonPkColumnTableRows[] | |<> |bigint |NULL | | |<> |nvarchar(261) |NULL | // end::AntoraNonPkColumnTableRows[] == AntoraIndexList // tag::AntoraIndexList[] [#index-pkunderlinerepoobjectunderlinesqlmodulesunderline33underlineobjectnormalized] === PK_RepoObject_SqlModules_33_ObjectNormalized * IndexSemanticGroup: xref:other/indexsemanticgroup.adoc#startbnoblankgroupendb[no_group] + -- * <>; uniqueidentifier * <>; nvarchar(max) -- * PK, Unique, Real: 1, 1, 0 [#index-idxunderlinerepoobjectunderlinesqlmodulesunderline33underlineobjectnormalizedunderlineunderline2] === idx_RepoObject_SqlModules_33_ObjectNormalized++__++2 * IndexSemanticGroup: xref:other/indexsemanticgroup.adoc#startbnoblankgroupendb[no_group] + -- * <>; uniqueidentifier -- * 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:sqlparse.repoobject_sqlmodules_33_objectnormalized.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:sqlparse.repoobject_sqlmodules_20_statement_children.adoc[] // end::antorareferencedlist[] === AntoraReferencingList // tag::antorareferencinglist[] * xref:dhw:sqldb:sqlparse.repoobject_sqlmodules_39_object.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[] 874DBBB7-0799-EB11-84F4-A81E8446D5B0 // end::pk_index_guid[] === pk_IndexPatternColumnDatatype // tag::pk_indexpatterncolumndatatype[] uniqueidentifier,nvarchar(max) // end::pk_indexpatterncolumndatatype[] === pk_IndexPatternColumnName // tag::pk_indexpatterncolumnname[] RepoObject_guid,normalized // end::pk_indexpatterncolumnname[] === pk_IndexSemanticGroup // tag::pk_indexsemanticgroup[] // end::pk_indexsemanticgroup[] === ReferencedObjectList // tag::referencedobjectlist[] * [sqlparse].[RepoObject_SqlModules_20_statement_children] // 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:sqlparse.repoobject_sqlmodules_33_objectnormalized.adoc[]"" as sqlparse.RepoObject_SqlModules_33_ObjectNormalized << V >> { - **RepoObject_guid** : (uniqueidentifier) **normalized** : (nvarchar(max)) Min_RowNumber_per_normalized : (bigint) SysObject_fullname : (nvarchar(261)) -- } .... // 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:sqlparse.repoobject_sqlmodules_33_objectnormalized.adoc[]"" as sqlparse.RepoObject_SqlModules_33_ObjectNormalized << V >> { - **PK_RepoObject_SqlModules_33_ObjectNormalized** .. RepoObject_guid; uniqueidentifier normalized; nvarchar(max) -- - idx_RepoObject_SqlModules_33_ObjectNormalized__2 .. RepoObject_guid; uniqueidentifier } 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:sqlparse.repoobject_sqlmodules_20_statement_children.adoc[]"" as sqlparse.RepoObject_SqlModules_20_statement_children << V >> { - **RepoObject_guid** : (uniqueidentifier) - **json_key** : (nvarchar(4000)) -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_33_objectnormalized.adoc[]"" as sqlparse.RepoObject_SqlModules_33_ObjectNormalized << V >> { - **RepoObject_guid** : (uniqueidentifier) **normalized** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_39_object.adoc[]"" as sqlparse.RepoObject_SqlModules_39_object << V >> { -- } sqlparse.RepoObject_SqlModules_20_statement_children <.. sqlparse.RepoObject_SqlModules_33_ObjectNormalized sqlparse.RepoObject_SqlModules_33_ObjectNormalized <.. sqlparse.RepoObject_SqlModules_39_object 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:config.ftv_get_parameter_value.adoc[]"" as config.ftv_get_parameter_value << IF >> { -- } entity ""puml-link:dhw:sqldb:config.parameter.adoc[]"" as config.Parameter << U >> { - **Parameter_name** : (varchar(100)) - **sub_Parameter** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:configt.parameter_default.adoc[]"" as configT.Parameter_default << V >> { - **Parameter_name** : (varchar(52)) - **sub_Parameter** : (nvarchar(26)) -- } entity ""puml-link:dhw:sqldb:property.external_repoobjectproperty.adoc[]"" as property.external_RepoObjectProperty << U >> { - **RepoObject_guid** : (uniqueidentifier) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.propertyname_repoobject.adoc[]"" as property.PropertyName_RepoObject << V >> { **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.propertyname_repoobject_t.adoc[]"" as property.PropertyName_RepoObject_T << U >> { **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty.adoc[]"" as property.RepoObjectProperty << U >> { - **RepoObjectProperty_id** : (int) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty_external_src.adoc[]"" as property.RepoObjectProperty_external_src << V >> { - **RepoObject_guid** : (uniqueidentifier) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty_external_tgt.adoc[]"" as property.RepoObjectProperty_external_tgt << V >> { - **RepoObject_guid** : (uniqueidentifier) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty_selectedpropertyname_split.adoc[]"" as property.RepoObjectProperty_SelectedPropertyName_split << V >> { -- } entity ""puml-link:dhw:sqldb:reference.additional_reference.adoc[]"" as reference.additional_Reference << U >> { - **Id** : (int) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_properties_src.adoc[]"" as reference.additional_Reference_from_properties_src << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) **referencing_Column** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_properties_tgt.adoc[]"" as reference.additional_Reference_from_properties_tgt << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) **referencing_Column** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_ssas_src.adoc[]"" as reference.additional_Reference_from_ssas_src << V >> { **referenced_AntoraComponent** : (nvarchar(128)) **referenced_AntoraModule** : (nvarchar(128)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(500)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) - **referencing_Schema** : (nvarchar(128)) - **referencing_Object** : (nvarchar(128)) **referencing_Column** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_ssas_tgt.adoc[]"" as reference.additional_Reference_from_ssas_tgt << V >> { **referenced_AntoraComponent** : (nvarchar(128)) **referenced_AntoraModule** : (nvarchar(128)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(500)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) - **referencing_Schema** : (nvarchar(128)) - **referencing_Object** : (nvarchar(128)) **referencing_Column** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_is_external.adoc[]"" as reference.additional_Reference_is_external << V >> { -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_object.adoc[]"" as reference.additional_Reference_Object << V >> { - **AntoraComponent** : (nvarchar(128)) - **AntoraModule** : (nvarchar(128)) - **SchemaName** : (nvarchar(128)) - **ObjectName** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_object_t.adoc[]"" as reference.additional_Reference_Object_T << U >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_wo_columns_from_properties_src.adoc[]"" as reference.additional_Reference_wo_columns_from_properties_src << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_wo_columns_from_properties_tgt.adoc[]"" as reference.additional_Reference_wo_columns_from_properties_tgt << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:repo.repoobject.adoc[]"" as repo.RepoObject << U >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_external_src.adoc[]"" as repo.RepoObject_external_src << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_external_tgt.adoc[]"" as repo.RepoObject_external_tgt << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_ssas_src.adoc[]"" as repo.RepoObject_SSAS_src << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_ssas_tgt.adoc[]"" as repo.RepoObject_SSAS_tgt << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.reposchema.adoc[]"" as repo.RepoSchema << U >> { - **RepoSchema_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.reposchema_ssas_src.adoc[]"" as repo.RepoSchema_ssas_src << V >> { - **RepoSchema_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:repo.reposchema_ssas_tgt.adoc[]"" as repo.RepoSchema_ssas_tgt << V >> { - **RepoSchema_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:sqlparse.ftv_sqlparse_with_some_children.adoc[]"" as sqlparse.ftv_sqlparse_with_some_children << IF >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules.adoc[]"" as sqlparse.RepoObject_SqlModules << U >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_10_statement.adoc[]"" as sqlparse.RepoObject_SqlModules_10_statement << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_20_statement_children.adoc[]"" as sqlparse.RepoObject_SqlModules_20_statement_children << V >> { - **RepoObject_guid** : (uniqueidentifier) - **json_key** : (nvarchar(4000)) -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_33_objectnormalized.adoc[]"" as sqlparse.RepoObject_SqlModules_33_ObjectNormalized << V >> { - **RepoObject_guid** : (uniqueidentifier) **normalized** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:ssas.additional_reference_step1.adoc[]"" as ssas.additional_Reference_step1 << V >> { -- } 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_201_descriptions_multiline.adoc[]"" as ssas.model_json_201_descriptions_multiline << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_2011_descriptions_stragg.adoc[]"" as ssas.model_json_2011_descriptions_StrAgg << 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.model_json_313_tables_partitions.adoc[]"" as ssas.model_json_313_tables_partitions << V >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_partitions_name** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_3131_tables_partitions_source.adoc[]"" as ssas.model_json_3131_tables_partitions_source << V >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_partitions_name** : (nvarchar(500)) **tables_partitions_source_name** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31311_tables_partitions_source_posfrom.adoc[]"" as ssas.model_json_31311_tables_partitions_source_PosFrom << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_313111_tables_partitions_source_stringfrom.adoc[]"" as ssas.model_json_313111_tables_partitions_source_StringFrom << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_3131111_tables_partitions_source_posdot.adoc[]"" as ssas.model_json_3131111_tables_partitions_source_PosDot << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31311111_tables_partitions_source_part123.adoc[]"" as ssas.model_json_31311111_tables_partitions_source_Part123 << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_33_datasources.adoc[]"" as ssas.model_json_33_dataSources << V >> { - **databasename** : (nvarchar(128)) **dataSources_name** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_33_datasources_t.adoc[]"" as ssas.model_json_33_dataSources_T << U >> { - **databasename** : (nvarchar(128)) **dataSources_name** : (nvarchar(500)) -- } config.ftv_get_parameter_value <.. repo.RepoObject_external_src config.ftv_get_parameter_value <.. ssas.additional_Reference_step1 config.ftv_get_parameter_value <.. reference.additional_Reference_is_external config.Parameter <.. property.PropertyName_RepoObject config.Parameter <.. config.ftv_get_parameter_value configT.Parameter_default <.. config.Parameter property.external_RepoObjectProperty <.. property.RepoObjectProperty_external_src property.PropertyName_RepoObject <.. property.PropertyName_RepoObject_T property.PropertyName_RepoObject_T <.. property.RepoObjectProperty_external_tgt property.RepoObjectProperty <.. property.RepoObjectProperty_SelectedPropertyName_split property.RepoObjectProperty <.. property.PropertyName_RepoObject property.RepoObjectProperty_external_src <.. property.RepoObjectProperty_external_tgt property.RepoObjectProperty_external_tgt <.. property.RepoObjectProperty property.RepoObjectProperty_SelectedPropertyName_split <.. reference.additional_Reference_from_properties_src property.RepoObjectProperty_SelectedPropertyName_split <.. reference.additional_Reference_wo_columns_from_properties_src reference.additional_Reference <.. reference.additional_Reference_is_external reference.additional_Reference_from_properties_src <.. reference.additional_Reference_from_properties_tgt reference.additional_Reference_from_properties_tgt <.. reference.additional_Reference reference.additional_Reference_from_ssas_src <.. reference.additional_Reference_from_ssas_tgt reference.additional_Reference_from_ssas_tgt <.. reference.additional_Reference reference.additional_Reference_is_external <.. reference.additional_Reference_Object reference.additional_Reference_Object <.. reference.additional_Reference_Object_T reference.additional_Reference_Object_T <.. repo.RepoObject_external_src reference.additional_Reference_wo_columns_from_properties_src <.. reference.additional_Reference_wo_columns_from_properties_tgt reference.additional_Reference_wo_columns_from_properties_tgt <.. reference.additional_Reference repo.RepoObject <.. sqlparse.RepoObject_SqlModules_10_statement repo.RepoObject <.. property.RepoObjectProperty_external_tgt repo.RepoObject <.. repo.RepoObject_external_src repo.RepoObject_external_src <.. repo.RepoObject_external_tgt repo.RepoObject_external_tgt <.. repo.RepoObject repo.RepoObject_SSAS_src <.. repo.RepoObject_SSAS_tgt repo.RepoObject_SSAS_tgt <.. repo.RepoObject repo.RepoSchema <.. repo.RepoObject_SSAS_src repo.RepoSchema_ssas_src <.. repo.RepoSchema_ssas_tgt repo.RepoSchema_ssas_tgt <.. repo.RepoSchema sqlparse.ftv_sqlparse_with_some_children <.. sqlparse.RepoObject_SqlModules_20_statement_children sqlparse.RepoObject_SqlModules <.. sqlparse.RepoObject_SqlModules_10_statement sqlparse.RepoObject_SqlModules_10_statement <.. sqlparse.RepoObject_SqlModules_20_statement_children sqlparse.RepoObject_SqlModules_20_statement_children <.. sqlparse.RepoObject_SqlModules_33_ObjectNormalized ssas.additional_Reference_step1 <.. reference.additional_Reference_from_ssas_src ssas.model_json <.. ssas.model_json_10 ssas.model_json_10 <.. ssas.model_json_20 ssas.model_json_20 <.. repo.RepoSchema_ssas_src ssas.model_json_20 <.. ssas.model_json_201_descriptions_multiline ssas.model_json_20 <.. ssas.model_json_33_dataSources ssas.model_json_20 <.. ssas.model_json_31_tables ssas.model_json_201_descriptions_multiline <.. ssas.model_json_2011_descriptions_StrAgg ssas.model_json_2011_descriptions_StrAgg <.. repo.RepoSchema_ssas_src 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_31_tables_T <.. repo.RepoObject_SSAS_src ssas.model_json_31_tables_T <.. ssas.model_json_313_tables_partitions ssas.model_json_311_tables_columns <.. ssas.model_json_311_tables_columns_T ssas.model_json_311_tables_columns_T <.. ssas.additional_Reference_step1 ssas.model_json_313_tables_partitions <.. ssas.model_json_3131_tables_partitions_source ssas.model_json_3131_tables_partitions_source <.. ssas.model_json_31311_tables_partitions_source_PosFrom ssas.model_json_31311_tables_partitions_source_PosFrom <.. ssas.model_json_313111_tables_partitions_source_StringFrom ssas.model_json_313111_tables_partitions_source_StringFrom <.. ssas.model_json_3131111_tables_partitions_source_PosDot ssas.model_json_3131111_tables_partitions_source_PosDot <.. ssas.model_json_31311111_tables_partitions_source_Part123 ssas.model_json_31311111_tables_partitions_source_Part123 <.. ssas.additional_Reference_step1 ssas.model_json_33_dataSources <.. ssas.model_json_33_dataSources_T ssas.model_json_33_dataSources_T <.. ssas.additional_Reference_step1 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.antoranavlistpage_by_schema.adoc[]"" as docs.AntoraNavListPage_by_schema << V >> { -- } entity ""puml-link:dhw:sqldb:docs.ftv_repoobject_reference_plantuml_entityreflist.adoc[]"" as docs.ftv_RepoObject_Reference_PlantUml_EntityRefList << IF >> { -- } entity ""puml-link:dhw:sqldb:docs.objectrefcyclic.adoc[]"" as docs.ObjectRefCyclic << V >> { -- } entity ""puml-link:dhw:sqldb:docs.objectrefcyclic_entitylist.adoc[]"" as docs.ObjectRefCyclic_EntityList << V >> { -- } entity ""puml-link:dhw:sqldb:docs.repoobject_adoc.adoc[]"" as docs.RepoObject_Adoc << V >> { -- } entity ""puml-link:dhw:sqldb:docs.repoobject_adoc_t.adoc[]"" as docs.RepoObject_Adoc_T << U >> { - **RepoObject_guid** : (uniqueidentifier) - **cultures_name** : (nvarchar(10)) -- } entity ""puml-link:dhw:sqldb:docs.repoobject_columnlist.adoc[]"" as docs.RepoObject_ColumnList << V >> { -- } entity ""puml-link:dhw:sqldb:docs.repoobject_columnlist_t.adoc[]"" as docs.RepoObject_ColumnList_T << U >> { - **RepoObject_guid** : (uniqueidentifier) - **cultures_name** : (nvarchar(10)) -- } entity ""puml-link:dhw:sqldb:docs.repoobject_plantuml.adoc[]"" as docs.RepoObject_Plantuml << V >> { - **RepoObject_guid** : (uniqueidentifier) **cultures_name** : (nvarchar(10)) -- } entity ""puml-link:dhw:sqldb:docs.repoobject_plantuml_colreflist_1_1.adoc[]"" as docs.RepoObject_Plantuml_ColRefList_1_1 << V >> { -- } entity ""puml-link:dhw:sqldb:docs.repoobject_plantuml_entity.adoc[]"" as docs.RepoObject_Plantuml_Entity << V >> { -- } entity ""puml-link:dhw:sqldb:docs.repoobject_plantuml_entity_t.adoc[]"" as docs.RepoObject_Plantuml_Entity_T << U >> { - **RepoObject_guid** : (uniqueidentifier) - **cultures_name** : (nvarchar(10)) -- } entity ""puml-link:dhw:sqldb:docs.repoobject_plantuml_pumlentityfklist.adoc[]"" as docs.RepoObject_PlantUml_PumlEntityFkList << V >> { **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:docs.repoobject_plantuml_t.adoc[]"" as docs.RepoObject_Plantuml_T << U >> { - **RepoObject_guid** : (uniqueidentifier) **cultures_name** : (nvarchar(10)) -- } entity ""puml-link:dhw:sqldb:docs.schema_entitylist.adoc[]"" as docs.Schema_EntityList << V >> { - **RepoObject_schema_name** : (nvarchar(128)) - **cultures_name** : (nvarchar(10)) -- } entity ""puml-link:dhw:sqldb:docs.schema_puml.adoc[]"" as docs.Schema_puml << V >> { - **RepoSchema_guid** : (uniqueidentifier) **cultures_name** : (nvarchar(10)) -- } entity ""puml-link:dhw:sqldb:docs.usp_antoraexport.adoc[]"" as docs.usp_AntoraExport << P >> { -- } entity ""puml-link:dhw:sqldb:docs.usp_antoraexport_objectpartialscontent.adoc[]"" as docs.usp_AntoraExport_ObjectPartialsContent << P >> { -- } entity ""puml-link:dhw:sqldb:docs.usp_antoraexport_objectpuml.adoc[]"" as docs.usp_AntoraExport_ObjectPuml << P >> { -- } entity ""puml-link:dhw:sqldb:docs.usp_persist_repoobject_adoc_t.adoc[]"" as docs.usp_PERSIST_RepoObject_Adoc_T << P >> { -- } entity ""puml-link:dhw:sqldb:docs.usp_persist_repoobject_columnlist_t.adoc[]"" as docs.usp_PERSIST_RepoObject_ColumnList_T << P >> { -- } entity ""puml-link:dhw:sqldb:docs.usp_persist_repoobject_plantuml_entity_t.adoc[]"" as docs.usp_PERSIST_RepoObject_Plantuml_Entity_T << P >> { -- } entity ""puml-link:dhw:sqldb:docs.usp_persist_repoobject_plantuml_t.adoc[]"" as docs.usp_PERSIST_RepoObject_Plantuml_T << P >> { -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty_collect_source_rogross.adoc[]"" as property.RepoObjectProperty_Collect_source_ROGross << V >> { - **RepoObject_guid** : (uniqueidentifier) - **property_name** : (varchar(39)) -- } entity ""puml-link:dhw:sqldb:property.usp_repoobject_inheritance.adoc[]"" as property.usp_RepoObject_Inheritance << P >> { -- } entity ""puml-link:dhw:sqldb:property.usp_repoobjectproperty_collect.adoc[]"" as property.usp_RepoObjectProperty_collect << P >> { -- } entity ""puml-link:dhw:sqldb:reference.ftv_repoobject_columreferencerepoobject.adoc[]"" as reference.ftv_RepoObject_ColumReferenceRepoObject << IF >> { -- } entity ""puml-link:dhw:sqldb:reference.ftv_repoobject_dbmlcolumnrelation.adoc[]"" as reference.ftv_RepoObject_DbmlColumnRelation << IF >> { -- } entity ""puml-link:dhw:sqldb:reference.ftv_repoobjectcolumn_referencetree.adoc[]"" as reference.ftv_RepoObjectColumn_ReferenceTree << IF >> { -- } entity ""puml-link:dhw:sqldb:reference.repoobjectcolumn_reference.adoc[]"" as reference.RepoObjectColumn_reference << V >> { **referenced_RepoObjectColumn_guid** : (uniqueidentifier) **referencing_RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.repoobjectcolumn_reference_sqlmodules.adoc[]"" as reference.RepoObjectColumn_reference_SqlModules << V >> { **referencing_id** : (int) **referencing_minor_id** : (int) **referenced_id** : (int) **referenced_minor_id** : (int) -- } entity ""puml-link:dhw:sqldb:reference.repoobjectcolumn_reference_t.adoc[]"" as reference.RepoObjectColumn_reference_T << U >> { **referenced_RepoObjectColumn_guid** : (uniqueidentifier) **referencing_RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.repoobjectcolumn_reference_union.adoc[]"" as reference.RepoObjectColumn_reference_union << V >> { -- } entity ""puml-link:dhw:sqldb:reference.repoobjectcolumn_referencedlist.adoc[]"" as reference.RepoObjectColumn_ReferencedList << V >> { -- } entity ""puml-link:dhw:sqldb:reference.repoobjectcolumn_referencedreferencing.adoc[]"" as reference.RepoObjectColumn_ReferencedReferencing << V >> { -- } entity ""puml-link:dhw:sqldb:reference.repoobjectcolumn_referencetree.adoc[]"" as reference.RepoObjectColumn_ReferenceTree << V >> { -- } entity ""puml-link:dhw:sqldb:reference.repoobjectcolumn_referencinglist.adoc[]"" as reference.RepoObjectColumn_ReferencingList << V >> { -- } entity ""puml-link:dhw:sqldb:reference.repoobjectcolumn_relationscript.adoc[]"" as reference.RepoObjectColumn_RelationScript << V >> { -- } entity ""puml-link:dhw:sqldb:reference.usp_persist_repoobjectcolumn_reference_t.adoc[]"" as reference.usp_PERSIST_RepoObjectColumn_reference_T << P >> { -- } entity ""puml-link:dhw:sqldb:repo.check_indexcolumn_virtual_referenced_setpoint.adoc[]"" as repo.check_IndexColumn_virtual_referenced_setpoint << V >> { -- } entity ""puml-link:dhw:sqldb:repo.index_referencing_indexpatterncolumnguid.adoc[]"" as repo.Index_referencing_IndexPatternColumnGuid << V >> { **source_index_guid** : (uniqueidentifier) **referencing_RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.indexcolumn_referencedreferencing_hasfullcolumnsinreferencing.adoc[]"" as repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing << V >> { - **index_guid** : (uniqueidentifier) - **index_column_id** : (int) **RowNumberInReferencing** : (bigint) -- } entity ""puml-link:dhw:sqldb:repo.indexcolumn_referencedreferencing_hasfullcolumnsinreferencing_check.adoc[]"" as repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_check << V >> { -- } entity ""puml-link:dhw:sqldb:repo.indexcolumn_referencedreferencing_hasfullcolumnsinreferencing_t.adoc[]"" as repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T << U >> { **index_guid** : (uniqueidentifier) - **index_column_id** : (int) **RowNumberInReferencing** : (bigint) -- } entity ""puml-link:dhw:sqldb:repo.indexcolumn_virtual_referenced_setpoint.adoc[]"" as repo.IndexColumn_virtual_referenced_setpoint << V >> { - **index_guid** : (uniqueidentifier) - **index_column_id** : (int) -- } entity ""puml-link:dhw:sqldb:repo.indexreferencedreferencing_hasfullcolumnsinreferencing.adoc[]"" as repo.IndexReferencedReferencing_HasFullColumnsInReferencing << V >> { -- } entity ""puml-link:dhw:sqldb:repo.repoobject_columnlist.adoc[]"" as repo.RepoObject_ColumnList << V >> { -- } entity ""puml-link:dhw:sqldb:repo.repoobject_gross2.adoc[]"" as repo.RepoObject_gross2 << V >> { -- } entity ""puml-link:dhw:sqldb:repo.repoobject_sat2.adoc[]"" as repo.RepoObject_sat2 << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_sat2_t.adoc[]"" as repo.RepoObject_sat2_T << U >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_sqlcreatetable.adoc[]"" as repo.RepoObject_SqlCreateTable << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn_gross2.adoc[]"" as repo.RepoObjectColumn_gross2 << V >> { -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn_missingsource_typev.adoc[]"" as repo.RepoObjectColumn_MissingSource_TypeV << V >> { -- } entity ""puml-link:dhw:sqldb:repo.usp_index_inheritance.adoc[]"" as repo.usp_index_inheritance << P >> { -- } entity ""puml-link:dhw:sqldb:repo.usp_main.adoc[]"" as repo.usp_main << P >> { -- } entity ""puml-link:dhw:sqldb:repo.usp_persist_indexcolumn_referencedreferencing_hasfullcolumnsinreferencing_t.adoc[]"" as repo.usp_PERSIST_IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T << P >> { -- } entity ""puml-link:dhw:sqldb:repo.usp_persist_repoobject_sat2_t.adoc[]"" as repo.usp_PERSIST_RepoObject_sat2_T << P >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_33_objectnormalized.adoc[]"" as sqlparse.RepoObject_SqlModules_33_ObjectNormalized << V >> { - **RepoObject_guid** : (uniqueidentifier) **normalized** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_39_object.adoc[]"" as sqlparse.RepoObject_SqlModules_39_object << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_41_from.adoc[]"" as sqlparse.RepoObject_SqlModules_41_from << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_41_from_t.adoc[]"" as sqlparse.RepoObject_SqlModules_41_from_T << U >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_42_from_identifier.adoc[]"" as sqlparse.RepoObject_SqlModules_42_from_Identifier << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_43_from_identifier.adoc[]"" as sqlparse.RepoObject_SqlModules_43_from_Identifier << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_44_from_identifier_quotename.adoc[]"" as sqlparse.RepoObject_SqlModules_44_from_Identifier_QuoteName << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_61_selectidentifier_union.adoc[]"" as sqlparse.RepoObject_SqlModules_61_SelectIdentifier_Union << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_61_selectidentifier_union_t.adoc[]"" as sqlparse.RepoObject_SqlModules_61_SelectIdentifier_Union_T << U >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_71_reference_explicitetablealias.adoc[]"" as sqlparse.RepoObject_SqlModules_71_reference_ExpliciteTableAlias << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_72_reference_notablealias.adoc[]"" as sqlparse.RepoObject_SqlModules_72_reference_NoTableAlias << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_79_reference_union.adoc[]"" as sqlparse.RepoObject_SqlModules_79_reference_union << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.usp_persist_repoobject_sqlmodules_41_from_t.adoc[]"" as sqlparse.usp_PERSIST_RepoObject_SqlModules_41_from_T << P >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.usp_persist_repoobject_sqlmodules_61_selectidentifier_union_t.adoc[]"" as sqlparse.usp_PERSIST_RepoObject_SqlModules_61_SelectIdentifier_Union_T << P >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.usp_sqlparse.adoc[]"" as sqlparse.usp_sqlparse << P >> { -- } entity ""puml-link:dhw:sqldb:uspgenerator.generatoruspstep_persistence_src.adoc[]"" as uspgenerator.GeneratorUspStep_Persistence_src << V >> { - **usp_id** : (int) -- } entity ""puml-link:dhw:sqldb:uspgenerator.usp_generatorusp_insert_update_persistence.adoc[]"" as uspgenerator.usp_GeneratorUsp_insert_update_persistence << P >> { -- } docs.ftv_RepoObject_Reference_PlantUml_EntityRefList <.. docs.RepoObject_Plantuml docs.ObjectRefCyclic_EntityList <.. docs.ObjectRefCyclic docs.RepoObject_Adoc <.. docs.RepoObject_Adoc_T docs.RepoObject_Adoc <.. docs.usp_PERSIST_RepoObject_Adoc_T docs.REpoObject_Adoc_T <.. docs.usp_PERSIST_RepoObject_Adoc_T docs.RepoObject_ColumnList <.. docs.usp_PERSIST_RepoObject_ColumnList_T docs.RepoObject_ColumnList <.. docs.RepoObject_ColumnList_T docs.RepoObject_ColumnList_T <.. docs.RepoObject_Adoc docs.RepoObject_ColumnList_T <.. docs.usp_PERSIST_RepoObject_ColumnList_T docs.RepoObject_ColumnList_T <.. docs.RepoObject_Plantuml_Entity docs.RepoObject_Plantuml <.. docs.RepoObject_Plantuml_T docs.RepoObject_Plantuml <.. docs.usp_PERSIST_RepoObject_Plantuml_T docs.RepoObject_Plantuml_ColRefList_1_1 <.. docs.RepoObject_Plantuml docs.RepoObject_Plantuml_Entity <.. docs.RepoObject_Plantuml_Entity_T docs.RepoObject_Plantuml_Entity <.. docs.usp_PERSIST_RepoObject_Plantuml_Entity_T docs.RepoObject_Plantuml_Entity_T <.. docs.RepoObject_Adoc docs.RepoObject_Plantuml_Entity_T <.. docs.ftv_RepoObject_Reference_PlantUml_EntityRefList docs.RepoObject_Plantuml_Entity_T <.. docs.usp_PERSIST_RepoObject_Plantuml_Entity_T docs.RepoObject_Plantuml_Entity_T <.. docs.Schema_EntityList docs.RepoObject_Plantuml_Entity_T <.. docs.ObjectRefCyclic_EntityList docs.RepoObject_Plantuml_Entity_T <.. docs.RepoObject_PlantUml_PumlEntityFkList docs.RepoObject_PlantUml_PumlEntityFkList <.. docs.RepoObject_Plantuml docs.RepoObject_Plantuml_T <.. docs.usp_PERSIST_RepoObject_Plantuml_T docs.RepoObject_Plantuml_T <.. docs.RepoObject_Adoc docs.Schema_EntityList <.. docs.Schema_puml docs.Schema_puml <.. docs.AntoraNavListPage_by_schema docs.usp_AntoraExport_ObjectPartialsContent <.. docs.usp_AntoraExport docs.usp_AntoraExport_ObjectPuml <.. docs.usp_AntoraExport docs.usp_PERSIST_RepoObject_Adoc_T <.. docs.usp_AntoraExport_ObjectPartialsContent docs.usp_PERSIST_RepoObject_ColumnList_T <.. docs.usp_AntoraExport_ObjectPartialsContent docs.usp_PERSIST_RepoObject_Plantuml_Entity_T <.. docs.usp_AntoraExport_ObjectPuml docs.usp_PERSIST_RepoObject_Plantuml_T <.. docs.usp_AntoraExport_ObjectPuml property.RepoObjectProperty_Collect_source_ROGross <.. property.usp_RepoObjectProperty_collect property.usp_RepoObject_Inheritance <.. repo.usp_main property.usp_RepoObjectProperty_collect <.. repo.usp_main property.usp_RepoObjectProperty_collect <.. property.usp_RepoObject_Inheritance reference.ftv_RepoObjectColumn_ReferenceTree <.. reference.RepoObjectColumn_ReferenceTree reference.RepoObjectColumn_reference <.. reference.RepoObjectColumn_reference_T reference.RepoObjectColumn_reference <.. reference.usp_PERSIST_RepoObjectColumn_reference_T reference.RepoObjectColumn_reference_SqlModules <.. reference.RepoObjectColumn_reference_union reference.RepoObjectColumn_reference_T <.. docs.RepoObject_Plantuml_ColRefList_1_1 reference.RepoObjectColumn_reference_T <.. reference.RepoObjectColumn_ReferencedReferencing reference.RepoObjectColumn_reference_T <.. reference.usp_PERSIST_RepoObjectColumn_reference_T reference.RepoObjectColumn_reference_T <.. repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing reference.RepoObjectColumn_reference_T <.. repo.RepoObjectColumn_MissingSource_TypeV reference.RepoObjectColumn_reference_T <.. reference.RepoObjectColumn_RelationScript reference.RepoObjectColumn_reference_union <.. reference.RepoObjectColumn_reference reference.RepoObjectColumn_ReferencedList <.. repo.RepoObjectColumn_gross2 reference.RepoObjectColumn_ReferencedReferencing <.. reference.RepoObjectColumn_ReferencingList reference.RepoObjectColumn_ReferencedReferencing <.. reference.ftv_RepoObject_DbmlColumnRelation reference.RepoObjectColumn_ReferencedReferencing <.. reference.RepoObjectColumn_ReferencedList reference.RepoObjectColumn_ReferencedReferencing <.. reference.ftv_RepoObjectColumn_ReferenceTree reference.RepoObjectColumn_ReferenceTree <.. reference.ftv_RepoObject_ColumReferenceRepoObject reference.RepoObjectColumn_ReferencingList <.. repo.RepoObjectColumn_gross2 reference.RepoObjectColumn_RelationScript <.. reference.ftv_RepoObject_ColumReferenceRepoObject reference.usp_PERSIST_RepoObjectColumn_reference_T <.. repo.usp_main repo.Index_referencing_IndexPatternColumnGuid <.. repo.IndexReferencedReferencing_HasFullColumnsInReferencing repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing <.. repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing <.. repo.usp_PERSIST_IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T <.. repo.IndexColumn_virtual_referenced_setpoint repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T <.. repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_check repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T <.. repo.usp_PERSIST_IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T <.. repo.Index_referencing_IndexPatternColumnGuid repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T <.. repo.IndexReferencedReferencing_HasFullColumnsInReferencing repo.IndexColumn_virtual_referenced_setpoint <.. repo.check_IndexColumn_virtual_referenced_setpoint repo.IndexColumn_virtual_referenced_setpoint <.. repo.usp_index_inheritance repo.IndexReferencedReferencing_HasFullColumnsInReferencing <.. repo.usp_index_inheritance repo.RepoObject_ColumnList <.. repo.RepoObject_sat2 repo.RepoObject_ColumnList <.. repo.RepoObject_gross2 repo.RepoObject_ColumnList <.. repo.RepoObject_SqlCreateTable repo.RepoObject_gross2 <.. uspgenerator.GeneratorUspStep_Persistence_src repo.RepoObject_sat2 <.. repo.usp_PERSIST_RepoObject_sat2_T repo.RepoObject_sat2 <.. repo.RepoObject_sat2_T repo.RepoObject_sat2_T <.. repo.usp_PERSIST_RepoObject_sat2_T repo.RepoObject_sat2_T <.. property.RepoObjectProperty_Collect_source_ROGross repo.RepoObject_sat2_T <.. docs.RepoObject_Adoc repo.RepoObject_SqlCreateTable <.. reference.ftv_RepoObject_ColumReferenceRepoObject repo.RepoObjectColumn_gross2 <.. uspgenerator.usp_GeneratorUsp_insert_update_persistence repo.RepoObjectColumn_gross2 <.. repo.RepoObject_ColumnList repo.RepoObjectColumn_gross2 <.. docs.RepoObject_ColumnList repo.usp_index_inheritance <.. repo.usp_main repo.usp_PERSIST_IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T <.. repo.usp_index_inheritance repo.usp_PERSIST_RepoObject_sat2_T <.. repo.usp_main sqlparse.RepoObject_SqlModules_33_ObjectNormalized <.. sqlparse.RepoObject_SqlModules_39_object sqlparse.RepoObject_SqlModules_39_object <.. sqlparse.RepoObject_SqlModules_61_SelectIdentifier_Union sqlparse.RepoObject_SqlModules_39_object <.. sqlparse.RepoObject_SqlModules_41_from sqlparse.RepoObject_SqlModules_41_from <.. sqlparse.usp_PERSIST_RepoObject_SqlModules_41_from_T sqlparse.RepoObject_SqlModules_41_from <.. sqlparse.RepoObject_SqlModules_41_from_T sqlparse.RepoObject_SqlModules_41_from_T <.. sqlparse.usp_PERSIST_RepoObject_SqlModules_41_from_T sqlparse.RepoObject_SqlModules_41_from_T <.. sqlparse.RepoObject_SqlModules_42_from_Identifier sqlparse.RepoObject_SqlModules_42_from_Identifier <.. sqlparse.RepoObject_SqlModules_43_from_Identifier sqlparse.RepoObject_SqlModules_43_from_Identifier <.. sqlparse.RepoObject_SqlModules_44_from_Identifier_QuoteName sqlparse.RepoObject_SqlModules_44_from_Identifier_QuoteName <.. sqlparse.RepoObject_SqlModules_71_reference_ExpliciteTableAlias sqlparse.RepoObject_SqlModules_44_from_Identifier_QuoteName <.. sqlparse.RepoObject_SqlModules_72_reference_NoTableAlias sqlparse.RepoObject_SqlModules_61_SelectIdentifier_Union <.. sqlparse.usp_PERSIST_RepoObject_SqlModules_61_SelectIdentifier_Union_T sqlparse.RepoObject_SqlModules_61_SelectIdentifier_Union <.. sqlparse.RepoObject_SqlModules_61_SelectIdentifier_Union_T sqlparse.RepoObject_SqlModules_61_SelectIdentifier_Union_T <.. sqlparse.RepoObject_SqlModules_71_reference_ExpliciteTableAlias sqlparse.RepoObject_SqlModules_61_SelectIdentifier_Union_T <.. sqlparse.usp_PERSIST_RepoObject_SqlModules_61_SelectIdentifier_Union_T sqlparse.RepoObject_SqlModules_61_SelectIdentifier_Union_T <.. sqlparse.RepoObject_SqlModules_72_reference_NoTableAlias sqlparse.RepoObject_SqlModules_71_reference_ExpliciteTableAlias <.. sqlparse.RepoObject_SqlModules_79_reference_union sqlparse.RepoObject_SqlModules_72_reference_NoTableAlias <.. sqlparse.RepoObject_SqlModules_79_reference_union sqlparse.RepoObject_SqlModules_79_reference_union <.. reference.RepoObjectColumn_reference_SqlModules sqlparse.usp_PERSIST_RepoObject_SqlModules_41_from_T <.. sqlparse.usp_sqlparse sqlparse.usp_PERSIST_RepoObject_SqlModules_61_SelectIdentifier_Union_T <.. sqlparse.usp_sqlparse uspgenerator.GeneratorUspStep_Persistence_src <.. uspgenerator.usp_GeneratorUsp_insert_update_persistence uspgenerator.usp_GeneratorUsp_insert_update_persistence <.. repo.usp_main 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:sqlparse.repoobject_sqlmodules_20_statement_children.adoc[]"" as sqlparse.RepoObject_SqlModules_20_statement_children << V >> { - **RepoObject_guid** : (uniqueidentifier) - **json_key** : (nvarchar(4000)) child0_children : (nvarchar(max)) child0_class : (nvarchar(500)) child0_is_group : (bit) child0_is_keyword : (bit) child0_is_whitespace : (bit) child0_normalized : (nvarchar(max)) child1_children : (nvarchar(max)) child1_class : (nvarchar(500)) child1_is_group : (bit) child1_is_keyword : (bit) child1_is_whitespace : (bit) child1_normalized : (nvarchar(max)) child2_children : (nvarchar(max)) child2_class : (nvarchar(500)) child2_is_group : (bit) child2_is_keyword : (bit) child2_is_whitespace : (bit) child2_normalized : (nvarchar(max)) child3_children : (nvarchar(max)) child3_class : (nvarchar(500)) child3_is_group : (bit) child3_is_keyword : (bit) child3_is_whitespace : (bit) child3_normalized : (nvarchar(max)) child4_children : (nvarchar(max)) child4_class : (nvarchar(500)) child4_is_group : (bit) child4_is_keyword : (bit) child4_is_whitespace : (bit) child4_normalized : (nvarchar(max)) children : (nvarchar(max)) class : (nvarchar(500)) is_group : (bit) is_keyword : (bit) is_whitespace : (bit) normalized : (nvarchar(max)) RowNumber_per_Object : (bigint) SysObject_fullname : (nvarchar(261)) -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_33_objectnormalized.adoc[]"" as sqlparse.RepoObject_SqlModules_33_ObjectNormalized << V >> { - **RepoObject_guid** : (uniqueidentifier) **normalized** : (nvarchar(max)) Min_RowNumber_per_normalized : (bigint) SysObject_fullname : (nvarchar(261)) -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_39_object.adoc[]"" as sqlparse.RepoObject_SqlModules_39_object << V >> { has_GroupBy : (int) is_1_create : (int) is_2_view : (int) is_3_Identifier : (int) is_4_as : (int) is_5_select : (int) is_6_Identifier : (int) is_6_IdentifierList : (int) is_7_from : (int) is_7_IdentifierList : (int) is_8_IdentifierList : (int) is_create_view_Identifier_as_select : (int) is_select_IdentifierList_from : (int) is_union : (int) Min_RowNumber_From : (bigint) Min_RowNumber_GroupBy : (bigint) Min_RowNumber_IdentifierList : (bigint) Min_RowNumber_Where : (bigint) - RepoObject_guid : (uniqueidentifier) SysObject_fullname : (nvarchar(261)) -- } sqlparse.RepoObject_SqlModules_20_statement_children <.. sqlparse.RepoObject_SqlModules_33_ObjectNormalized sqlparse.RepoObject_SqlModules_33_ObjectNormalized <.. sqlparse.RepoObject_SqlModules_39_object ""sqlparse.RepoObject_SqlModules_20_statement_children::normalized"" <-- ""sqlparse.RepoObject_SqlModules_33_ObjectNormalized::normalized"" ""sqlparse.RepoObject_SqlModules_20_statement_children::RepoObject_guid"" <-- ""sqlparse.RepoObject_SqlModules_33_ObjectNormalized::RepoObject_guid"" ""sqlparse.RepoObject_SqlModules_20_statement_children::SysObject_fullname"" <-- ""sqlparse.RepoObject_SqlModules_33_ObjectNormalized::SysObject_fullname"" ""sqlparse.RepoObject_SqlModules_33_ObjectNormalized::Min_RowNumber_per_normalized"" <-- ""sqlparse.RepoObject_SqlModules_39_object::Min_RowNumber_From"" ""sqlparse.RepoObject_SqlModules_33_ObjectNormalized::Min_RowNumber_per_normalized"" <-- ""sqlparse.RepoObject_SqlModules_39_object::Min_RowNumber_GroupBy"" 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 sqlparse.RepoObject_SqlModules_33_ObjectNormalized As -- Select T1.RepoObject_guid , T1.normalized , SysObject_fullname = Max ( T1.SysObject_fullname ) , Min_RowNumber_per_normalized = Min ( T1.RowNumber_per_Object ) From sqlparse.RepoObject_SqlModules_20_statement_children As T1 Group By T1.RepoObject_guid , T1.normalized ---- ======= // end::sql_modules_definition[] ",16137,True,3538.489764340487,median "-- This spec has been automatically generated from STM32F105xx.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; with System; package STM32.RCC is pragma Preelaborate; --------------- -- Registers -- --------------- ----------------- -- CR_Register -- ----------------- subtype CR_HSION_Field is STM32.Bit; subtype CR_HSIRDY_Field is STM32.Bit; subtype CR_HSITRIM_Field is STM32.UInt5; subtype CR_HSICAL_Field is STM32.Byte; subtype CR_HSEON_Field is STM32.Bit; subtype CR_HSERDY_Field is STM32.Bit; subtype CR_HSEBYP_Field is STM32.Bit; subtype CR_CSSON_Field is STM32.Bit; subtype CR_PLLON_Field is STM32.Bit; subtype CR_PLLRDY_Field is STM32.Bit; subtype CR_PLL2ON_Field is STM32.Bit; subtype CR_PLL2RDY_Field is STM32.Bit; subtype CR_PLL3ON_Field is STM32.Bit; subtype CR_PLL3RDY_Field is STM32.Bit; -- Clock control register type CR_Register is record -- Internal High Speed clock enable HSION : CR_HSION_Field := 16#1#; -- Read-only. Internal High Speed clock ready flag HSIRDY : CR_HSIRDY_Field := 16#1#; -- unspecified Reserved_2_2 : STM32.Bit := 16#0#; -- Internal High Speed clock trimming HSITRIM : CR_HSITRIM_Field := 16#10#; -- Read-only. Internal High Speed clock Calibration HSICAL : CR_HSICAL_Field := 16#0#; -- External High Speed clock enable HSEON : CR_HSEON_Field := 16#0#; -- Read-only. External High Speed clock ready flag HSERDY : CR_HSERDY_Field := 16#0#; -- External High Speed clock Bypass HSEBYP : CR_HSEBYP_Field := 16#0#; -- Clock Security System enable CSSON : CR_CSSON_Field := 16#0#; -- unspecified Reserved_20_23 : STM32.UInt4 := 16#0#; -- PLL enable PLLON : CR_PLLON_Field := 16#0#; -- Read-only. PLL clock ready flag PLLRDY : CR_PLLRDY_Field := 16#0#; -- PLL2 enable PLL2ON : CR_PLL2ON_Field := 16#0#; -- Read-only. PLL2 clock ready flag PLL2RDY : CR_PLL2RDY_Field := 16#0#; -- PLL3 enable PLL3ON : CR_PLL3ON_Field := 16#0#; -- Read-only. PLL3 clock ready flag PLL3RDY : CR_PLL3RDY_Field := 16#0#; -- unspecified Reserved_30_31 : STM32.UInt2 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CR_Register use record HSION at 0 range 0 .. 0; HSIRDY at 0 range 1 .. 1; Reserved_2_2 at 0 range 2 .. 2; HSITRIM at 0 range 3 .. 7; HSICAL at 0 range 8 .. 15; HSEON at 0 range 16 .. 16; HSERDY at 0 range 17 .. 17; HSEBYP at 0 range 18 .. 18; CSSON at 0 range 19 .. 19; Reserved_20_23 at 0 range 20 .. 23; PLLON at 0 range 24 .. 24; PLLRDY at 0 range 25 .. 25; PLL2ON at 0 range 26 .. 26; PLL2RDY at 0 range 27 .. 27; PLL3ON at 0 range 28 .. 28; PLL3RDY at 0 range 29 .. 29; Reserved_30_31 at 0 range 30 .. 31; end record; ------------------- -- CFGR_Register -- ------------------- subtype CFGR_SW_Field is STM32.UInt2; subtype CFGR_SWS_Field is STM32.UInt2; subtype CFGR_HPRE_Field is STM32.UInt4; --------------- -- CFGR.PPRE -- --------------- -- CFGR_PPRE array element subtype CFGR_PPRE_Element is STM32.UInt3; -- CFGR_PPRE array type CFGR_PPRE_Field_Array is array (1 .. 2) of CFGR_PPRE_Element with Component_Size => 3, Size => 6; -- Type definition for CFGR_PPRE type CFGR_PPRE_Field (As_Array : Boolean := False) is record case As_Array is when False => -- PPRE as a value Val : STM32.UInt6; when True => -- PPRE as an array Arr : CFGR_PPRE_Field_Array; end case; end record with Unchecked_Union, Size => 6; for CFGR_PPRE_Field use record Val at 0 range 0 .. 5; Arr at 0 range 0 .. 5; end record; subtype CFGR_ADCPRE_Field is STM32.UInt2; subtype CFGR_PLLSRC_Field is STM32.Bit; subtype CFGR_PLLXTPRE_Field is STM32.Bit; subtype CFGR_PLLMUL_Field is STM32.UInt4; subtype CFGR_OTGFSPRE_Field is STM32.Bit; subtype CFGR_MCO_Field is STM32.UInt4; -- Clock configuration register (RCC_CFGR) type CFGR_Register is record -- System clock Switch SW : CFGR_SW_Field := 16#0#; -- Read-only. System Clock Switch Status SWS : CFGR_SWS_Field := 16#0#; -- AHB prescaler HPRE : CFGR_HPRE_Field := 16#0#; -- APB Low speed prescaler (APB1) PPRE : CFGR_PPRE_Field := (As_Array => False, Val => 16#0#); -- ADC prescaler ADCPRE : CFGR_ADCPRE_Field := 16#0#; -- PLL entry clock source PLLSRC : CFGR_PLLSRC_Field := 16#0#; -- HSE divider for PLL entry PLLXTPRE : CFGR_PLLXTPRE_Field := 16#0#; -- PLL Multiplication Factor PLLMUL : CFGR_PLLMUL_Field := 16#0#; -- USB OTG FS prescaler OTGFSPRE : CFGR_OTGFSPRE_Field := 16#0#; -- unspecified Reserved_23_23 : STM32.Bit := 16#0#; -- Microcontroller clock output MCO : CFGR_MCO_Field := 16#0#; -- unspecified Reserved_28_31 : STM32.UInt4 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CFGR_Register use record SW at 0 range 0 .. 1; SWS at 0 range 2 .. 3; HPRE at 0 range 4 .. 7; PPRE at 0 range 8 .. 13; ADCPRE at 0 range 14 .. 15; PLLSRC at 0 range 16 .. 16; PLLXTPRE at 0 range 17 .. 17; PLLMUL at 0 range 18 .. 21; OTGFSPRE at 0 range 22 .. 22; Reserved_23_23 at 0 range 23 .. 23; MCO at 0 range 24 .. 27; Reserved_28_31 at 0 range 28 .. 31; end record; ------------------ -- CIR_Register -- ------------------ subtype CIR_LSIRDYF_Field is STM32.Bit; subtype CIR_LSERDYF_Field is STM32.Bit; subtype CIR_HSIRDYF_Field is STM32.Bit; subtype CIR_HSERDYF_Field is STM32.Bit; subtype CIR_PLLRDYF_Field is STM32.Bit; subtype CIR_PLL2RDYF_Field is STM32.Bit; subtype CIR_PLL3RDYF_Field is STM32.Bit; subtype CIR_CSSF_Field is STM32.Bit; subtype CIR_LSIRDYIE_Field is STM32.Bit; subtype CIR_LSERDYIE_Field is STM32.Bit; subtype CIR_HSIRDYIE_Field is STM32.Bit; subtype CIR_HSERDYIE_Field is STM32.Bit; subtype CIR_PLLRDYIE_Field is STM32.Bit; subtype CIR_PLL2RDYIE_Field is STM32.Bit; subtype CIR_PLL3RDYIE_Field is STM32.Bit; subtype CIR_LSIRDYC_Field is STM32.Bit; subtype CIR_LSERDYC_Field is STM32.Bit; subtype CIR_HSIRDYC_Field is STM32.Bit; subtype CIR_HSERDYC_Field is STM32.Bit; subtype CIR_PLLRDYC_Field is STM32.Bit; subtype CIR_PLL2RDYC_Field is STM32.Bit; subtype CIR_PLL3RDYC_Field is STM32.Bit; subtype CIR_CSSC_Field is STM32.Bit; -- Clock interrupt register (RCC_CIR) type CIR_Register is record -- Read-only. LSI Ready Interrupt flag LSIRDYF : CIR_LSIRDYF_Field := 16#0#; -- Read-only. LSE Ready Interrupt flag LSERDYF : CIR_LSERDYF_Field := 16#0#; -- Read-only. HSI Ready Interrupt flag HSIRDYF : CIR_HSIRDYF_Field := 16#0#; -- Read-only. HSE Ready Interrupt flag HSERDYF : CIR_HSERDYF_Field := 16#0#; -- Read-only. PLL Ready Interrupt flag PLLRDYF : CIR_PLLRDYF_Field := 16#0#; -- Read-only. PLL2 Ready Interrupt flag PLL2RDYF : CIR_PLL2RDYF_Field := 16#0#; -- Read-only. PLL3 Ready Interrupt flag PLL3RDYF : CIR_PLL3RDYF_Field := 16#0#; -- Read-only. Clock Security System Interrupt flag CSSF : CIR_CSSF_Field := 16#0#; -- LSI Ready Interrupt Enable LSIRDYIE : CIR_LSIRDYIE_Field := 16#0#; -- LSE Ready Interrupt Enable LSERDYIE : CIR_LSERDYIE_Field := 16#0#; -- HSI Ready Interrupt Enable HSIRDYIE : CIR_HSIRDYIE_Field := 16#0#; -- HSE Ready Interrupt Enable HSERDYIE : CIR_HSERDYIE_Field := 16#0#; -- PLL Ready Interrupt Enable PLLRDYIE : CIR_PLLRDYIE_Field := 16#0#; -- PLL2 Ready Interrupt Enable PLL2RDYIE : CIR_PLL2RDYIE_Field := 16#0#; -- PLL3 Ready Interrupt Enable PLL3RDYIE : CIR_PLL3RDYIE_Field := 16#0#; -- unspecified Reserved_15_15 : STM32.Bit := 16#0#; -- Write-only. LSI Ready Interrupt Clear LSIRDYC : CIR_LSIRDYC_Field := 16#0#; -- Write-only. LSE Ready Interrupt Clear LSERDYC : CIR_LSERDYC_Field := 16#0#; -- Write-only. HSI Ready Interrupt Clear HSIRDYC : CIR_HSIRDYC_Field := 16#0#; -- Write-only. HSE Ready Interrupt Clear HSERDYC : CIR_HSERDYC_Field := 16#0#; -- Write-only. PLL Ready Interrupt Clear PLLRDYC : CIR_PLLRDYC_Field := 16#0#; -- Write-only. PLL2 Ready Interrupt Clear PLL2RDYC : CIR_PLL2RDYC_Field := 16#0#; -- Write-only. PLL3 Ready Interrupt Clear PLL3RDYC : CIR_PLL3RDYC_Field := 16#0#; -- Write-only. Clock security system interrupt clear CSSC : CIR_CSSC_Field := 16#0#; -- unspecified Reserved_24_31 : STM32.Byte := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CIR_Register use record LSIRDYF at 0 range 0 .. 0; LSERDYF at 0 range 1 .. 1; HSIRDYF at 0 range 2 .. 2; HSERDYF at 0 range 3 .. 3; PLLRDYF at 0 range 4 .. 4; PLL2RDYF at 0 range 5 .. 5; PLL3RDYF at 0 range 6 .. 6; CSSF at 0 range 7 .. 7; LSIRDYIE at 0 range 8 .. 8; LSERDYIE at 0 range 9 .. 9; HSIRDYIE at 0 range 10 .. 10; HSERDYIE at 0 range 11 .. 11; PLLRDYIE at 0 range 12 .. 12; PLL2RDYIE at 0 range 13 .. 13; PLL3RDYIE at 0 range 14 .. 14; Reserved_15_15 at 0 range 15 .. 15; LSIRDYC at 0 range 16 .. 16; LSERDYC at 0 range 17 .. 17; HSIRDYC at 0 range 18 .. 18; HSERDYC at 0 range 19 .. 19; PLLRDYC at 0 range 20 .. 20; PLL2RDYC at 0 range 21 .. 21; PLL3RDYC at 0 range 22 .. 22; CSSC at 0 range 23 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; ----------------------- -- APB2RSTR_Register -- ----------------------- subtype APB2RSTR_AFIORST_Field is STM32.Bit; subtype APB2RSTR_IOPARST_Field is STM32.Bit; subtype APB2RSTR_IOPBRST_Field is STM32.Bit; subtype APB2RSTR_IOPCRST_Field is STM32.Bit; subtype APB2RSTR_IOPDRST_Field is STM32.Bit; subtype APB2RSTR_IOPERST_Field is STM32.Bit; subtype APB2RSTR_ADC1RST_Field is STM32.Bit; subtype APB2RSTR_ADC2RST_Field is STM32.Bit; subtype APB2RSTR_TIM1RST_Field is STM32.Bit; subtype APB2RSTR_SPI1RST_Field is STM32.Bit; subtype APB2RSTR_USART1RST_Field is STM32.Bit; -- APB2 peripheral reset register (RCC_APB2RSTR) type APB2RSTR_Register is record -- Alternate function I/O reset AFIORST : APB2RSTR_AFIORST_Field := 16#0#; -- unspecified Reserved_1_1 : STM32.Bit := 16#0#; -- IO port A reset IOPARST : APB2RSTR_IOPARST_Field := 16#0#; -- IO port B reset IOPBRST : APB2RSTR_IOPBRST_Field := 16#0#; -- IO port C reset IOPCRST : APB2RSTR_IOPCRST_Field := 16#0#; -- IO port D reset IOPDRST : APB2RSTR_IOPDRST_Field := 16#0#; -- IO port E reset IOPERST : APB2RSTR_IOPERST_Field := 16#0#; -- unspecified Reserved_7_8 : STM32.UInt2 := 16#0#; -- ADC 1 interface reset ADC1RST : APB2RSTR_ADC1RST_Field := 16#0#; -- ADC 2 interface reset ADC2RST : APB2RSTR_ADC2RST_Field := 16#0#; -- TIM1 timer reset TIM1RST : APB2RSTR_TIM1RST_Field := 16#0#; -- SPI 1 reset SPI1RST : APB2RSTR_SPI1RST_Field := 16#0#; -- unspecified Reserved_13_13 : STM32.Bit := 16#0#; -- USART1 reset USART1RST : APB2RSTR_USART1RST_Field := 16#0#; -- unspecified Reserved_15_31 : STM32.UInt17 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for APB2RSTR_Register use record AFIORST at 0 range 0 .. 0; Reserved_1_1 at 0 range 1 .. 1; IOPARST at 0 range 2 .. 2; IOPBRST at 0 range 3 .. 3; IOPCRST at 0 range 4 .. 4; IOPDRST at 0 range 5 .. 5; IOPERST at 0 range 6 .. 6; Reserved_7_8 at 0 range 7 .. 8; ADC1RST at 0 range 9 .. 9; ADC2RST at 0 range 10 .. 10; TIM1RST at 0 range 11 .. 11; SPI1RST at 0 range 12 .. 12; Reserved_13_13 at 0 range 13 .. 13; USART1RST at 0 range 14 .. 14; Reserved_15_31 at 0 range 15 .. 31; end record; ----------------------- -- APB1RSTR_Register -- ----------------------- subtype APB1RSTR_TIM2RST_Field is STM32.Bit; subtype APB1RSTR_TIM3RST_Field is STM32.Bit; subtype APB1RSTR_TIM4RST_Field is STM32.Bit; subtype APB1RSTR_TIM5RST_Field is STM32.Bit; subtype APB1RSTR_TIM6RST_Field is STM32.Bit; subtype APB1RSTR_TIM7RST_Field is STM32.Bit; subtype APB1RSTR_WWDGRST_Field is STM32.Bit; subtype APB1RSTR_SPI2RST_Field is STM32.Bit; subtype APB1RSTR_SPI3RST_Field is STM32.Bit; subtype APB1RSTR_USART2RST_Field is STM32.Bit; subtype APB1RSTR_USART3RST_Field is STM32.Bit; subtype APB1RSTR_USART4RST_Field is STM32.Bit; subtype APB1RSTR_USART5RST_Field is STM32.Bit; subtype APB1RSTR_I2C1RST_Field is STM32.Bit; subtype APB1RSTR_I2C2RST_Field is STM32.Bit; subtype APB1RSTR_CAN1RST_Field is STM32.Bit; subtype APB1RSTR_CAN2RST_Field is STM32.Bit; subtype APB1RSTR_BKPRST_Field is STM32.Bit; subtype APB1RSTR_PWRRST_Field is STM32.Bit; subtype APB1RSTR_DACRST_Field is STM32.Bit; -- APB1 peripheral reset register (RCC_APB1RSTR) type APB1RSTR_Register is record -- Timer 2 reset TIM2RST : APB1RSTR_TIM2RST_Field := 16#0#; -- Timer 3 reset TIM3RST : APB1RSTR_TIM3RST_Field := 16#0#; -- Timer 4 reset TIM4RST : APB1RSTR_TIM4RST_Field := 16#0#; -- Timer 5 reset TIM5RST : APB1RSTR_TIM5RST_Field := 16#0#; -- Timer 6 reset TIM6RST : APB1RSTR_TIM6RST_Field := 16#0#; -- Timer 7 reset TIM7RST : APB1RSTR_TIM7RST_Field := 16#0#; -- unspecified Reserved_6_10 : STM32.UInt5 := 16#0#; -- Window watchdog reset WWDGRST : APB1RSTR_WWDGRST_Field := 16#0#; -- unspecified Reserved_12_13 : STM32.UInt2 := 16#0#; -- SPI2 reset SPI2RST : APB1RSTR_SPI2RST_Field := 16#0#; -- SPI3 reset SPI3RST : APB1RSTR_SPI3RST_Field := 16#0#; -- unspecified Reserved_16_16 : STM32.Bit := 16#0#; -- USART 2 reset USART2RST : APB1RSTR_USART2RST_Field := 16#0#; -- USART 3 reset USART3RST : APB1RSTR_USART3RST_Field := 16#0#; -- USART 4 reset USART4RST : APB1RSTR_USART4RST_Field := 16#0#; -- USART 5 reset USART5RST : APB1RSTR_USART5RST_Field := 16#0#; -- I2C1 reset I2C1RST : APB1RSTR_I2C1RST_Field := 16#0#; -- I2C2 reset I2C2RST : APB1RSTR_I2C2RST_Field := 16#0#; -- unspecified Reserved_23_24 : STM32.UInt2 := 16#0#; -- CAN1 reset CAN1RST : APB1RSTR_CAN1RST_Field := 16#0#; -- CAN2 reset CAN2RST : APB1RSTR_CAN2RST_Field := 16#0#; -- Backup interface reset BKPRST : APB1RSTR_BKPRST_Field := 16#0#; -- Power interface reset PWRRST : APB1RSTR_PWRRST_Field := 16#0#; -- DAC interface reset DACRST : APB1RSTR_DACRST_Field := 16#0#; -- unspecified Reserved_30_31 : STM32.UInt2 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for APB1RSTR_Register use record TIM2RST at 0 range 0 .. 0; TIM3RST at 0 range 1 .. 1; TIM4RST at 0 range 2 .. 2; TIM5RST at 0 range 3 .. 3; TIM6RST at 0 range 4 .. 4; TIM7RST at 0 range 5 .. 5; Reserved_6_10 at 0 range 6 .. 10; WWDGRST at 0 range 11 .. 11; Reserved_12_13 at 0 range 12 .. 13; SPI2RST at 0 range 14 .. 14; SPI3RST at 0 range 15 .. 15; Reserved_16_16 at 0 range 16 .. 16; USART2RST at 0 range 17 .. 17; USART3RST at 0 range 18 .. 18; USART4RST at 0 range 19 .. 19; USART5RST at 0 range 20 .. 20; I2C1RST at 0 range 21 .. 21; I2C2RST at 0 range 22 .. 22; Reserved_23_24 at 0 range 23 .. 24; CAN1RST at 0 range 25 .. 25; CAN2RST at 0 range 26 .. 26; BKPRST at 0 range 27 .. 27; PWRRST at 0 range 28 .. 28; DACRST at 0 range 29 .. 29; Reserved_30_31 at 0 range 30 .. 31; end record; --------------------- -- AHBENR_Register -- --------------------- subtype AHBENR_DMA1EN_Field is STM32.Bit; subtype AHBENR_DMA2EN_Field is STM32.Bit; subtype AHBENR_SRAMEN_Field is STM32.Bit; subtype AHBENR_FLITFEN_Field is STM32.Bit; subtype AHBENR_CRCEN_Field is STM32.Bit; subtype AHBENR_OTGFSEN_Field is STM32.Bit; -- AHB Peripheral Clock enable register (RCC_AHBENR) type AHBENR_Register is record -- DMA1 clock enable DMA1EN : AHBENR_DMA1EN_Field := 16#0#; -- DMA2 clock enable DMA2EN : AHBENR_DMA2EN_Field := 16#0#; -- SRAM interface clock enable SRAMEN : AHBENR_SRAMEN_Field := 16#1#; -- unspecified Reserved_3_3 : STM32.Bit := 16#0#; -- FLITF clock enable FLITFEN : AHBENR_FLITFEN_Field := 16#1#; -- unspecified Reserved_5_5 : STM32.Bit := 16#0#; -- CRC clock enable CRCEN : AHBENR_CRCEN_Field := 16#0#; -- unspecified Reserved_7_11 : STM32.UInt5 := 16#0#; -- USB OTG FS clock enable OTGFSEN : AHBENR_OTGFSEN_Field := 16#0#; -- unspecified Reserved_13_31 : STM32.UInt19 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for AHBENR_Register use record DMA1EN at 0 range 0 .. 0; DMA2EN at 0 range 1 .. 1; SRAMEN at 0 range 2 .. 2; Reserved_3_3 at 0 range 3 .. 3; FLITFEN at 0 range 4 .. 4; Reserved_5_5 at 0 range 5 .. 5; CRCEN at 0 range 6 .. 6; Reserved_7_11 at 0 range 7 .. 11; OTGFSEN at 0 range 12 .. 12; Reserved_13_31 at 0 range 13 .. 31; end record; ---------------------- -- APB2ENR_Register -- ---------------------- subtype APB2ENR_AFIOEN_Field is STM32.Bit; subtype APB2ENR_IOPAEN_Field is STM32.Bit; subtype APB2ENR_IOPBEN_Field is STM32.Bit; subtype APB2ENR_IOPCEN_Field is STM32.Bit; subtype APB2ENR_IOPDEN_Field is STM32.Bit; subtype APB2ENR_IOPEEN_Field is STM32.Bit; subtype APB2ENR_ADC1EN_Field is STM32.Bit; subtype APB2ENR_ADC2EN_Field is STM32.Bit; subtype APB2ENR_TIM1EN_Field is STM32.Bit; subtype APB2ENR_SPI1EN_Field is STM32.Bit; subtype APB2ENR_USART1EN_Field is STM32.Bit; -- APB2 peripheral clock enable register (RCC_APB2ENR) type APB2ENR_Register is record -- Alternate function I/O clock enable AFIOEN : APB2ENR_AFIOEN_Field := 16#0#; -- unspecified Reserved_1_1 : STM32.Bit := 16#0#; -- I/O port A clock enable IOPAEN : APB2ENR_IOPAEN_Field := 16#0#; -- I/O port B clock enable IOPBEN : APB2ENR_IOPBEN_Field := 16#0#; -- I/O port C clock enable IOPCEN : APB2ENR_IOPCEN_Field := 16#0#; -- I/O port D clock enable IOPDEN : APB2ENR_IOPDEN_Field := 16#0#; -- I/O port E clock enable IOPEEN : APB2ENR_IOPEEN_Field := 16#0#; -- unspecified Reserved_7_8 : STM32.UInt2 := 16#0#; -- ADC 1 interface clock enable ADC1EN : APB2ENR_ADC1EN_Field := 16#0#; -- ADC 2 interface clock enable ADC2EN : APB2ENR_ADC2EN_Field := 16#0#; -- TIM1 Timer clock enable TIM1EN : APB2ENR_TIM1EN_Field := 16#0#; -- SPI 1 clock enable SPI1EN : APB2ENR_SPI1EN_Field := 16#0#; -- unspecified Reserved_13_13 : STM32.Bit := 16#0#; -- USART1 clock enable USART1EN : APB2ENR_USART1EN_Field := 16#0#; -- unspecified Reserved_15_31 : STM32.UInt17 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for APB2ENR_Register use record AFIOEN at 0 range 0 .. 0; Reserved_1_1 at 0 range 1 .. 1; IOPAEN at 0 range 2 .. 2; IOPBEN at 0 range 3 .. 3; IOPCEN at 0 range 4 .. 4; IOPDEN at 0 range 5 .. 5; IOPEEN at 0 range 6 .. 6; Reserved_7_8 at 0 range 7 .. 8; ADC1EN at 0 range 9 .. 9; ADC2EN at 0 range 10 .. 10; TIM1EN at 0 range 11 .. 11; SPI1EN at 0 range 12 .. 12; Reserved_13_13 at 0 range 13 .. 13; USART1EN at 0 range 14 .. 14; Reserved_15_31 at 0 range 15 .. 31; end record; ---------------------- -- APB1ENR_Register -- ---------------------- subtype APB1ENR_TIM2EN_Field is STM32.Bit; subtype APB1ENR_TIM3EN_Field is STM32.Bit; subtype APB1ENR_TIM4EN_Field is STM32.Bit; subtype APB1ENR_TIM5EN_Field is STM32.Bit; subtype APB1ENR_TIM6EN_Field is STM32.Bit; subtype APB1ENR_TIM7EN_Field is STM32.Bit; subtype APB1ENR_WWDGEN_Field is STM32.Bit; subtype APB1ENR_SPI2EN_Field is STM32.Bit; subtype APB1ENR_SPI3EN_Field is STM32.Bit; subtype APB1ENR_USART2EN_Field is STM32.Bit; subtype APB1ENR_USART3EN_Field is STM32.Bit; subtype APB1ENR_UART4EN_Field is STM32.Bit; subtype APB1ENR_UART5EN_Field is STM32.Bit; subtype APB1ENR_I2C1EN_Field is STM32.Bit; subtype APB1ENR_I2C2EN_Field is STM32.Bit; subtype APB1ENR_CAN1EN_Field is STM32.Bit; subtype APB1ENR_CAN2EN_Field is STM32.Bit; subtype APB1ENR_BKPEN_Field is STM32.Bit; subtype APB1ENR_PWREN_Field is STM32.Bit; subtype APB1ENR_DACEN_Field is STM32.Bit; -- APB1 peripheral clock enable register (RCC_APB1ENR) type APB1ENR_Register is record -- Timer 2 clock enable TIM2EN : APB1ENR_TIM2EN_Field := 16#0#; -- Timer 3 clock enable TIM3EN : APB1ENR_TIM3EN_Field := 16#0#; -- Timer 4 clock enable TIM4EN : APB1ENR_TIM4EN_Field := 16#0#; -- Timer 5 clock enable TIM5EN : APB1ENR_TIM5EN_Field := 16#0#; -- Timer 6 clock enable TIM6EN : APB1ENR_TIM6EN_Field := 16#0#; -- Timer 7 clock enable TIM7EN : APB1ENR_TIM7EN_Field := 16#0#; -- unspecified Reserved_6_10 : STM32.UInt5 := 16#0#; -- Window watchdog clock enable WWDGEN : APB1ENR_WWDGEN_Field := 16#0#; -- unspecified Reserved_12_13 : STM32.UInt2 := 16#0#; -- SPI 2 clock enable SPI2EN : APB1ENR_SPI2EN_Field := 16#0#; -- SPI 3 clock enable SPI3EN : APB1ENR_SPI3EN_Field := 16#0#; -- unspecified Reserved_16_16 : STM32.Bit := 16#0#; -- USART 2 clock enable USART2EN : APB1ENR_USART2EN_Field := 16#0#; -- USART 3 clock enable USART3EN : APB1ENR_USART3EN_Field := 16#0#; -- UART 4 clock enable UART4EN : APB1ENR_UART4EN_Field := 16#0#; -- UART 5 clock enable UART5EN : APB1ENR_UART5EN_Field := 16#0#; -- I2C 1 clock enable I2C1EN : APB1ENR_I2C1EN_Field := 16#0#; -- I2C 2 clock enable I2C2EN : APB1ENR_I2C2EN_Field := 16#0#; -- unspecified Reserved_23_24 : STM32.UInt2 := 16#0#; -- CAN1 clock enable CAN1EN : APB1ENR_CAN1EN_Field := 16#0#; -- CAN2 clock enable CAN2EN : APB1ENR_CAN2EN_Field := 16#0#; -- Backup interface clock enable BKPEN : APB1ENR_BKPEN_Field := 16#0#; -- Power interface clock enable PWREN : APB1ENR_PWREN_Field := 16#0#; -- DAC interface clock enable DACEN : APB1ENR_DACEN_Field := 16#0#; -- unspecified Reserved_30_31 : STM32.UInt2 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for APB1ENR_Register use record TIM2EN at 0 range 0 .. 0; TIM3EN at 0 range 1 .. 1; TIM4EN at 0 range 2 .. 2; TIM5EN at 0 range 3 .. 3; TIM6EN at 0 range 4 .. 4; TIM7EN at 0 range 5 .. 5; Reserved_6_10 at 0 range 6 .. 10; WWDGEN at 0 range 11 .. 11; Reserved_12_13 at 0 range 12 .. 13; SPI2EN at 0 range 14 .. 14; SPI3EN at 0 range 15 .. 15; Reserved_16_16 at 0 range 16 .. 16; USART2EN at 0 range 17 .. 17; USART3EN at 0 range 18 .. 18; UART4EN at 0 range 19 .. 19; UART5EN at 0 range 20 .. 20; I2C1EN at 0 range 21 .. 21; I2C2EN at 0 range 22 .. 22; Reserved_23_24 at 0 range 23 .. 24; CAN1EN at 0 range 25 .. 25; CAN2EN at 0 range 26 .. 26; BKPEN at 0 range 27 .. 27; PWREN at 0 range 28 .. 28; DACEN at 0 range 29 .. 29; Reserved_30_31 at 0 range 30 .. 31; end record; ------------------- -- BDCR_Register -- ------------------- subtype BDCR_LSEON_Field is STM32.Bit; subtype BDCR_LSERDY_Field is STM32.Bit; subtype BDCR_LSEBYP_Field is STM32.Bit; subtype BDCR_RTCSEL_Field is STM32.UInt2; subtype BDCR_RTCEN_Field is STM32.Bit; subtype BDCR_BDRST_Field is STM32.Bit; -- Backup domain control register (RCC_BDCR) type BDCR_Register is record -- External Low Speed oscillator enable LSEON : BDCR_LSEON_Field := 16#0#; -- Read-only. External Low Speed oscillator ready LSERDY : BDCR_LSERDY_Field := 16#0#; -- External Low Speed oscillator bypass LSEBYP : BDCR_LSEBYP_Field := 16#0#; -- unspecified Reserved_3_7 : STM32.UInt5 := 16#0#; -- RTC clock source selection RTCSEL : BDCR_RTCSEL_Field := 16#0#; -- unspecified Reserved_10_14 : STM32.UInt5 := 16#0#; -- RTC clock enable RTCEN : BDCR_RTCEN_Field := 16#0#; -- Backup domain software reset BDRST : BDCR_BDRST_Field := 16#0#; -- unspecified Reserved_17_31 : STM32.UInt15 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for BDCR_Register use record LSEON at 0 range 0 .. 0; LSERDY at 0 range 1 .. 1; LSEBYP at 0 range 2 .. 2; Reserved_3_7 at 0 range 3 .. 7; RTCSEL at 0 range 8 .. 9; Reserved_10_14 at 0 range 10 .. 14; RTCEN at 0 range 15 .. 15; BDRST at 0 range 16 .. 16; Reserved_17_31 at 0 range 17 .. 31; end record; ------------------ -- CSR_Register -- ------------------ subtype CSR_LSION_Field is STM32.Bit; subtype CSR_LSIRDY_Field is STM32.Bit; subtype CSR_RMVF_Field is STM32.Bit; subtype CSR_PINRSTF_Field is STM32.Bit; subtype CSR_PORRSTF_Field is STM32.Bit; subtype CSR_SFTRSTF_Field is STM32.Bit; subtype CSR_IWDGRSTF_Field is STM32.Bit; subtype CSR_WWDGRSTF_Field is STM32.Bit; subtype CSR_LPWRRSTF_Field is STM32.Bit; -- Control/status register (RCC_CSR) type CSR_Register is record -- Internal low speed oscillator enable LSION : CSR_LSION_Field := 16#0#; -- Read-only. Internal low speed oscillator ready LSIRDY : CSR_LSIRDY_Field := 16#0#; -- unspecified Reserved_2_23 : STM32.UInt22 := 16#0#; -- Remove reset flag RMVF : CSR_RMVF_Field := 16#0#; -- unspecified Reserved_25_25 : STM32.Bit := 16#0#; -- PIN reset flag PINRSTF : CSR_PINRSTF_Field := 16#1#; -- POR/PDR reset flag PORRSTF : CSR_PORRSTF_Field := 16#1#; -- Software reset flag SFTRSTF : CSR_SFTRSTF_Field := 16#0#; -- Independent watchdog reset flag IWDGRSTF : CSR_IWDGRSTF_Field := 16#0#; -- Window watchdog reset flag WWDGRSTF : CSR_WWDGRSTF_Field := 16#0#; -- Low-power reset flag LPWRRSTF : CSR_LPWRRSTF_Field := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CSR_Register use record LSION at 0 range 0 .. 0; LSIRDY at 0 range 1 .. 1; Reserved_2_23 at 0 range 2 .. 23; RMVF at 0 range 24 .. 24; Reserved_25_25 at 0 range 25 .. 25; PINRSTF at 0 range 26 .. 26; PORRSTF at 0 range 27 .. 27; SFTRSTF at 0 range 28 .. 28; IWDGRSTF at 0 range 29 .. 29; WWDGRSTF at 0 range 30 .. 30; LPWRRSTF at 0 range 31 .. 31; end record; ---------------------- -- AHBRSTR_Register -- ---------------------- subtype AHBRSTR_OTGFSRST_Field is STM32.Bit; -- AHB peripheral clock reset register (RCC_AHBRSTR) type AHBRSTR_Register is record -- unspecified Reserved_0_11 : STM32.UInt12 := 16#0#; -- USB OTG FS reset OTGFSRST : AHBRSTR_OTGFSRST_Field := 16#0#; -- unspecified Reserved_13_31 : STM32.UInt19 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for AHBRSTR_Register use record Reserved_0_11 at 0 range 0 .. 11; OTGFSRST at 0 range 12 .. 12; Reserved_13_31 at 0 range 13 .. 31; end record; -------------------- -- CFGR2_Register -- -------------------- ------------------ -- CFGR2.PREDIV -- ------------------ -- CFGR2_PREDIV array element subtype CFGR2_PREDIV_Element is STM32.UInt4; -- CFGR2_PREDIV array type CFGR2_PREDIV_Field_Array is array (1 .. 2) of CFGR2_PREDIV_Element with Component_Size => 4, Size => 8; -- Type definition for CFGR2_PREDIV type CFGR2_PREDIV_Field (As_Array : Boolean := False) is record case As_Array is when False => -- PREDIV as a value Val : STM32.Byte; when True => -- PREDIV as an array Arr : CFGR2_PREDIV_Field_Array; end case; end record with Unchecked_Union, Size => 8; for CFGR2_PREDIV_Field use record Val at 0 range 0 .. 7; Arr at 0 range 0 .. 7; end record; subtype CFGR2_PLL2MUL_Field is STM32.UInt4; subtype CFGR2_PLL3MUL_Field is STM32.UInt4; subtype CFGR2_PREDIV1SRC_Field is STM32.Bit; subtype CFGR2_I2S2SRC_Field is STM32.Bit; subtype CFGR2_I2S3SRC_Field is STM32.Bit; -- Clock configuration register2 (RCC_CFGR2) type CFGR2_Register is record -- PREDIV1 division factor PREDIV : CFGR2_PREDIV_Field := (As_Array => False, Val => 16#0#); -- PLL2 Multiplication Factor PLL2MUL : CFGR2_PLL2MUL_Field := 16#0#; -- PLL3 Multiplication Factor PLL3MUL : CFGR2_PLL3MUL_Field := 16#0#; -- PREDIV1 entry clock source PREDIV1SRC : CFGR2_PREDIV1SRC_Field := 16#0#; -- I2S2 clock source I2S2SRC : CFGR2_I2S2SRC_Field := 16#0#; -- I2S3 clock source I2S3SRC : CFGR2_I2S3SRC_Field := 16#0#; -- unspecified Reserved_19_31 : STM32.UInt13 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CFGR2_Register use record PREDIV at 0 range 0 .. 7; PLL2MUL at 0 range 8 .. 11; PLL3MUL at 0 range 12 .. 15; PREDIV1SRC at 0 range 16 .. 16; I2S2SRC at 0 range 17 .. 17; I2S3SRC at 0 range 18 .. 18; Reserved_19_31 at 0 range 19 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- Reset and clock control type RCC_Peripheral is record -- Clock control register CR : CR_Register; -- Clock configuration register (RCC_CFGR) CFGR : CFGR_Register; -- Clock interrupt register (RCC_CIR) CIR : CIR_Register; -- APB2 peripheral reset register (RCC_APB2RSTR) APB2RSTR : APB2RSTR_Register; -- APB1 peripheral reset register (RCC_APB1RSTR) APB1RSTR : APB1RSTR_Register; -- AHB Peripheral Clock enable register (RCC_AHBENR) AHBENR : AHBENR_Register; -- APB2 peripheral clock enable register (RCC_APB2ENR) APB2ENR : APB2ENR_Register; -- APB1 peripheral clock enable register (RCC_APB1ENR) APB1ENR : APB1ENR_Register; -- Backup domain control register (RCC_BDCR) BDCR : BDCR_Register; -- Control/status register (RCC_CSR) CSR : CSR_Register; -- AHB peripheral clock reset register (RCC_AHBRSTR) AHBRSTR : AHBRSTR_Register; -- Clock configuration register2 (RCC_CFGR2) CFGR2 : CFGR2_Register; end record with Volatile; for RCC_Peripheral use record CR at 0 range 0 .. 31; CFGR at 4 range 0 .. 31; CIR at 8 range 0 .. 31; APB2RSTR at 12 range 0 .. 31; APB1RSTR at 16 range 0 .. 31; AHBENR at 20 range 0 .. 31; APB2ENR at 24 range 0 .. 31; APB1ENR at 28 range 0 .. 31; BDCR at 32 range 0 .. 31; CSR at 36 range 0 .. 31; AHBRSTR at 40 range 0 .. 31; CFGR2 at 44 range 0 .. 31; end record; -- Reset and clock control RCC_Periph : aliased RCC_Peripheral with Import, Address => RCC_Base; end STM32.RCC; ",12526,True,3253.057926209903,median "[[bbv2.jam]] = Boost.Jam Documentation ____ Jam is a make(1) replacement that makes building simple things simple and building complicated things manageable. ____ [[jam.building]] == Building B2 Installing `B2` after building it is simply a matter of copying the generated executables someplace in your `PATH`. For building the executables there are a set of `build` bootstrap scripts to accommodate particular environments. The scripts take one optional argument, the name of the toolset to build with. When the toolset is not given an attempt is made to detect an available toolset and use that. The build scripts accept these arguments: [source,shell] ---- build [toolset] ---- Running the scripts without arguments will give you the best chance of success. On Windows platforms from a command console do: [source,bat] ---- cd jam source location .\\build.bat ---- On Unix type platforms do: [source,shell] ---- cd jam source location sh ./build.sh ---- For the Boost.Jam source included with the Boost distribution the _jam source location_ is `BOOST_ROOT/tools/build/src/engine`. If the scripts fail to detect an appropriate toolset to build with your particular toolset may not be auto-detectable. In that case, you can specify the toolset as the first argument, this assumes that the toolset is readily available in the `PATH`. NOTE: The toolset used to build Boost.Jam is independent of the toolsets used for B2. Only one version of Boost.Jam is needed to use B2. The supported toolsets, and whether they are auto-detected, are: [%autowidth] .Supported Toolsets [cols="",,,"",options=""header"",] |=== |Script |Platform |Toolset |Detection and Notes |`build.bat` |Windows NT, 2000, and XP |http://www.codegear.com/downloads/free/cppbuilder[`borland`], http://www.borland.com/[Borland] {CPP}Builder (BCC 5.5) a| * Common install location: `C:\\Borland\\BCC55` * `BCC32.EXE` in `PATH` | | |http://www.comeaucomputing.com/[`como`], Comeau Computing C/{CPP} | | | |http://gcc.gnu.org/[`gcc`], GNU GCC | | | |http://gcc.gnu.org/[`gcc-nocygwin`], GNU GCC | | | |http://www.intel.com/software/products/compilers/c60[`intel-win32`], Intel {CPP} Compiler for Windows a| * `ICL.EXE` in `PATH` | | |http://www.metrowerks.com/[`metrowerks`], MetroWerks CodeWarrior C/{CPP} 7.x, 8.x, 9.x a| * `CWFolder` variable configured * `MWCC.EXE` in PATH | | |http://www.mingw.org/[`mingw`], GNU http://gcc.gnu.org/[GCC] as the http://www.mingw.org/[MinGW] configuration a| * Common install location: `C:\\MinGW` | | |http://msdn.microsoft.com/visualc/[`msvc`], Microsoft Visual {CPP} 6.x a| * `VCVARS32.BAT` already configured * `%MSVCDir%` is present in environment * Common install locations: `%ProgramFiles%\\Microsoft Visual Studio`, `%ProgramFiles%\\Microsoft Visual {CPP}` * `CL.EXE` in `PATH` | | |http://msdn.microsoft.com/visualc/[`vc7`], Microsoft Visual {CPP} 7.x a| * `VCVARS32.BAT` or `VSVARS32.BAT` already configured * `%VS71COMNTOOLS%` is present in environment * `%VCINSTALLDIR%` is present in environment * Common install locations: `%ProgramFiles%\\Microsoft Visual Studio .NET`, `%ProgramFiles%\\Microsoft Visual Studio .NET 2003` * `CL.EXE` in `PATH` | | |http://msdn.microsoft.com/visualc/[`vc8` and `vc9`], Microsoft Visual {CPP} 8.x and 9.x a| Detection: * `VCVARSALL.BAT` already configured * `%VS90COMNTOOLS%` is present in environment * Common install location: `%ProgramFiles%\\Microsoft Visual Studio 9` * `%VS80COMNTOOLS%` is present in environment * Common install location: `%ProgramFiles%\\Microsoft Visual Studio 8` * `CL.EXE` in `PATH` Notes: * If `VCVARSALL.BAT` is called to set up the toolset, it is passed all the extra arguments, see below for what those arguments are. This can be used to build, for example, a Win64 specific version of `b2`. Consult the VisualStudio documentation for what the possible argument values to the `VCVARSALL.BAT` are. |`build.sh` |Unix, Linux, Cygwin, etc. |http://www.hp.com/go/c++[`acc`], HP-UX aCC a| * `aCC` in `PATH` * `uname` is ""HP-UX"" | | |http://www.comeaucomputing.com/[`como`], Comeau Computing C/{CPP} a| * `como` in `PATH` | | |http://gcc.gnu.org/[`gcc`], GNU GCC a| * `gcc` in `PATH` | | |http://www.intel.com/software/products/compilers/c60l/[`intel-linux`], Intel {CPP} for Linux a| * `icc` in `PATH` * Common install locations: `/opt/intel/cc/9.0`, `/opt/intel_cc_80`, `/opt/intel/compiler70`, `/opt/intel/compiler60`, `/opt/intel/compiler50` | | |`kcc`, Intel KAI {CPP} a| * `KCC` in `PATH` | | |http://www.codegear.com/downloads/free/cppbuilder[`kylix`], http://www.borland.com/[Borland] {CPP}Builder a| * `bc++` in `PATH` | | |http://www.sgi.com/developers/devtools/languages/mipspro.html[`mipspro`], SGI MIPSpro C a| * `uname` is ""IRIX"" or ""IRIX64"" | | |`sunpro`, Sun Workshop 6 {CPP} a| * Standard install location: `/opt/SUNWspro` | | |`qcc`, http://www.qnx.com/[QNX Neutrino] a| * `uname` is ""QNX"" and `qcc` in `PATH` | | |http://www.tru64unix.compaq.com/cplus/[`true64cxx`], Compaq {CPP} Compiler for True64 UNIX a| * `uname` is ""OSF1"" | | |http://www.ibm.com/software/awdtools/vacpp/[`vacpp`], IBM VisualAge {CPP} a| * `xlc` in `PATH` | |MacOS X |http://developer.apple.com/tools/compilers.html[`darwin`], Apple MacOS X GCC a| * `uname` is ""Darwin"" | |Windows NT, 2000, and XP |http://www.mingw.org/[`mingw`], GNU http://gcc.gnu.org/[GCC] as the http://www.mingw.org/[MinGW] configuration with the MSYS shell a| * Common install location: `/mingw` |=== The built executables are placed in a subdirectory specific to your platform. For example, in Linux running on an Intel x86 compatible chip, the executables are placed in: `bin.linuxx86`. The `b2[.exe]` executable can be used to invoke B2. The build scripts support additional invocation arguments for use by developers of Boost.Jam and for additional setup of the toolset. The extra arguments come after the toolset: * Arguments not in the form of an option, before option arguments, are used for extra setup to toolset configuration scripts. * Arguments of the form `--option`, which are passed to the `build.jam` build script. * Arguments not in the form of an option, after the options, which are targets for the `build.jam` script. ---- build [toolset] [setup*] [--option+ target*] ---- The arguments immediately after the toolset are passed directly to the setup script of the toolset, if available and if it needs to be invoked. This allows one to configure the toolset ass needed to do non-default builds of `b2`. For example to build a Win64 version with `vc8`. See the toolset description above for when particular toolsets support this. The arguments starting with the `--option` forms are passed to the `build.jam` script and are used to further customize what gets built. Options and targets supported by the `build.jam` script: `---`:: Empty option when one wants to only specify a target. `--release`:: The default, builds the optimized executable. `--debug`:: Builds debugging versions of the executable. When built they are placed in their own directory `bin./platform/.debug`. `--grammar`:: Normally the Jam language grammar parsing files are not regenerated. This forces building of the grammar, although it may not force the regeneration of the grammar parser. If the parser is out of date it will be regenerated and subsequently built. `--with-python=path`:: Enables Python integration, given a path to the Python libraries. `--gc`:: Enables use of the Boehm Garbage Collector. The build will look for the Boehm-GC source in a ""boehm_gc"" subdirectory from the `b2` sources. `--duma`:: Enables use of the DUMA (Detect Unintended Memory Access) debugging memory allocator. The build expects to find the DUMA source files in a ""duma"" subdirectory from the `b2` sources. `--toolset-root=path`:: Indicates where the toolset used to build is located. This option is passed in by the bootstrap (`build.bat` or `build.sh`) script. `--show-locate-target`:: For information, prints out where it will put the built executable. `--noassert`:: Disable debug assertions, even if building the debug version of the executable. `dist`:: Generate packages (compressed archives) as appropriate for distribution in the platform, if possible. `clean`:: Remove all the built executables and objects. [[jam.language]] == Language `B2` has an interpreted, procedural language. Statements in `b2` are rule (procedure) definitions, rule invocations, flow-of-control structures, variable assignments, and sundry language support. [[jam.language.lexical]] === Lexical Features `B2` treats its input files as whitespace-separated tokens, with two exceptions: double quotes ("") can enclose whitespace to embed it into a token, and everything between the matching curly braces (\\{}) in the definition of a rule action is treated as a single string. A backslash (\\) can escape a double quote, or any single whitespace character. `B2` requires whitespace (blanks, tabs, or newlines) to surround all tokens, including the colon (:) and semicolon (;) tokens. `B2` keywords (an mentioned in this document) are reserved and generally must be quoted with double quotes ("") to be used as arbitrary tokens, such as variable or target names. Comments start with the `\\#` character and extend until the end of line. And block comments start with `#|` and extend until the next `|#`. [[jam.language.target]] === Targets The essential `b2` data entity is a target. Build targets are files to be updated. Source targets are the files used in updating built targets. Built targets and source targets are collectively referred to as file targets, and frequently built targets are source targets for other built targets. Pseudo-targets are symbols representing dependencies on other targets, but which are not themselves associated with any real file. A file target's identifier is generally the file's name, which can be absolutely rooted, relative to the directory of `b2`s invocation, or simply local (no directory). Most often it is the last case, and the actual file path is bound using the `$(SEARCH)` and `$(LOCATE)` special variables. See link:#jam.language.variables.builtins.search[SEARCH and LOCATE Variables] below. A local filename is optionally qualified with grist, a string value used to assure uniqueness. A file target with an identifier of the form _file(member)_ is a library member (usually an `ar`(1) archive on Unix). [[jam.language.target.binding_detection]] ==== Binding Detection Whenever a target is bound to a location in the filesystem, Boost Jam will look for a variable called `BINDRULE` (first ""on"" the target being bound, then in the global module). If non-empty, `$(BINDRULE[1])` names a rule which is called with the name of the target and the path it is being bound to. The signature of the rule named by `$(BINDRULE[1])` should match the following: [source] ---- rule bind-rule ( target : path ) ---- This facility is useful for correct header file scanning, since many compilers will search for `#include` files first in the directory containing the file doing the `#include` directive. `$(BINDRULE)` can be used to make a record of that directory. [[jam.language.rules]] === Rules The basic `b2` language entity is called a rule. A rule is defined in two parts: the procedure and the actions. The procedure is a body of jam statements to be run when the rule is invoked; the actions are the OS shell commands to execute when updating the built targets of the rule. Rules can return values, which can be expanded into a list with ""[ _rule_ _args_ ... ]"". A rule's value is the value of its last statement, though only the following statements have values: 'if' (value of the leg chosen), 'switch' (value of the case chosen), set (value of the resulting variable), and 'return' (value of its arguments). The `b2` statements for defining and invoking rules are as follows: Define a rule's procedure, replacing any previous definition. [source] ---- rule rulename { statements } ---- Define a rule's updating actions, replacing any previous definition. [source] ---- actions [ modifiers ] rulename { commands } ---- Invoke a rule. [source] ---- rulename field1 : field2 : ... : fieldN ; ---- Invoke a rule under the influence of target's specific variables.. [source] ---- on target rulename field1 : field2 : ... : fieldN ; ---- Used as an argument, expands to the return value of the rule invoked. [source] ---- [ rulename field1 : field2 : ... : fieldN ] [ on target rulename field1 : field2 : ... : fieldN ] ---- A rule is invoked with values in _field1_ through _fieldN_. They may be referenced in the procedure's statements as `$(1)` through `$(N)` (9 max), and the first two only may be referenced in the action's _commands_ as `$(1)` and `$(2)`. `$(<)` and `$(>)` are synonymous with `$(1)` and `$(2)`. Rules fall into two categories: updating rules (with actions), and pure procedure rules (without actions). Updating rules treat arguments `$(1)` and `$(2)` as built targets and sources, respectively, while pure procedure rules can take arbitrary arguments. When an updating rule is invoked, its updating actions are added to those associated with its built targets (`$(1)`) before the rule's procedure is run. Later, to build the targets in the updating phase, _commands_ are passed to the OS command shell, with `$(1)` and `$(2)` replaced by bound versions of the target names. See Binding above. Rule invocation may be indirected through a variable: [source] ---- $(var) field1 : field2 : ... : fieldN ; on target $(var) field1 : field2 : ... : fieldN ; [ $(var) field1 : field2 : ... : fieldN ] [ on target $(var) field1 : field2 : ... : fieldN ] ---- The variable's value names the rule (or rules) to be invoked. A rule is invoked for each element in the list of `$(var)`s values. The fields `field1 : field2 : ...` are passed as arguments for each invocation For the [ ... ] forms, the return value is the concatenation of the return values for all of the invocations. [[jam.language.rules.action_modifiers]] ==== Action Modifiers The following action modifiers are understood: `actions bind vars`:: `$(vars)` will be replaced with bound values. `actions existing`:: `$(>)` includes only source targets currently existing. `actions ignore`:: The return status of the commands is ignored. `actions piecemeal`:: commands are repeatedly invoked with a subset of `$(>)` small enough to fit in the command buffer on this OS. `actions quietly`:: The action is not echoed to the standard output. `actions together`:: The `$(>)` from multiple invocations of the same action on the same built target are glommed together. `actions updated`:: `$(>)` includes only source targets themselves marked for updating. [[jam.language.rules.argument_lists]] ==== Argument lists You can describe the arguments accepted by a rule, and refer to them by name within the rule. For example, the following prints ""I'm sorry, Dave"" to the console: [source] ---- rule report ( pronoun index ? : state : names + ) { local he.suffix she.suffix it.suffix = s ; local I.suffix = m ; local they.suffix you.suffix = re ; ECHO $(pronoun)'$($(pronoun).suffix) $(state), $(names[$(index)]) ; } report I 2 : sorry : Joe Dave Pete ; ---- Each name in a list of formal arguments (separated by `:` in the rule declaration) is bound to a single element of the corresponding actual argument unless followed by one of these modifiers: [%autowidth] [cols="","",options=""header"",] |=== |Symbol |Semantics of preceding symbol |`?` |optional |`*` |Bind to zero or more unbound elements of the actual argument. When `*` appears where an argument name is expected, any number of additional arguments are accepted. This feature can be used to implement ""varargs"" rules. |`+` |Bind to one or more unbound elements of the actual argument. |=== The actual and formal arguments are checked for inconsistencies, which cause `b2` to exit with an error code: [source] ---- ### argument error # rule report ( pronoun index ? : state : names + ) # called with: ( I 2 foo : sorry : Joe Dave Pete ) # extra argument foo ### argument error # rule report ( pronoun index ? : state : names + ) # called with: ( I 2 : sorry ) # missing argument names ---- If you omit the list of formal arguments, all checking is bypassed as in ""classic"" Jam. Argument lists drastically improve the reliability and readability of your rules, however, and are *strongly recommended* for any new Jam code you write. [[jam.language.rules.builtins]] === Built-in Rules `B2` has a growing set of built-in rules, all of which are pure procedure rules without updating actions. They are in three groups: the first builds the dependency graph; the second modifies it; and the third are just utility rules. [[jam.language.rules.builtins.dependency_building]] ==== Dependency Building [[jam.language.rules.builtins.dependency_building._depends__]] ===== `DEPENDS` [source] ---- rule DEPENDS ( targets1 * : targets2 * ) ---- Builds a direct dependency: makes each of _targets1_ depend on each of _targets2_. Generally, _targets1_ will be rebuilt if _targets2_ are themselves rebuilt or are newer than _targets1_. [[jam.language.rules.builtins.dependency_building._includes__]] ===== `INCLUDES` [source] ---- rule INCLUDES ( targets1 * : targets2 * ) ---- Builds a sibling dependency: makes any target that depends on any of _targets1_ also depend on each of _targets2_. This reflects the dependencies that arise when one source file includes another: the object built from the source file depends both on the original and included source file, but the two sources files don't depend on each other. For example: [source] ---- DEPENDS foo.o : foo.c ; INCLUDES foo.c : foo.h ; ---- `foo.o` depends on `foo.c` and `foo.h` in this example. [[jam.language.rules.builtins.modifying_binding]] ==== Modifying Binding The six rules `ALWAYS`, `LEAVES`, `NOCARE`, `NOTFILE`, `NOUPDATE`, and `TEMPORARY` modify the dependency graph so that `b2` treats the targets differently during its target binding phase. See Binding above. Normally, `b2` updates a target if it is missing, if its filesystem modification time is older than any of its dependencies (recursively), or if any of its dependencies are being updated. This basic behavior can be changed by invoking the following rules: [[jam.language.rules.builtins.modifying_binding._always__]] ===== `ALWAYS` [source] ---- rule ALWAYS ( targets * ) ---- Causes _targets_ to be rebuilt regardless of whether they are up-to-date (they must still be in the dependency graph). This is used for the clean and uninstall targets, as they have no dependencies and would otherwise appear never to need building. It is best applied to targets that are also `NOTFILE` targets, but it can also be used to force a real file to be updated as well. [[jam.language.rules.builtins.modifying_binding._leaves__]] ===== `LEAVES` [source] ---- rule LEAVES ( targets * ) ---- Makes each of _targets_ depend only on its leaf sources, and not on any intermediate targets. This makes it immune to its dependencies being updated, as the ""leaf"" dependencies are those without their own dependencies and without updating actions. This allows a target to be updated only if original source files change. [[jam.language.rules.builtins.modifying_binding._nocare__]] ===== `NOCARE` [source] ---- rule NOCARE ( targets * ) ---- Causes `b2` to ignore _targets_ that neither can be found nor have updating actions to build them. Normally for such targets `b2` issues a warning and then skips other targets that depend on these missing targets. The `HdrRule` in `Jambase` uses `NOCARE` on the header file names found during header file scanning, to let `b2` know that the included files may not exist. For example, if an `#include` is within an `#ifdef`, the included file may not actually be around. WARNING: For targets with build actions: if their build actions exit with a nonzero return code, dependent targets will still be built. [[jam.language.rules.builtins.modifying_binding._notfile__]] ===== `NOTFILE` [source] ---- rule NOTFILE ( targets * ) ---- Marks _targets_ as pseudo-targets and not real files. No timestamp is checked, and so the actions on such a target are only executed if the target's dependencies are updated, or if the target is also marked with `ALWAYS`. The default `b2` target `all` is a pseudo-target In `Jambase`, `NOTFILE` is used to define several addition convenient pseudo-targets [[jam.language.rules.builtins.modifying_binding._noupdate__]] ===== `NOUPDATE` [source] ---- rule NOUPDATE ( targets * ) ---- Causes the timestamps on _targets_ to be ignored. This has two effects: first, once the target has been created it will never be updated; second, manually updating target will not cause other targets to be updated. In `Jambase`, for example, this rule is applied to directories by the `MkDir` rule, because `MkDir` only cares that the target directory exists, not when it has last been updated. [[jam.language.rules.builtins.modifying_binding._temporary__]] ===== `TEMPORARY` [source] ---- rule TEMPORARY ( targets * ) ---- Marks _targets_ as temporary, allowing them to be removed after other targets that depend upon them have been updated. If a `TEMPORARY` target is missing, `b2` uses the timestamp of the target's parent. `Jambase` uses `TEMPORARY` to mark object files that are archived in a library after they are built, so that they can be deleted after they are archived. [[jam.language.rules.builtins.modifying_binding._fail_expected__]] ===== `FAIL_EXPECTED` [source] ---- rule FAIL_EXPECTED ( targets * ) ---- For handling targets whose build actions are expected to fail (e.g. when testing that assertions or compile-time type checking work properly), Boost Jam supplies the `FAIL_EXPECTED` rule in the same style as `NOCARE`, et. al. During target updating, the return code of the build actions for arguments to `FAIL_EXPECTED` is inverted: if it fails, building of dependent targets continues as though it succeeded. If it succeeds, dependent targets are skipped. [[jam.language.rules.builtins.modifying_binding._rmold__]] ===== `RMOLD` [source] ---- rule RMOLD ( targets * ) ---- `B2` removes any target files that may exist on disk when the rule used to build those targets fails. However, targets whose dependencies fail to build are not removed by default. The `RMOLD` rule causes its arguments to be removed if any of their dependencies fail to build. [[jam.language.rules.builtins.modifying_binding._isfile__]] ===== `ISFILE` [source] ---- rule ISFILE ( targets * ) ---- `ISFILE` marks targets as required to be files. This changes the way `b2` searches for the target such that it ignores matches for file system items that are not files, like directories. This makes it possible to avoid `#include ""exception""` matching if one happens to have a directory named exception in the header search path. WARNING: This is currently not fully implemented. [[jam.language.rules.builtins.utility]] ==== Utility The two rules `ECHO` and `EXIT` are utility rules, used only in `b2`s parsing phase. [[jam.language.rules.builtins.utility._echo__]] ===== `ECHO` [source] ---- rule ECHO ( args * ) ---- Blurts out the message _args_ to stdout. [[jam.language.rules.builtins.utility._exit__]] ===== `EXIT` [source] ---- rule EXIT ( message * : result-value ? ) ---- Blurts out the _message_ to stdout and then exits with a failure status if no _result-value_ is given, otherwise it exits with the given _result-value_. `Echo`, `echo`, `Exit`, and `exit` are accepted as aliases for `ECHO` and `EXIT`, since it is hard to tell that these are built-in rules and not part of the language, like `include`. [[jam.language.rules.builtins.utility._glob__]] ===== `GLOB` The `GLOB` rule does filename globing [source] ---- rule GLOB ( directories * : patterns * : downcase-opt ? ) ---- Using the same wildcards as for the patterns in the switch statement. It is invoked by being used as an argument to a rule invocation inside of ""[ ]"". For example: `FILES = [ GLOB dir1 dir2 : *.c *.h ]` sets `FILES` to the list of C source and header files in `dir1` and `dir2`. The resulting filenames are the full pathnames, including the directory, but the pattern is applied only to the file name without the directory. If _downcase-opt_ is supplied, filenames are converted to all-lowercase before matching against the pattern; you can use this to do case-insensitive matching using lowercase patterns. The paths returned will still have mixed case if the OS supplies them. On Windows NT and Cygwin, and OpenVMS, filenames are always down-cased before matching. [[jam.language.rules.builtins.utility._glob_archive__]] ===== `GLOB_ARCHIVE` The `GLOB_ARCHIVE` rule does name globing of object archive members. [source] ---- rule GLOB_ARCHIVE ( archives * : member-patterns * : downcase-opt ? : symbol-patterns ? ) ---- Similarly to `GLOB`, this rule is used to match names of member files in an archive (static object library). List of successfully matched members is returned or null otherwise. The resulting member names are qualified with pathname of the containing archive in the form `archive-path(member-name)`. Member patterns are for matching member name only; when no wildcards specified -- an exact match is assumed. Member names generally correspond to object file names and as such are platform-specific -- use of platform-defined object suffix in the matching patterns can allow for portability. If _downcase-opt_ is supplied, the member names are converted to all-lowercase before matching against the pattern; you can use this to do case-insensitive matching using lowercase patterns. The paths returned will still have mixed case if the OS supplies them. On Windows NT, Cygwin, and OpenVMS, filenames are always down-cased before matching. Additionally, members can be matched with symbol/function patterns on supported platforms (currently, OpenVMS only). In this case, members containing the matching symbols are returned. Member and symbol patterns are applied as OR conditions, with member patterns taking precedence. On unsupported platforms, null is returned when any symbol patterns are specified. [[jam.language.rules.builtins.utility._match__]] ===== `MATCH` The `MATCH` rule does pattern matching. [source] ---- rule MATCH ( regexps + : list * ) ---- Matches the `egrep`(1) style regular expressions _regexps_ against the strings in _list_. The result is a list of matching `()` subexpressions for each string in _list_, and for each regular expression in _regexps_. [[jam.language.rules.builtins.utility._backtrace__]] ===== `BACKTRACE` [source] ---- rule BACKTRACE ( ) ---- Returns a list of quadruples: _filename_ _line_ _module_ _rulename_..., describing each shallower level of the call stack. This rule can be used to generate useful diagnostic messages from Jam rules. [[jam.language.rules.builtins.utility._update__]] ===== `UPDATE` [source] ---- rule UPDATE ( targets * ) ---- Classic jam treats any non-option element of command line as a name of target to be updated. This prevented more sophisticated handling of command line. This is now enabled again but with additional changes to the `UPDATE` rule to allow for the flexibility of changing the list of targets to update. The UPDATE rule has two effects: 1. It clears the list of targets to update, and 2. Causes the specified targets to be updated. If no target was specified with the `UPDATE` rule, no targets will be updated. To support changing of the update list in more useful ways, the rule also returns the targets previously in the update list. This makes it possible to add targets as such: [source] ---- local previous-updates = [ UPDATE ] ; UPDATE $(previous-updates) a-new-target ; ---- [[jam.language.rules.builtins.utility._w32_getreg__]] ===== `W32_GETREG` [source] ---- rule W32_GETREG ( path : data ? ) ---- Defined only for win32 platform. It reads the registry of Windows. '_path_' is the location of the information, and '_data_' is the name of the value which we want to get. If '_data_' is omitted, the default value of '_path_' will be returned. The '_path_' value must conform to MS key path format and must be prefixed with one of the predefined root keys. As usual, * `HKLM` is equivalent to `HKEY_LOCAL_MACHINE`. * `HKCU` is equivalent to `HKEY_CURRENT_USER`. * `HKCR` is equivalent to `HKEY_CLASSES_ROOT`. Other predefined root keys are not supported. Currently supported data types : `REG_DWORD`, `REG_SZ`, `REG_EXPAND_SZ`, `REG_MULTI_SZ`. The data with `REG_DWORD` type will be turned into a string, `REG_MULTI_SZ` into a list of strings, and for those with `REG_EXPAND_SZ` type environment variables in it will be replaced with their defined values. The data with `REG_SZ` type and other unsupported types will be put into a string without modification. If it can't receive the value of the data, it just return an empty list. For example, [source] ---- local PSDK-location = [ W32_GETREG HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\Microsoft\\\\MicrosoftSDK\\\\Directories : ""Install Dir"" ] ; ---- [[jam.language.rules.builtins.utility._w32_getregnames__]] ===== `W32_GETREGNAMES` [source] ---- rule W32_GETREGNAMES ( path : result-type ) ---- Defined only for win32 platform. It reads the registry of Windows. '_path_' is the location of the information, and '_result-type_' is either `subkeys` or `values`. For more information on '_path_' format and constraints, please see `W32_GETREG`. Depending on '_result-type_', the rule returns one of the following: `subkeys`:: Names of all direct sub-keys of '_path_'. `values`:: Names of values contained in registry key given by '_path_'. The ""default"" value of the key appears in the returned list only if its value has been set in the registry. If '_result-type_' is not recognized, or requested data cannot be retrieved, the rule returns an empty list. Example: [source] ---- local key = ""HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\App Paths"" ; local subkeys = [ W32_GETREGNAMES ""$(key)"" : subkeys ] ; for local subkey in $(subkeys) { local values = [ W32_GETREGNAMES ""$(key)\\\\$(subkey)"" : values ] ; for local value in $(values) { local data = [ W32_GETREG ""$(key)\\\\$(subkey)"" : ""$(value)"" ] ; ECHO ""Registry path: "" $(key)\\\\$(subkey) "":"" $(value) ""="" $(data) ; } } ---- [[jam.language.rules.builtins.utility._shell__]] ===== `SHELL` [source] ---- rule SHELL ( command : * ) ---- `SHELL` executes _command_, and then returns the standard output of _command_. `SHELL` only works on platforms with a `popen()` function in the C library. On platforms without a working `popen()` function, `SHELL` is implemented as a no-op. `SHELL` works on Unix, MacOS X, and most Windows compilers. `SHELL` is a no-op on Metrowerks compilers under Windows. There is a variable set of allowed options as additional arguments: `exit-status`:: In addition to the output the result status of the executed command is returned as a second element of the result. `no-output`:: Don't capture the output of the command. Instead an empty ("""") string value is returned in place of the output. `strip-eol`:: Remove trailing end-of-line character from output, if any. Because the Perforce/Jambase defines a `SHELL` rule which hides the builtin rule, `COMMAND` can be used as an alias for `SHELL` in such a case. [[jam.language.rules.builtins.utility._md5__]] ===== `MD5` [source] ---- rule MD5 ( string ) ---- `MD5` computes the MD5 hash of the string passed as parameter and returns it. [[jam.language.rules.builtins.utility._split_by_characters__]] ===== `SPLIT_BY_CHARACTERS` [source] ---- rule SPLIT_BY_CHARACTERS ( string : delimiters ) ---- `SPLIT_BY_CHARACTERS` splits the specified _string_ on any delimiter character present in _delimiters_ and returns the resulting list. [[jam.language.rules.builtins.utility._precious__]] ===== `PRECIOUS` [source] ---- rule PRECIOUS ( targets * ) ---- The `PRECIOUS` rule specifies that each of the targets passed as the arguments should not be removed even if the command updating that target fails. [[jam.language.rules.builtins.utility._pad__]] ===== `PAD` [source] ---- rule PAD ( string : width ) ---- If _string_ is shorter than _width_ characters, pads it with whitespace characters on the right, and returns the result. Otherwise, returns _string_ unmodified. [[jam.language.rules.builtins.utility._file_open__]] ===== `FILE_OPEN` [source] ---- rule FILE_OPEN ( filename : mode ) ---- The `FILE_OPEN` rule opens the specified file and returns a file descriptor. The _mode_ parameter can be either ""w"" or ""r"". Note that at present, only the `UPDATE_NOW` rule can use the resulting file descriptor number. [[jam.language.rules.builtins.utility._update_now__]] ===== `UPDATE_NOW` [source] ---- rule UPDATE_NOW ( targets * : log ? : ignore-minus-n ? ) ---- The `UPDATE_NOW` caused the specified targets to be updated immediately. If update was successful, non-empty string is returned. The _log_ parameter, if present, specifies a descriptor of a file where all output from building is redirected. If the _ignore-minus-n_ parameter is specified, the targets are updated even if the `-n` parameter is specified on the command line. [[jam.language.flow_of_control]] === Flow-of-Control `B2` has several simple flow-of-control statements: [source] ---- for var in list { statements } ---- Executes _statements_ for each element in _list_, setting the variable _var_ to the element value. [source] ---- if cond { statements } [ else { statements } ] ---- Does the obvious; the `else` clause is optional. _cond_ is built of: `a`:: true if any _a_ element is a non-zero-length string `a = b`:: list _a_ matches list _b_ string-for-string `a != b`:: list _a_ does not match list _b_ `a < b`:: _a[i]_ string is less than _b[i]_ string, where _i_ is first mismatched element in lists _a_ and _b_ `+a <= b+`:: every _a_ string is less than or equal to its _b_ counterpart `a > b`:: _a[i]_ string is greater than _b[i]_ string, where _i_ is first mismatched element `a >= b`:: every _a_ string is greater than or equal to its _b_ counterpart `a in b`:: true if all elements of _a_ can be found in _b_, or if _a_ has no elements `! cond`:: condition not true `cond && cond`:: conjunction `cond || cond`:: disjunction `( cond )`:: precedence grouping [source] ---- include file ; ---- Causes `b2` to read the named _file_. The _file_ is bound like a regular target (see Binding above) but unlike a regular target the include _file_ cannot be built. The include _file_ is inserted into the input stream during the parsing phase. The primary input file and all the included file(s) are treated as a single file; that is, `b2` infers no scope boundaries from included files. [source] ---- local vars [ = values ] ; ---- Creates new _vars_ inside to the enclosing `{}` block, obscuring any previous values they might have. The previous values for vars are restored when the current block ends. Any rule called or file included will see the local and not the previous value (this is sometimes called Dynamic Scoping). The local statement may appear anywhere, even outside of a block (in which case the previous value is restored when the input ends). The _vars_ are initialized to _values_ if present, or left uninitialized otherwise. [source] ---- return values ; ---- Within a rule body, the return statement sets the return value for an invocation of the rule and returns to the caller. [source] ---- switch value { case pattern1 : statements ; case pattern2 : statements ; ... } ---- The switch statement executes zero or one of the enclosed _statements_, depending on which, if any, is the first case whose _pattern_ matches _value_. The _pattern_ values are not variable-expanded. The pattern values may include the following wildcards: `?`:: match any single character `*`:: match zero or more characters `[chars]`:: match any single character in _chars_ `[^chars]`:: match any single character not in _chars_ `\\x`:: match _x_ (escapes the other wildcards) [source] ---- while cond { statements } ---- Repeatedly execute _statements_ while _cond_ remains true upon entry. (See the description of _cond_ expression syntax under if, above). [source] ---- break ; ---- Immediately exits the nearest enclosing while or for loop. [source] ---- continue ; ---- Jumps to the top of the nearest enclosing while or for loop. [[jam.language.variables]] === Variables `B2` variables are lists of zero or more elements, with each element being a string value. An undefined variable is indistinguishable from a variable with an empty list, however, a defined variable may have one more elements which are null strings. All variables are referenced as `$(variable)`. Variables are either global or target-specific. In the latter case, the variable takes on the given value only during the updating of the specific target. A variable is defined with: [source] ---- variable = elements ; variable += elements ; variable on targets = elements ; variable on targets += elements ; variable default = elements ; variable ?= elements ; ---- The first two forms set _variable_ globally. The third and forth forms set a target-specific variable. The `=` operator replaces any previous elements of _variable_ with _elements_; the `+=` operation adds _elements_ to _variable_'s list of elements. The final two forms are synonymous: they set _variable_ globally, but only if it was previously unset. Variables referenced in updating commands will be replaced with their values; target-specific values take precedence over global values. Variables passed as arguments (`$(1)` and `$(2)`) to actions are replaced with their bound values; the `bind` modifier can be used on actions to cause other variables to be replaced with bound values. See Action Modifiers above. `B2` variables are not re-exported to the environment of the shell that executes the updating actions, but the updating actions can reference `b2` variables with `$(variable)`. [[jam.language.variables.expansion]] ==== Variable Expansion During parsing, `b2` performs variable expansion on each token that is not a keyword or rule name. Such tokens with embedded variable references are replaced with zero or more tokens. Variable references are of the form `$(v)` or `$(vm)`, where _v_ is the variable name, and _m_ are optional modifiers. Variable expansion in a rule's actions is similar to variable expansion in statements, except that the action string is tokenized at whitespace regardless of quoting. The result of a token after variable expansion is the _product_ of the components of the token, where each component is a literal substring or a list substituting a variable reference. For example: ---- $(X) -> a b c t$(X) -> ta tb tc $(X)z -> az bz cz $(X)-$(X) -> a-a a-b a-c b-a b-b b-c c-a c-b c-c ---- The variable name and modifiers can themselves contain a variable reference, and this partakes of the product as well: ---- $(X) -> a b c $(Y) -> 1 2 $(Z) -> X Y $($(Z)) -> a b c 1 2 ---- Because of this product expansion, if any variable reference in a token is undefined, the result of the expansion is an empty list. If any variable element is a null string, the result propagates the non-null elements: ---- $(X) -> a """" $(Y) -> """" 1 $(Z) -> -$(X)$(Y)- -> -a- -a1- -- -1- -$(X)$(Z)- -> ---- A variable element's string value can be parsed into grist and filename-related components. Modifiers to a variable are used to select elements, select components, and replace components. The modifiers are: `[n]`:: + Select element number _n_ (starting at 1). If the variable contains fewer than _n_ elements, the result is a zero-element list. _n_ can be negative in which case the element number _n_ from the last leftward is returned. `[n-m]`:: + Select elements number _n_ through _m_. _n_ and _m_ can be negative in which case they refer to elements counting from the last leftward. `[n-]`:: + Select elements number _n_ through the last. _n_ can be negative in which case it refers to the element counting from the last leftward. `:B`:: + Select filename base -- a basename without extension. `:S`:: + Select file extension -- a (last) filename suffix. `:M`:: + Select archive member name. `:D`:: + Select directory path. `:P`:: + Select parent directory. `:G`:: + Select grist. `:U`:: + Replace lowercase characters with uppercase. `:L`:: + Replace uppercase characters with lowercase. `:T`:: + Converts all back-slashes (""\\"") to forward slashes (""/""). For example + ---- x = ""C:\\\\Program Files\\\\Borland"" ; ECHO $(x:T) ; ---- + prints `C:/Program Files/Borland` `:W`:: + When invoking Windows-based tools from http://www.cygwin.com/[Cygwin] it can be important to pass them true windows-style paths. The `:W` modifier, *under Cygwin only*, turns a cygwin path into a Win32 path using the http://www.cygwin.com/cygwin-api/func-cygwin-conv-to-win32-path.html[`cygwin_conv_to_win32_path`] function. For example + ---- x = ""/cygdrive/c/Program Files/Borland"" ; ECHO $(x:W) ; ---- + prints `C:\\Program Files\\Borland` on Cygwin + Similarly, when used on OpenVMS, the `:W` modifier translates a POSIX-style path into native VMS-style format using `decc$to_vms` CRTL function. This modifier is generally used inside action blocks to properly specify file paths in VMS-specific commands. For example + ---- x = ""subdir/filename.c"" ; ECHO $(x:W) ; ---- + prints `[.subdir]filename.c` on OpenVMS + On other platforms, the string is unchanged. `:chars`:: Select the components listed in _chars_. + For example, `:BS` selects filename (basename and extension). `:G=grist`:: Replace grist with _grist_. `:D=path`:: Replace directory with _path_. `:B=base`:: Replace the base part of file name with _base_. `:S=suf`:: Replace the suffix of file name with _suf_. `:M=mem`:: Replace the archive member name with _mem_. `:R=root`:: Prepend _root_ to the whole file name, if not already rooted. `:E=value`:: Assign _value_ to the variable if it is unset. `:J=joinval`:: Concatenate list elements into single element, separated by _joinval_. On VMS, `$(var:P)` is the parent directory of `$(var:D)`. [[jam.language.variables.local_for_loop_variables]] ==== Local For Loop Variables Boost Jam allows you to declare a local for loop control variable right in the loop: [source] ---- x = 1 2 3 ; y = 4 5 6 ; for local y in $(x) { ECHO $(y) ; # prints ""1"", ""2"", or ""3"" } ECHO $(y) ; # prints ""4 5 6"" ---- [[jam.language.variables.atfile]] ==== Generated File Expansion During expansion of expressions `b2` also looks for subexpressions of the form `@(filename:E=filecontents)` and replaces the expression with `filename` after creating the given file with the contents set to `filecontents`. This is useful for creating compiler response files, and other ""internal"" files. The expansion works both during parsing and action execution. Hence it is possible to create files during any of the three build phases. [[jam.language.variables.builtins]] ==== Built-in Variables This section discusses variables that have special meaning to `b2`. All of these must be defined or used in the global module -- using those variables inside a named module will not have the desired effect. See link:#jam.language.modules[Modules]. [[jam.language.variables.builtins.search]] ===== SEARCH and LOCATE These two variables control the binding of file target names to locations in the file system. Generally, `$(SEARCH)` is used to find existing sources while `$(LOCATE)` is used to fix the location for built targets. Rooted (absolute path) file targets are bound as is. Unrooted file target names are also normally bound as is, and thus relative to the current directory, but the settings of `$(LOCATE)` and `$(SEARCH)` alter this: * If `$(LOCATE)` is set then the target is bound relative to the first directory in `$(LOCATE)`. Only the first element is used for binding. * If `$(SEARCH)` is set then the target is bound to the first directory in `$(SEARCH)` where the target file already exists. * If the `$(SEARCH)` search fails, the target is bound relative to the current directory anyhow. Both `$(SEARCH)` and `$(LOCATE)` should be set target-specific and not globally. If they were set globally, `b2` would use the same paths for all file binding, which is not likely to produce sane results. When writing your own rules, especially ones not built upon those in Jambase, you may need to set `$(SEARCH)` or `$(LOCATE)` directly. Almost all of the rules defined in Jambase set `$(SEARCH)` and `$(LOCATE)` to sensible values for sources they are looking for and targets they create, respectively. [[jam.language.variables.builtins.hdrscan]] ===== HDRSCAN and HDRRULE These two variables control header file scanning. `$(HDRSCAN)` is an `egrep(1)` pattern, with ()'s surrounding the file name, used to find file inclusion statements in source files. `Jambase` uses `$(HDRPATTERN)` as the pattern for `$(HDRSCAN)`. `$(HDRRULE)` is the name of a rule to invoke with the results of the scan: the scanned file is the target, the found files are the sources. This is the only place where `b2` invokes a rule through a variable setting. Both `$(HDRSCAN)` and `$(HDRRULE)` must be set for header file scanning to take place, and they should be set target-specific and not globally. If they were set globally, all files, including executables and libraries, would be scanned for header file include statements. The scanning for header file inclusions is not exact, but it is at least dynamic, so there is no need to run something like `makedepend(GNU)` to create a static dependency file. The scanning mechanism errs on the side of inclusion (i.e., it is more likely to return filenames that are not actually used by the compiler than to miss include files) because it can't tell if `#include` lines are inside `#ifdefs` or other conditional logic. In `Jambase`, `HdrRule` applies the `NOCARE` rule to each header file found during scanning so that if the file isn't present yet doesn't cause the compilation to fail, `b2` won't care. Also, scanning for regular expressions only works where the included file name is literally in the source file. It can't handle languages that allow including files using variable names (as the `Jam` language itself does). [[jam.language.variables.builtins.semaphores]] ===== Semaphores It is sometimes desirable to disallow parallel execution of some actions. For example: * Old versions of yacc use files with fixed names. So, running two yacc actions is dangerous. * One might want to perform parallel compiling, but not do parallel linking, because linking is i/o bound and only gets slower. Craig McPeeters has extended Perforce Jam to solve such problems, and that extension was integrated in Boost.Jam. Any target can be assigned a _semaphore_, by setting a variable called `SEMAPHORE` on that target. The value of the variable is the semaphore name. It must be different from names of any declared target, but is arbitrary otherwise. The semantic of semaphores is that in a group of targets which have the same semaphore, only one can be updated at the moment, regardless of `-j` option. [[jam.language.variables.builtins.platform_identifier]] ===== Platform Identifier A number of Jam built-in variables can be used to identify runtime platform: `OS`:: OS identifier string `OSPLAT`:: Underlying architecture, when applicable `MAC`:: true on MAC platform `NT`:: true on NT platform `OS2`:: true on OS2 platform `UNIX`:: true on Unix platforms `VMS`:: true on VMS platform [[jam.language.variables.builtins.jam_version]] ==== Jam Version `JAMDATE`:: Time and date at `b2` start-up as an ISO-8601 UTC value. `JAMUNAME`:: Output of uname(1) command (Unix only) `JAMVERSION`:: `b2` version, as a sematic triplet ""X.Y.Z"". `JAM_VERSION`:: A predefined global variable with two elements indicates the version number of Boost Jam. Boost Jam versions start at `03` `00`. Earlier versions of `Jam` do not automatically define `JAM_VERSION`. [[jam.language.variables.builtins.jamshell]] ===== JAMSHELL When `b2` executes a rule's action block, it forks and execs a shell, passing the action block as an argument to the shell. The invocation of the shell can be controlled by `$(JAMSHELL)`. The default on Unix is, for example: [source] ---- JAMSHELL = /bin/sh -c % ; ---- The `%` is replaced with the text of the action block. `B2` does not directly support building in parallel across multiple hosts, since that is heavily dependent on the local environment. To build in parallel across multiple hosts, you need to write your own shell that provides access to the multiple hosts. You then reset `$(JAMSHELL)` to reference it. Just as `b2` expands a `%` to be the text of the rule's action block, it expands a `!` to be the multi-process slot number. The slot number varies between 1 and the number of concurrent jobs permitted by the `-j` flag given on the command line. Armed with this, it is possible to write a multiple host shell. For example: [source,bash] ---- #!/bin/sh # This sample JAMSHELL uses the SunOS on(1) command to execute a # command string with an identical environment on another host. # Set JAMSHELL = jamshell ! % # # where jamshell is the name of this shell file. # # This version handles up to -j6; after that they get executed # locally. case $1 in 1|4) on winken sh -c ""$2"";; 2|5) on blinken sh -c ""$2"";; 3|6) on nod sh -c ""$2"";; *) eval ""$2"";; esac ---- [[jam.language.variables.builtins.actionrule]] ===== `+__TIMING_RULE__+` and `+__ACTION_RULE__+` The `+__TIMING_RULE__+` and `+__ACTION_RULE__+` can be set to the name of a rule for `b2` to call *after* an action completes for a target. They both give diagnostic information about the action that completed. For `+__TIMING_RULE__+` the rule is called as: [source] ---- rule timing-rule ( args * : target : start end user system ) ---- And `+__ACTION_RULE__+` is called as: [source] ---- rule action-rule ( args * : target : command status start end user system : output ? ) ---- The arguments for both are: `args`:: Any values following the rule name in the `+__TIMING_RULE__+` or `+__ACTION_RULE__+` are passed along here. `target`:: The `b2` target that was built. `command`:: The text of the executed command in the action body. `status`:: The integer result of the executed command. `start`:: The starting timestamp of the executed command as a ISO-8601 UTC value. `end`:: The completion timestamp of the executed command as a ISO-8601 UTC value. `user`:: The number of user CPU seconds the executed command spent as a floating point value. `system`:: The number of system CPU seconds the executed command spent as a floating point value. `output`:: The output of the command as a single string. The content of the output reflects the use of the `-pX` option. NOTE: If both variables are set for a target both are called, first `+__TIMING_RULE__+` then `+__ACTION_RULE__+`. [[jam.language.modules]] === Modules Boost Jam introduces support for modules, which provide some rudimentary namespace protection for rules and variables. A new keyword, `module` was also introduced. The features described in this section are primitives, meaning that they are meant to provide the operations needed to write Jam rules which provide a more elegant module interface. [[jam.language.modules.declaration]] ==== Declaration [source] ---- module expression { ... } ---- Code within the `{ ... }` executes within the module named by evaluating expression. Rule definitions can be found in the module's own namespace, and in the namespace of the global module as _module-name_._rule-name_, so within a module, other rules in that module may always be invoked without qualification: [source] ---- module my_module { rule salute ( x ) { ECHO $(x), world ; } rule greet ( ) { salute hello ; } greet ; } my_module.salute goodbye ; ---- When an invoked rule is not found in the current module's namespace, it is looked up in the namespace of the global module, so qualified calls work across modules: [source] ---- module your_module { rule bedtime ( ) { my_module.salute goodnight ; } } ---- [[jam.language.modules.variable_scope]] ==== Variable Scope Each module has its own set of dynamically nested variable scopes. When execution passes from module A to module B, all the variable bindings from A become unavailable, and are replaced by the bindings that belong to B. This applies equally to local and global variables: [source] ---- module A { x = 1 ; rule f ( ) { local y = 999 ; # becomes visible again when B.f calls A.g B.f ; } rule g ( ) { ECHO $(y) ; # prints ""999"" } } module B { y = 2 ; rule f ( ) { ECHO $(y) ; # always prints ""2"" A.g ; } } ---- The only way to access another module's variables is by entering that module: [source] ---- rule peek ( module-name ? : variables + ) { module $(module-name) { return $($(>)) ; } } ---- Note that because existing variable bindings change whenever a new module scope is entered, argument bindings become unavailable. That explains the use of `$(>)` in the peek rule above. [[jam.language.modules.local_rules]] ==== Local Rules [source] ---- local rule rulename... ---- The rule is declared locally to the current module. It is not entered in the global module with qualification, and its name will not appear in the result of: [source] ---- [ RULENAMES module-name ] ---- [[jam.language.modules.the__rulenames__rule]] ==== The `RULENAMES` Rule [source] ---- rule RULENAMES ( module ? ) ---- Returns a list of the names of all non-local rules in the given module. If _module_ is omitted, the names of all non-local rules in the global module are returned. [[jam.language.modules.the__varnames__rule]] ==== The `VARNAMES` Rule [source] ---- rule VARNAMES ( module ? ) ---- Returns a list of the names of all variable bindings in the given module. If _module_ is omitted, the names of all variable bindings in the global module are returned. NOTE: This includes any local variables in rules from the call stack which have not returned at the time of the `VARNAMES` invocation. [[jam.language.modules.the__import__rule]] ==== The `IMPORT` Rule `IMPORT` allows rule name aliasing across modules: [source] ---- rule IMPORT ( source_module ? : source_rules * : target_module ? : target_rules * ) ---- The `IMPORT` rule copies rules from the _source_module_ into the _target_module_ as local rules. If either _source_module_ or _target_module_ is not supplied, it refers to the global module. _source_rules_ specifies which rules from the _source_module_ to import; _target_rules_ specifies the names to give those rules in _target_module_. If _source_rules_ contains a name which doesn't correspond to a rule in _source_module_, or if it contains a different number of items than _target_rules_, an error is issued. For example, [source] ---- # import m1.rule1 into m2 as local rule m1-rule1. IMPORT m1 : rule1 : m2 : m1-rule1 ; # import all non-local rules from m1 into m2 IMPORT m1 : [ RULENAMES m1 ] : m2 : [ RULENAMES m1 ] ; ---- [[jam.language.modules.the__export__rule]] ==== The `EXPORT` Rule `EXPORT` allows rule name aliasing across modules: [source] ---- rule EXPORT ( module ? : rules * ) ---- The `EXPORT` rule marks _rules_ from the `source_module` as non-local (and thus exportable). If an element of _rules_ does not name a rule in _module_, an error is issued. For example, [source] ---- module X { local rule r { ECHO X.r ; } } IMPORT X : r : : r ; # error - r is local in X EXPORT X : r ; IMPORT X : r : : r ; # OK. ---- [[jam.language.modules.the__caller_module__rule]] ==== The `CALLER_MODULE` Rule [source] ---- rule CALLER_MODULE ( levels ? ) ---- `CALLER_MODULE` returns the name of the module scope enclosing the call to its caller (if levels is supplied, it is interpreted as an integer number of additional levels of call stack to traverse to locate the module). If the scope belongs to the global module, or if no such module exists, returns the empty list. For example, the following prints ""\\{Y} \\{X}"": [source] ---- module X { rule get-caller { return [ CALLER_MODULE ] ; } rule get-caller's-caller { return [ CALLER_MODULE 1 ] ; } rule call-Y { return Y.call-X2 ; } } module Y { rule call-X { return X.get-caller ; } rule call-X2 { return X.get-caller's-caller ; } } callers = [ X.get-caller ] [ Y.call-X ] [ X.call-Y ] ; ECHO {$(callers)} ; ---- [[jam.language.modules.the__delete_module__rule]] ==== The `DELETE_MODULE` Rule [source] ---- rule DELETE_MODULE ( module ? ) ---- `DELETE_MODULE` removes all of the variable bindings and otherwise-unreferenced rules from the given module (or the global module, if no module is supplied), and returns their memory to the system. NOTE: Though it won't affect rules that are currently executing until they complete, `DELETE_MODULE` should be used with extreme care because it will wipe out any others and all variable (including locals in that module) immediately. Because of the way dynamic binding works, variables which are shadowed by locals will not be destroyed, so the results can be really unpredictable. [[jam.miscellaneous]] == Miscellaneous [[jam.miscellaneous.diagnostics]] === Diagnostics In addition to generic error messages, `b2` may emit one of the following: ---- warning: unknown rule X ---- A rule was invoked that has not been defined with an `actions` or `rule` statement. ---- using N temp target(s) ---- Targets marked as being temporary (but nonetheless present) have been found. ---- updating N target(s) ---- Targets are out-of-date and will be updated. ---- can't find N target(s) ---- Source files can't be found and there are no actions to create them. ---- can't make N target(s) ---- Due to sources not being found, other targets cannot be made. ---- warning: X depends on itself ---- A target depends on itself either directly or through its sources. ---- don't know how to make X ---- A target is not present and no actions have been defined to create it. ---- X skipped for lack of Y ---- A source failed to build, and thus a target cannot be built. ---- warning: using independent target X ---- A target that is not a dependency of any other target is being referenced with `$(<)` or `$(>)`. ---- X removed ---- `B2` removed a partially built target after being interrupted. [[jam.miscellaneous.bugs__limitations]] === Bugs, Limitations For parallel building to be successful, the dependencies among files must be properly spelled out, as targets tend to get built in a quickest-first ordering. Also, beware of un-parallelizable commands that drop fixed-named files into the current directory, like `yacc(1)` does. A poorly set `$(JAMSHELL)` is likely to result in silent failure. [[jam.miscellaneous.fundamentals]] === Fundamentals This section is derived from the official Jam documentation and from experience using it and reading the Jambase rules. We repeat the information here mostly because it is essential to understanding and using Jam, but is not consolidated in a single place. Some of it is missing from the official documentation altogether. We hope it will be useful to anyone wishing to become familiar with Jam and the Boost build system. * Jam `rules` are actually simple procedural entities. Think of them as functions. Arguments are separated by colons. * A Jam *target* is an abstract entity identified by an arbitrary string. The built-in `DEPENDS` rule creates a link in the dependency graph between the named targets. * Note that the original Jam documentation for the built-in `INCLUDES` rule is incorrect: `INCLUDES targets1 : targets2` causes everything that depends on a member of _targets1_ to depend on all members of _targets2_. It does this in an odd way, by tacking _targets2_ onto a special tail section in the dependency list of everything in _targets1_. It seems to be OK to create circular dependencies this way; in fact, it appears to be the ""right thing to do"" when a single build action produces both _targets1_ and _targets2_. * When a rule is invoked, if there are `actions` declared with the same name as the rule, the actions are added to the updating actions for the target identified by the rule's first argument. It is actually possible to invoke an undeclared rule if corresponding actions are declared: the rule is treated as empty. * Targets (other than `NOTFILE` targets) are associated with paths in the file system through a process called binding. Binding is a process of searching for a file with the same name as the target (sans grist), based on the settings of the target-specific `SEARCH` and `LOCATE` variables. * In addition to local and global variables, jam allows you to set a variable `on` a target. Target-specific variable values can usually not be read, and take effect only in the following contexts: ** In updating actions, variable values are first looked up `on` the target named by the first argument (the target being updated). Because Jam builds its entire dependency tree before executing actions, Jam rules make target-specific variable settings as a way of supplying parameters to the corresponding actions. ** Binding is controlled _entirely_ by the target-specific setting of the `SEARCH` and `LOCATE` variables, as described here. ** In the special rule used for header file scanning, variable values are first looked up `on` the target named by the rule's first argument (the source file being scanned). * The ""bound value"" of a variable is the path associated with the target named by the variable. In build actions, the first two arguments are automatically replaced with their bound values. Target-specific variables can be selectively replaced by their bound values using the `bind` action modifier. * Note that the term ""binding"" as used in the Jam documentation indicates a phase of processing that includes three sub-phases: _binding_ (yes!), update determination, and header file scanning. The repetition of the term ""binding"" can lead to some confusion. In particular, the Modifying Binding section in the Jam documentation should probably be titled ""Modifying Update Determination"". * ""Grist"" is just a string prefix of the form <__characters__>. It is used in Jam to create unique target names based on simpler names. For example, the file name `test.exe` may be used by targets in separate sub-projects, or for the debug and release variants of the ""same"" abstract target. Each distinct target bound to a file called ""test.exe"" has its own unique grist prefix. The Boost build system also takes full advantage of Jam's ability to divide strings on grist boundaries, sometimes concatenating multiple gristed elements at the beginning of a string. Grist is used instead of identifying targets with absolute paths for two reasons: 1. The location of targets cannot always be derived solely from what the user puts in a Jamfile, but sometimes depends also on the binding process. Some mechanism to distinctly identify targets with the same name is still needed. 2. Grist allows us to use a uniform abstract identifier for each built target, regardless of target file location (as allowed by setting ALL_LOCATE_TARGET). * When grist is extracted from a name with $(var:G), the result includes the leading and trailing angle brackets. When grist is added to a name with `$(var:G=expr)`, existing grist is first stripped. Then, if `expr` is non-empty, leading s are added if necessary to form an expression of the form ; is then prepended. * When Jam is invoked it imports all environment variable settings into corresponding Jam variables, followed by all command-line (-s...) variable settings. Variables whose name ends in PATH, Path, or path are split into string lists on OS-specific path-list separator boundaries (e.g. "":"" for UNIX and "";"" for Windows). All other variables are split on space ("" "") boundaries. Boost Jam modifies that behavior by allowing variables to be quoted. * A variable whose value is an empty list or which consists entirely of empty strings has a negative logical value. Thus, for example, code like the following allows a sensible non-empty default which can easily be overridden by the user: + ---- MESSAGE ?\\= starting jam... ; if $(MESSAGE) { ECHO The message is: $(MESSAGE) ; } ---- + If the user wants a specific message, he invokes jam with `-sMESSAGE=message text`. If he wants no message, he invokes jam with `-sMESSAGE=` and nothing at all is printed. * The parsing of command line options in Jam can be rather unintuitive, with regards to how other Unix programs accept options. There are two variants accepted as valid for an option: 1. `-xvalue`, and 2. `-x value`. ",16212,True,2633.004013617119,median "------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- G N A T . C O M M A N D _ L I N E -- -- -- -- S p e c -- -- -- -- Copyright (C) 1999-2012, AdaCore -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- -- -- -- -- -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- . -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- High level package for command line parsing and manipulation ---------------------------------------- -- Simple Parsing of the Command Line -- ---------------------------------------- -- This package provides an interface for parsing command line arguments, -- when they are either read from Ada.Command_Line or read from a string list. -- As shown in the example below, one should first retrieve the switches -- (special command line arguments starting with '-' by default) and their -- parameters, and then the rest of the command line arguments. -- -- While it may appear easy to parse the command line arguments with -- Ada.Command_Line, there are in fact lots of special cases to handle in some -- applications. Those are fully managed by GNAT.Command_Line. Among these are -- switches with optional parameters, grouping switches (for instance ""-ab"" -- might mean the same as ""-a -b""), various characters to separate a switch -- and its parameter (or none: ""-a 1"" and ""-a1"" are generally the same, which -- can introduce confusion with grouped switches),... -- -- begin -- loop -- case Getopt (""a b: ad"") is -- Accepts '-a', '-ad', or '-b argument' -- when ASCII.NUL => exit; -- when 'a' => -- if Full_Switch = ""a"" then -- Put_Line (""Got a""); -- else -- Put_Line (""Got ad""); -- end if; -- when 'b' => Put_Line (""Got b + "" & Parameter); -- when others => -- raise Program_Error; -- cannot occur! -- end case; -- end loop; -- loop -- declare -- S : constant String := Get_Argument (Do_Expansion => True); -- begin -- exit when S'Length = 0; -- Put_Line (""Got "" & S); -- end; -- end loop; -- exception -- when Invalid_Switch => Put_Line (""Invalid Switch "" & Full_Switch); -- when Invalid_Parameter => Put_Line (""No parameter for "" & Full_Switch); -- end; -------------- -- Sections -- -------------- -- A more complicated example would involve the use of sections for the -- switches, as for instance in gnatmake. The same command line is used to -- provide switches for several tools. Each tool recognizes its switches by -- separating them with special switches that act as section separators. -- Each section acts as a command line of its own. -- begin -- Initialize_Option_Scan ('-', False, ""largs bargs cargs""); -- loop -- -- Same loop as above to get switches and arguments -- end loop; -- Goto_Section (""bargs""); -- loop -- -- Same loop as above to get switches and arguments -- -- The supported switches in Getopt might be different -- end loop; -- Goto_Section (""cargs""); -- loop -- -- Same loop as above to get switches and arguments -- -- The supported switches in Getopt might be different -- end loop; -- end; ------------------------------- -- Parsing a List of Strings -- ------------------------------- -- The examples above show how to parse the command line when the arguments -- are read directly from Ada.Command_Line. However, these arguments can also -- be read from a list of strings. This can be useful in several contexts, -- either because your system does not support Ada.Command_Line, or because -- you are manipulating other tools and creating their command lines by hand, -- or for any other reason. -- To create the list of strings, it is recommended to use -- GNAT.OS_Lib.Argument_String_To_List. -- The example below shows how to get the parameters from such a list. Note -- also the use of '*' to get all the switches, and not report errors when an -- unexpected switch was used by the user -- declare -- Parser : Opt_Parser; -- Args : constant Argument_List_Access := -- GNAT.OS_Lib.Argument_String_To_List (""-g -O1 -Ipath""); -- begin -- Initialize_Option_Scan (Parser, Args); -- while Getopt (""* g O! I="", Parser) /= ASCII.NUL loop -- Put_Line (""Switch "" & Full_Switch (Parser) -- & "" param="" & Parameter (Parser)); -- end loop; -- Free (Parser); -- end; ------------------------------------------- -- High-Level Command Line Configuration -- ------------------------------------------- -- As shown above, the code is still relatively low-level. For instance, there -- is no way to indicate which switches are related (thus if ""-l"" and ""--long"" -- should have the same effect, your code will need to test for both cases). -- Likewise, it is difficult to handle more advanced constructs, like: -- * Specifying -gnatwa is the same as specifying -gnatwu -gnatwv, but -- shorter and more readable -- * All switches starting with -gnatw can be grouped, for instance one -- can write -gnatwcd instead of -gnatwc -gnatwd. -- Of course, this can be combined with the above and -gnatwacd is the -- same as -gnatwc -gnatwd -gnatwu -gnatwv -- * The switch -T is the same as -gnatwAB (same as -gnatwA -gnatwB) -- With the above form of Getopt, you would receive ""-gnatwa"", ""-T"" or -- ""-gnatwcd"" in the examples above, and thus you require additional manual -- parsing of the switch. -- Instead, this package provides the type Command_Line_Configuration, which -- stores all the knowledge above. For instance: -- Config : Command_Line_Configuration; -- Define_Alias (Config, ""-gnatwa"", ""-gnatwu -gnatwv""); -- Define_Prefix (Config, ""-gnatw""); -- Define_Alias (Config, ""-T"", ""-gnatwAB""); -- You then need to specify all possible switches in your application by -- calling Define_Switch, for instance: -- Define_Switch (Config, ""-gnatwu"", Help => ""warn on unused entities""); -- Define_Switch (Config, ""-gnatwv"", Help => ""warn on unassigned var""); -- ... -- Specifying the help message is optional, but makes it easy to then call -- the function: -- Display_Help (Config); -- that will display a properly formatted help message for your application, -- listing all possible switches. That way you have a single place in which -- to maintain the list of switches and their meaning, rather than maintaining -- both the string to pass to Getopt and a subprogram to display the help. -- Both will properly stay synchronized. -- Once you have this Config, you just have to call: -- Getopt (Config, Callback'Access); -- to parse the command line. The Callback will be called for each switch -- found on the command line (in the case of our example, that is ""-gnatwu"" -- and then ""-gnatwv"", not ""-gnatwa"" itself). This simplifies command line -- parsing a lot. -- In fact, this can be further automated for the most command case where the -- parameter passed to a switch is stored in a variable in the application. -- When a switch is defined, you only have to indicate where to store the -- value, and let Getopt do the rest. For instance: -- Optimization : aliased Integer; -- Verbose : aliased Boolean; -- Define_Switch (Config, Verbose'Access, -- ""-v"", Long_Switch => ""--verbose"", -- Help => ""Output extra verbose information""); -- Define_Switch (Config, Optimization'Access, -- ""-O?"", Help => ""Optimization level""); -- Getopt (Config); -- No callback -- Since all switches are handled automatically, we don't even need to pass -- a callback to Getopt. Once getopt has been called, the two variables -- Optimization and Verbose have been properly initialized, either to the -- default value or to the value found on the command line. ------------------------------------------------ -- Creating and Manipulating the Command Line -- ------------------------------------------------ -- This package provides mechanisms to create and modify command lines by -- adding or removing arguments from them. The resulting command line is kept -- as short as possible by coalescing arguments whenever possible. -- Complex command lines can thus be constructed, for example from a GUI -- (although this package does not by itself depend upon any specific GUI -- toolkit). -- Using the configuration defined earlier, one can then construct a command -- line for the tool with: -- Cmd : Command_Line; -- Set_Configuration (Cmd, Config); -- Config created earlier -- Add_Switch (Cmd, ""-bar""); -- Add_Switch (Cmd, ""-gnatwu""); -- Add_Switch (Cmd, ""-gnatwv""); -- will be grouped with the above -- Add_Switch (Cmd, ""-T""); -- The resulting command line can be iterated over to get all its switches, -- There are two modes for this iteration: either you want to get the -- shortest possible command line, which would be: -- -bar -gnatwaAB -- or on the other hand you want each individual switch (so that your own -- tool does not have to do further complex processing), which would be: -- -bar -gnatwu -gnatwv -gnatwA -gnatwB -- Of course, we can assume that the tool you want to spawn would understand -- both of these, since they are both compatible with the description we gave -- above. However, the first result is useful if you want to show the user -- what you are spawning (since that keeps the output shorter), and the second -- output is more useful for a tool that would check whether -gnatwu was -- passed (which isn't obvious in the first output). Likewise, the second -- output is more useful if you have a graphical interface since each switch -- can be associated with a widget, and you immediately know whether -gnatwu -- was selected. -- -- Some command line arguments can have parameters, which on a command line -- appear as a separate argument that must immediately follow the switch. -- Since the subprograms in this package will reorganize the switches to group -- them, you need to indicate what is a command line parameter, and what is a -- switch argument. -- This is done by passing an extra argument to Add_Switch, as in: -- Add_Switch (Cmd, ""-foo"", Parameter => ""arg1""); -- This ensures that ""arg1"" will always be treated as the argument to -foo, -- and will not be grouped with other parts of the command line. with Ada.Command_Line; with GNAT.Directory_Operations; with GNAT.OS_Lib; with GNAT.Regexp; with GNAT.Strings; package GNAT.Command_Line is ------------- -- Parsing -- ------------- type Opt_Parser is private; Command_Line_Parser : constant Opt_Parser; -- This object is responsible for parsing a list of arguments, which by -- default are the standard command line arguments from Ada.Command_Line. -- This is really a pointer to actual data, which must therefore be -- initialized through a call to Initialize_Option_Scan, and must be freed -- with a call to Free. -- -- As a special case, Command_Line_Parser does not need to be either -- initialized or free-ed. procedure Initialize_Option_Scan (Switch_Char : Character := '-'; Stop_At_First_Non_Switch : Boolean := False; Section_Delimiters : String := """"); procedure Initialize_Option_Scan (Parser : out Opt_Parser; Command_Line : GNAT.OS_Lib.Argument_List_Access; Switch_Char : Character := '-'; Stop_At_First_Non_Switch : Boolean := False; Section_Delimiters : String := """"); -- The first procedure resets the internal state of the package to prepare -- to rescan the parameters. It does not need to be called before the -- first use of Getopt (but it could be), but it must be called if you -- want to start rescanning the command line parameters from the start. -- The optional parameter Switch_Char can be used to reset the switch -- character, e.g. to '/' for use in DOS-like systems. -- -- The second subprogram initializes a parser that takes its arguments -- from an array of strings rather than directly from the command line. In -- this case, the parser is responsible for freeing the strings stored in -- Command_Line. If you pass null to Command_Line, this will in fact create -- a second parser for Ada.Command_Line, which doesn't share any data with -- the default parser. This parser must be free'ed. -- -- The optional parameter Stop_At_First_Non_Switch indicates if Getopt is -- to look for switches on the whole command line, or if it has to stop as -- soon as a non-switch argument is found. -- -- Example: -- -- Arguments: my_application file1 -c -- -- If Stop_At_First_Non_Switch is False, then -c will be considered -- as a switch (returned by getopt), otherwise it will be considered -- as a normal argument (returned by Get_Argument). -- -- If Section_Delimiters is set, then every following subprogram -- (Getopt and Get_Argument) will only operate within a section, which -- is delimited by any of these delimiters or the end of the command line. -- -- Example: -- Initialize_Option_Scan (Section_Delimiters => ""largs bargs cargs""); -- -- Arguments on command line : my_application -c -bargs -d -e -largs -f -- This line contains three sections, the first one is the default one -- and includes only the '-c' switch, the second one is between -bargs -- and -largs and includes '-d -e' and the last one includes '-f'. procedure Free (Parser : in out Opt_Parser); -- Free the memory used by the parser. Calling this is not mandatory for -- the Command_Line_Parser procedure Goto_Section (Name : String := """"; Parser : Opt_Parser := Command_Line_Parser); -- Change the current section. The next Getopt or Get_Argument will start -- looking at the beginning of the section. An empty name ("""") refers to -- the first section between the program name and the first section -- delimiter. If the section does not exist in Section_Delimiters, then -- Invalid_Section is raised. If the section does not appear on the command -- line, then it is treated as an empty section. function Full_Switch (Parser : Opt_Parser := Command_Line_Parser) return String; -- Returns the full name of the last switch found (Getopt only returns the -- first character). Does not include the Switch_Char ('-' by default), -- unless the ""*"" option of Getopt is used (see below). function Current_Section (Parser : Opt_Parser := Command_Line_Parser) return String; -- Return the name of the current section. -- The list of valid sections is defined through Initialize_Option_Scan function Getopt (Switches : String; Concatenate : Boolean := True; Parser : Opt_Parser := Command_Line_Parser) return Character; -- This function moves to the next switch on the command line (defined as -- switch character followed by a character within Switches, casing being -- significant). The result returned is the first character of the switch -- that is located. If there are no more switches in the current section, -- returns ASCII.NUL. If Concatenate is True (the default), the switches do -- not need to be separated by spaces (they can be concatenated if they do -- not require an argument, e.g. -ab is the same as two separate arguments -- -a -b). -- -- Switches is a string of all the possible switches, separated by -- spaces. A switch can be followed by one of the following characters: -- -- ':' The switch requires a parameter. There can optionally be a space -- on the command line between the switch and its parameter. -- -- '=' The switch requires a parameter. There can either be a '=' or a -- space on the command line between the switch and its parameter. -- -- '!' The switch requires a parameter, but there can be no space on the -- command line between the switch and its parameter. -- -- '?' The switch may have an optional parameter. There can be no space -- between the switch and its argument. -- -- e.g. if Switches has the following value : ""a? b"", -- The command line can be: -- -- -afoo : -a switch with 'foo' parameter -- -a foo : -a switch and another element on the -- command line 'foo', returned by Get_Argument -- -- Example: if Switches is ""-a: -aO:"", you can have the following -- command lines: -- -- -aarg : 'a' switch with 'arg' parameter -- -a arg : 'a' switch with 'arg' parameter -- -aOarg : 'aO' switch with 'arg' parameter -- -aO arg : 'aO' switch with 'arg' parameter -- -- Example: -- -- Getopt (""a b: ac ad?"") -- -- accept either 'a' or 'ac' with no argument, -- accept 'b' with a required argument -- accept 'ad' with an optional argument -- -- If the first item in switches is '*', then Getopt will catch -- every element on the command line that was not caught by any other -- switch. The character returned by GetOpt is '*', but Full_Switch -- contains the full command line argument, including leading '-' if there -- is one. If this character was not returned, there would be no way of -- knowing whether it is there or not. -- -- Example -- Getopt (""* a b"") -- If the command line is '-a -c toto.o -b', Getopt will return -- successively 'a', '*', '*' and 'b', with Full_Switch returning -- ""a"", ""-c"", ""toto.o"", and ""b"". -- -- When Getopt encounters an invalid switch, it raises the exception -- Invalid_Switch and sets Full_Switch to return the invalid switch. -- When Getopt cannot find the parameter associated with a switch, it -- raises Invalid_Parameter, and sets Full_Switch to return the invalid -- switch. -- -- Note: in case of ambiguity, e.g. switches a ab abc, then the longest -- matching switch is returned. -- -- Arbitrary characters are allowed for switches, although it is -- strongly recommended to use only letters and digits for portability -- reasons. -- -- When Concatenate is False, individual switches need to be separated by -- spaces. -- -- Example -- Getopt (""a b"", Concatenate => False) -- If the command line is '-ab', exception Invalid_Switch will be -- raised and Full_Switch will return ""ab"". function Get_Argument (Do_Expansion : Boolean := False; Parser : Opt_Parser := Command_Line_Parser) return String; -- Returns the next element on the command line that is not a switch. This -- function should not be called before Getopt has returned ASCII.NUL. -- -- If Do_Expansion is True, then the parameter on the command line will -- be considered as a filename with wild cards, and will be expanded. The -- matching file names will be returned one at a time. This is useful in -- non-Unix systems for obtaining normal expansion of wild card references. -- When there are no more arguments on the command line, this function -- returns an empty string. function Parameter (Parser : Opt_Parser := Command_Line_Parser) return String; -- Returns parameter associated with the last switch returned by Getopt. -- If no parameter was associated with the last switch, or no previous call -- has been made to Get_Argument, raises Invalid_Parameter. If the last -- switch was associated with an optional argument and this argument was -- not found on the command line, Parameter returns an empty string. function Separator (Parser : Opt_Parser := Command_Line_Parser) return Character; -- The separator that was between the switch and its parameter. This is -- useful if you want to know exactly what was on the command line. This -- is in general a single character, set to ASCII.NUL if the switch and -- the parameter were concatenated. A space is returned if the switch and -- its argument were in two separate arguments. Invalid_Section : exception; -- Raised when an invalid section is selected by Goto_Section Invalid_Switch : exception; -- Raised when an invalid switch is detected in the command line Invalid_Parameter : exception; -- Raised when a parameter is missing, or an attempt is made to obtain a -- parameter for a switch that does not allow a parameter. ----------------------------------------- -- Expansion of command line arguments -- ----------------------------------------- -- These subprograms take care of of expanding globbing patterns on the -- command line. On Unix, such expansion is done by the shell before your -- application is called. But on Windows you must do this expansion -- yourself. type Expansion_Iterator is limited private; -- Type used during expansion of file names procedure Start_Expansion (Iterator : out Expansion_Iterator; Pattern : String; Directory : String := """"; Basic_Regexp : Boolean := True); -- Initialize a wild card expansion. The next calls to Expansion will -- return the next file name in Directory which match Pattern (Pattern -- is a regular expression, using only the Unix shell and DOS syntax if -- Basic_Regexp is True). When Directory is an empty string, the current -- directory is searched. -- -- Pattern may contain directory separators (as in ""src/*/*.ada""). -- Subdirectories of Directory will also be searched, up to one -- hundred levels deep. -- -- When Start_Expansion has been called, function Expansion should -- be called repeatedly until it returns an empty string, before -- Start_Expansion can be called again with the same Expansion_Iterator -- variable. function Expansion (Iterator : Expansion_Iterator) return String; -- Returns the next file in the directory matching the parameters given -- to Start_Expansion and updates Iterator to point to the next entry. -- Returns an empty string when there are no more files. -- -- If Expansion is called again after an empty string has been returned, -- then the exception GNAT.Directory_Operations.Directory_Error is raised. ----------------- -- Configuring -- ----------------- -- The following subprograms are used to manipulate a command line -- represented as a string (for instance ""-g -O2""), as well as parsing -- the switches from such a string. They provide high-level configurations -- to define aliases (a switch is equivalent to one or more other switches) -- or grouping of switches (""-gnatyac"" is equivalent to ""-gnatya"" and -- ""-gnatyc""). -- See the top of this file for examples on how to use these subprograms type Command_Line_Configuration is private; procedure Define_Section (Config : in out Command_Line_Configuration; Section : String); -- Indicates a new switch section. All switches belonging to the same -- section are ordered together, preceded by the section. They are placed -- at the end of the command line (as in ""gnatmake somefile.adb -cargs -g"") -- -- The section name should not include the leading '-'. So for instance in -- the case of gnatmake we would use: -- -- Define_Section (Config, ""cargs""); -- Define_Section (Config, ""bargs""); procedure Define_Alias (Config : in out Command_Line_Configuration; Switch : String; Expanded : String; Section : String := """"); -- Indicates that whenever Switch appears on the command line, it should -- be expanded as Expanded. For instance, for the GNAT compiler switches, -- we would define ""-gnatwa"" as an alias for ""-gnatwcfijkmopruvz"", ie some -- default warnings to be activated. -- -- This expansion is only done within the specified section, which must -- have been defined first through a call to [Define_Section]. procedure Define_Prefix (Config : in out Command_Line_Configuration; Prefix : String); -- Indicates that all switches starting with the given prefix should be -- grouped. For instance, for the GNAT compiler we would define ""-gnatw"" as -- a prefix, so that ""-gnatwu -gnatwv"" can be grouped into ""-gnatwuv"" It is -- assumed that the remainder of the switch (""uv"") is a set of characters -- whose order is irrelevant. In fact, this package will sort them -- alphabetically. -- -- When grouping switches that accept arguments (for instance ""-gnatyL!"" -- as the definition, and ""-gnatyaL12b"" as the command line), only -- numerical arguments are accepted. The above is equivalent to -- ""-gnatya -gnatyL12 -gnatyb"". procedure Define_Switch (Config : in out Command_Line_Configuration; Switch : String := """"; Long_Switch : String := """"; Help : String := """"; Section : String := """"; Argument : String := ""ARG""); -- Indicates a new switch. The format of this switch follows the getopt -- format (trailing ':', '?', etc for defining a switch with parameters). -- -- Switch should also start with the leading '-' (or any other characters). -- If this character is not '-', you need to call Initialize_Option_Scan to -- set the proper character for the parser. -- -- The switches defined in the command_line_configuration object are used -- when ungrouping switches with more that one character after the prefix. -- -- Switch and Long_Switch (when specified) are aliases and can be used -- interchangeably. There is no check that they both take an argument or -- both take no argument. Switch can be set to ""*"" to indicate that any -- switch is supported (in which case Getopt will return '*', see its -- documentation). -- -- Help is used by the Display_Help procedure to describe the supported -- switches. -- -- In_Section indicates in which section the switch is valid (you need to -- first define the section through a call to Define_Section). -- -- Argument is the name of the argument, as displayed in the automatic -- help message. It is always capitalized for consistency. procedure Define_Switch (Config : in out Command_Line_Configuration; Output : access Boolean; Switch : String := """"; Long_Switch : String := """"; Help : String := """"; Section : String := """"; Value : Boolean := True); -- See Define_Switch for a description of the parameters. -- When the switch is found on the command line, Getopt will set -- Output.all to Value. -- -- Output is always initially set to ""not Value"", so that if the switch is -- not found on the command line, Output still has a valid value. -- The switch must not take any parameter. -- -- Output must exist at least as long as Config, otherwise an erroneous -- memory access may occur. procedure Define_Switch (Config : in out Command_Line_Configuration; Output : access Integer; Switch : String := """"; Long_Switch : String := """"; Help : String := """"; Section : String := """"; Initial : Integer := 0; Default : Integer := 1; Argument : String := ""ARG""); -- See Define_Switch for a description of the parameters. When the -- switch is found on the command line, Getopt will set Output.all to the -- value of the switch's parameter. If the parameter is not an integer, -- Invalid_Parameter is raised. -- Output is always initialized to Initial. If the switch has an optional -- argument which isn't specified by the user, then Output will be set to -- Default. The switch must accept an argument. procedure Define_Switch (Config : in out Command_Line_Configuration; Output : access GNAT.Strings.String_Access; Switch : String := """"; Long_Switch : String := """"; Help : String := """"; Section : String := """"; Argument : String := ""ARG""); -- Set Output to the value of the switch's parameter when the switch is -- found on the command line. Output is always initialized to the empty -- string if it does not have a value already (otherwise it is left as is -- so that you can specify the default value directly in the declaration -- of the variable). The switch must accept an argument. procedure Set_Usage (Config : in out Command_Line_Configuration; Usage : String := ""[switches] [arguments]""; Help : String := """"; Help_Msg : String := """"); -- Defines the general format of the call to the application, and a short -- help text. These are both displayed by Display_Help. When a non-empty -- Help_Msg is given, it is used by Display_Help instead of the -- automatically generated list of supported switches. procedure Display_Help (Config : Command_Line_Configuration); -- Display the help for the tool (ie its usage, and its supported switches) function Get_Switches (Config : Command_Line_Configuration; Switch_Char : Character := '-'; Section : String := """") return String; -- Get the switches list as expected by Getopt, for a specific section of -- the command line. This list is built using all switches defined -- previously via Define_Switch above. function Section_Delimiters (Config : Command_Line_Configuration) return String; -- Return a string suitable for use in Initialize_Option_Scan procedure Free (Config : in out Command_Line_Configuration); -- Free the memory used by Config type Switch_Handler is access procedure (Switch : String; Parameter : String; Section : String); -- Called when a switch is found on the command line. Switch includes -- any leading '-' that was specified in Define_Switch. This is slightly -- different from the functional version of Getopt above, for which -- Full_Switch omits the first leading '-'. Exit_From_Command_Line : exception; -- Emitted when the program should exit. This is called when Getopt below -- has seen -h, --help or an invalid switch. procedure Getopt (Config : Command_Line_Configuration; Callback : Switch_Handler := null; Parser : Opt_Parser := Command_Line_Parser; Concatenate : Boolean := True); -- Similar to the standard Getopt function. For each switch found on the -- command line, this calls Callback, if the switch is not handled -- automatically. -- -- The list of valid switches are the ones from the configuration. The -- switches that were declared through Define_Switch with an Output -- parameter are never returned (and result in a modification of the Output -- variable). This function will in fact never call [Callback] if all -- switches were handled automatically and there is nothing left to do. -- -- The option Concatenate is identical to the one of the standard Getopt -- function. -- -- This procedure automatically adds -h and --help to the valid switches, -- to display the help message and raises Exit_From_Command_Line. -- If an invalid switch is specified on the command line, this procedure -- will display an error message and raises Invalid_Switch again. -- -- This function automatically expands switches: -- -- If Define_Prefix was called (for instance ""-gnaty"") and the user -- specifies ""-gnatycb"" on the command line, then Getopt returns -- ""-gnatyc"" and ""-gnatyb"" separately. -- -- If Define_Alias was called (for instance ""-gnatya = -gnatycb"") then -- the latter is returned (in this case it also expands -gnaty as per -- the above. -- -- The goal is to make handling as easy as possible by leaving as much -- work as possible to this package. -- -- As opposed to the standard Getopt, this one will analyze all sections -- as defined by Define_Section, and automatically jump from one section to -- the next. ------------------------------ -- Generating command lines -- ------------------------------ -- Once the command line configuration has been created, you can build your -- own command line. This will be done in general because you need to spawn -- external tools from your application. -- Although it could be done by concatenating strings, the following -- subprograms will properly take care of grouping switches when possible, -- so as to keep the command line as short as possible. They also provide a -- way to remove a switch from an existing command line. -- For instance: -- declare -- Config : Command_Line_Configuration; -- Line : Command_Line; -- Args : Argument_List_Access; -- begin -- Define_Switch (Config, ""-gnatyc""); -- Define_Switch (Config, ...); -- for all valid switches -- Define_Prefix (Config, ""-gnaty""); -- Set_Configuration (Line, Config); -- Add_Switch (Line, ""-O2""); -- Add_Switch (Line, ""-gnatyc""); -- Add_Switch (Line, ""-gnatyd""); -- -- Build (Line, Args); -- -- Args is now [""-O2"", ""-gnatycd""] -- end; type Command_Line is private; procedure Set_Configuration (Cmd : in out Command_Line; Config : Command_Line_Configuration); function Get_Configuration (Cmd : Command_Line) return Command_Line_Configuration; -- Set or retrieve the configuration used for that command line. The Config -- must have been initialized first, by calling one of the Define_Switches -- subprograms. procedure Set_Command_Line (Cmd : in out Command_Line; Switches : String; Getopt_Description : String := """"; Switch_Char : Character := '-'); -- Set the new content of the command line, by replacing the current -- version with Switches. -- -- The parsing of Switches is done through calls to Getopt, by passing -- Getopt_Description as an argument. (A ""*"" is automatically prepended so -- that all switches and command line arguments are accepted). If a config -- was defined via Set_Configuration, the Getopt_Description parameter will -- be ignored. -- -- To properly handle switches that take parameters, you should document -- them in Getopt_Description. Otherwise, the switch and its parameter will -- be recorded as two separate command line arguments as returned by a -- Command_Line_Iterator (which might be fine depending on your -- application). -- -- If the command line has sections (such as -bargs -cargs), then they -- should be listed in the Sections parameter (as ""-bargs -cargs""). -- -- This function can be used to reset Cmd by passing an empty string -- -- If an invalid switch is found on the command line (ie wasn't defined in -- the configuration via Define_Switch), and the configuration wasn't set -- to accept all switches (by defining ""*"" as a valid switch), then an -- exception Invalid_Switch is raised. The exception message indicates the -- invalid switch. procedure Add_Switch (Cmd : in out Command_Line; Switch : String; Parameter : String := """"; Separator : Character := ASCII.NUL; Section : String := """"; Add_Before : Boolean := False); -- Add a new switch to the command line, and combine/group it with existing -- switches if possible. Nothing is done if the switch already exists with -- the same parameter. -- -- If the Switch takes a parameter, the latter should be specified -- separately, so that the association between the two is always correctly -- recognized even if the order of switches on the command line changes. -- For instance, you should pass ""--check=full"" as (""--check"", ""full"") so -- that Remove_Switch below can simply take ""--check"" in parameter. That -- will automatically remove ""full"" as well. The value of the parameter is -- never modified by this package. -- -- On the other hand, you could decide to simply pass ""--check=full"" as -- the Switch above, and then pass no parameter. This means that you need -- to pass ""--check=full"" to Remove_Switch as well. -- -- A Switch with a parameter will never be grouped with another switch to -- avoid ambiguities as to what the parameter applies to. -- -- If the switch is part of a section, then it should be specified so that -- the switch is correctly placed in the command line, and the section -- added if not already present. For example, to add the -g switch into the -- -cargs section, you need to call (Cmd, ""-g"", Section => ""-cargs""). -- -- [Separator], if specified, overrides the separator that was defined -- through Define_Switch. For instance, if the switch was defined as -- ""-from:"", the separator defaults to a space. But if your application -- uses unusual separators not supported by GNAT.Command_Line (for instance -- it requires "":""), you can specify this separator here. -- -- For instance, -- Add_Switch(Cmd, ""-from"", ""bar"", ':') -- -- results in -- -from:bar -- -- rather than the default -- -from bar -- -- Note however that Getopt doesn't know how to handle "":"" as a separator. -- So the recommendation is to declare the switch as ""-from!"" (ie no -- space between the switch and its parameter). Then Getopt will return -- "":bar"" as the parameter, and you can trim the "":"" in your application. -- -- Invalid_Section is raised if Section was not defined in the -- configuration of the command line. -- -- Add_Before allows insertion of the switch at the beginning of the -- command line. procedure Add_Switch (Cmd : in out Command_Line; Switch : String; Parameter : String := """"; Separator : Character := ASCII.NUL; Section : String := """"; Add_Before : Boolean := False; Success : out Boolean); -- Same as above, returning the status of the operation procedure Remove_Switch (Cmd : in out Command_Line; Switch : String; Remove_All : Boolean := False; Has_Parameter : Boolean := False; Section : String := """"); -- Remove Switch from the command line, and ungroup existing switches if -- necessary. -- -- The actual parameter to the switches are ignored. If for instance -- you are removing ""-foo"", then ""-foo param1"" and ""-foo param2"" can -- be removed. -- -- If Remove_All is True, then all matching switches are removed, otherwise -- only the first matching one is removed. -- -- If Has_Parameter is set to True, then only switches having a parameter -- are removed. -- -- If the switch belongs to a section, then this section should be -- specified: Remove_Switch (Cmd_Line, ""-g"", Section => ""-cargs"") called -- on the command line ""-g -cargs -g"" will result in ""-g"", while if -- called with (Cmd_Line, ""-g"") this will result in ""-cargs -g"". -- If Remove_All is set, then both ""-g"" will be removed. procedure Remove_Switch (Cmd : in out Command_Line; Switch : String; Remove_All : Boolean := False; Has_Parameter : Boolean := False; Section : String := """"; Success : out Boolean); -- Same as above, reporting the success of the operation (Success is False -- if no switch was removed). procedure Remove_Switch (Cmd : in out Command_Line; Switch : String; Parameter : String; Section : String := """"); -- Remove a switch with a specific parameter. If Parameter is the empty -- string, then only a switch with no parameter will be removed. procedure Free (Cmd : in out Command_Line); -- Free the memory used by Cmd --------------- -- Iteration -- --------------- -- When a command line was created with the above, you can then iterate -- over its contents using the following iterator. type Command_Line_Iterator is private; procedure Start (Cmd : in out Command_Line; Iter : in out Command_Line_Iterator; Expanded : Boolean := False); -- Start iterating over the command line arguments. If Expanded is true, -- then the arguments are not grouped and no alias is used. For instance, -- ""-gnatwv"" and ""-gnatwu"" would be returned instead of ""-gnatwuv"". -- -- The iterator becomes invalid if the command line is changed through a -- call to Add_Switch, Remove_Switch or Set_Command_Line. function Current_Switch (Iter : Command_Line_Iterator) return String; function Is_New_Section (Iter : Command_Line_Iterator) return Boolean; function Current_Section (Iter : Command_Line_Iterator) return String; function Current_Separator (Iter : Command_Line_Iterator) return String; function Current_Parameter (Iter : Command_Line_Iterator) return String; -- Return the current switch and its parameter (or the empty string if -- there is no parameter or the switch was added through Add_Switch -- without specifying the parameter. -- -- Separator is the string that goes between the switch and its separator. -- It could be the empty string if they should be concatenated, or a space -- for instance. When printing, you should not add any other character. function Has_More (Iter : Command_Line_Iterator) return Boolean; -- Return True if there are more switches to be returned procedure Next (Iter : in out Command_Line_Iterator); -- Move to the next switch procedure Build (Line : in out Command_Line; Args : out GNAT.OS_Lib.Argument_List_Access; Expanded : Boolean := False; Switch_Char : Character := '-'); -- This is a wrapper using the Command_Line_Iterator. It provides a simple -- way to get all switches (grouped as much as possible), and possibly -- create an Opt_Parser. -- -- Args must be freed by the caller. -- -- Expanded has the same meaning as in Start. private Max_Depth : constant := 100; -- Maximum depth of subdirectories Max_Path_Length : constant := 1024; -- Maximum length of relative path type Depth is range 1 .. Max_Depth; type Level is record Name_Last : Natural := 0; Dir : GNAT.Directory_Operations.Dir_Type; end record; type Level_Array is array (Depth) of Level; type Section_Number is new Natural range 0 .. 65534; for Section_Number'Size use 16; type Parameter_Type is record Arg_Num : Positive; First : Positive; Last : Positive; Extra : Character; end record; type Is_Switch_Type is array (Natural range <>) of Boolean; pragma Pack (Is_Switch_Type); type Section_Type is array (Natural range <>) of Section_Number; pragma Pack (Section_Type); type Expansion_Iterator is limited record Start : Positive := 1; -- Position of the first character of the relative path to check against -- the pattern. Dir_Name : String (1 .. Max_Path_Length); Current_Depth : Depth := 1; Levels : Level_Array; Regexp : GNAT.Regexp.Regexp; -- Regular expression built with the pattern Maximum_Depth : Depth := 1; -- The maximum depth of directories, reflecting the number of directory -- separators in the pattern. end record; type Opt_Parser_Data (Arg_Count : Natural) is record Arguments : GNAT.OS_Lib.Argument_List_Access; -- null if reading from the command line The_Parameter : Parameter_Type; The_Separator : Character; The_Switch : Parameter_Type; -- This type and this variable are provided to store the current switch -- and parameter. Is_Switch : Is_Switch_Type (1 .. Arg_Count) := (others => False); -- Indicates wich arguments on the command line are considered not be -- switches or parameters to switches (leaving e.g. filenames,...) Section : Section_Type (1 .. Arg_Count) := (others => 1); -- Contains the number of the section associated with the current -- switch. If this number is 0, then it is a section delimiter, which is -- never returned by GetOpt. Current_Argument : Natural := 1; -- Number of the current argument parsed on the command line Current_Index : Natural := 1; -- Index in the current argument of the character to be processed Current_Section : Section_Number := 1; Expansion_It : aliased Expansion_Iterator; -- When Get_Argument is expanding a file name, this is the iterator used In_Expansion : Boolean := False; -- True if we are expanding a file Switch_Character : Character := '-'; -- The character at the beginning of the command line arguments, -- indicating the beginning of a switch. Stop_At_First : Boolean := False; -- If it is True then Getopt stops at the first non-switch argument end record; Command_Line_Parser_Data : aliased Opt_Parser_Data (Ada.Command_Line.Argument_Count); -- The internal data used when parsing the command line type Opt_Parser is access all Opt_Parser_Data; Command_Line_Parser : constant Opt_Parser := Command_Line_Parser_Data'Access; type Switch_Type is (Switch_Untyped, Switch_Boolean, Switch_Integer, Switch_String); type Switch_Definition (Typ : Switch_Type := Switch_Untyped) is record Switch : GNAT.OS_Lib.String_Access; Long_Switch : GNAT.OS_Lib.String_Access; Section : GNAT.OS_Lib.String_Access; Help : GNAT.OS_Lib.String_Access; Argument : GNAT.OS_Lib.String_Access; -- null if ""ARG"". -- Name of the argument for this switch. case Typ is when Switch_Untyped => null; when Switch_Boolean => Boolean_Output : access Boolean; Boolean_Value : Boolean; -- will set Output to that value when Switch_Integer => Integer_Output : access Integer; Integer_Initial : Integer; Integer_Default : Integer; when Switch_String => String_Output : access GNAT.Strings.String_Access; end case; end record; type Switch_Definitions is array (Natural range <>) of Switch_Definition; type Switch_Definitions_List is access all Switch_Definitions; -- [Switch] includes the leading '-' type Alias_Definition is record Alias : GNAT.OS_Lib.String_Access; Expansion : GNAT.OS_Lib.String_Access; Section : GNAT.OS_Lib.String_Access; end record; type Alias_Definitions is array (Natural range <>) of Alias_Definition; type Alias_Definitions_List is access all Alias_Definitions; type Command_Line_Configuration_Record is record Prefixes : GNAT.OS_Lib.Argument_List_Access; -- The list of prefixes Sections : GNAT.OS_Lib.Argument_List_Access; -- The list of sections Star_Switch : Boolean := False; -- Whether switches not described in this configuration should be -- returned to the user (True). If False, an exception Invalid_Switch -- is raised. Aliases : Alias_Definitions_List; Usage : GNAT.OS_Lib.String_Access; Help : GNAT.OS_Lib.String_Access; Help_Msg : GNAT.OS_Lib.String_Access; Switches : Switch_Definitions_List; -- List of expected switches (Used when expanding switch groups) end record; type Command_Line_Configuration is access Command_Line_Configuration_Record; type Command_Line is record Config : Command_Line_Configuration; Expanded : GNAT.OS_Lib.Argument_List_Access; Params : GNAT.OS_Lib.Argument_List_Access; -- Parameter for the corresponding switch in Expanded. The first -- character is the separator (or ASCII.NUL if there is no separator). Sections : GNAT.OS_Lib.Argument_List_Access; -- The list of sections Coalesce : GNAT.OS_Lib.Argument_List_Access; Coalesce_Params : GNAT.OS_Lib.Argument_List_Access; Coalesce_Sections : GNAT.OS_Lib.Argument_List_Access; -- Cached version of the command line. This is recomputed every time -- the command line changes. Switches are grouped as much as possible, -- and aliases are used to reduce the length of the command line. The -- parameters are not allocated, they point into Params, so they must -- not be freed. end record; type Command_Line_Iterator is record List : GNAT.OS_Lib.Argument_List_Access; Sections : GNAT.OS_Lib.Argument_List_Access; Params : GNAT.OS_Lib.Argument_List_Access; Current : Natural; end record; end GNAT.Command_Line; ",12171,False,2430.4436460157885,median "= Setting up plentyShop LTS :lang: en include::{includedir}/_header.adoc[] :author: team-webshop :keywords: online store, Ceres, plentyShop LTS, multilingualism, Trusted Shops, template, ShopBuilder, widget, plentyShop, ShopBooster :position: 10 :url: online-store/setting-up-ceres :id: GW5QHSI link:https://marketplace.plentymarkets.com/plugins/templates/Ceres_4697[plentyShop LTS]{nbsp}icon:external-link[] is the official template plugin for the default online store of plentymarkets: plentyShop. In plentyShop, design and logic are separated from each other. The shop is integrated into your plentymarkets system via 2 plugins. The *plentyShop LTS* plugin contains plentyShop's standard design and can be customised to meet your needs. The link:https://marketplace.plentymarkets.com/plugins/templates/IO_4696[IO^]{nbsp}icon:external-link[] plugin contains the logic of plentyShop, is a general basis for all design plugins and can also be used by other plugins. [#15] == Preparation Before you can begin setting up your plentyShop, the plugins *IO* and *plentyShop LTS* need to be: [.instruction] <> in the plentyMarketplace - <> in the *Plugins » Plugin overview* menu - <> in the *Plugin » Plugin overview* menu. You can find detailed instructions in the link:https://marketplace.plentymarkets.com/plugins/templates/Ceres_4697[plugin guides^]{nbsp}icon:external-link[]. When both plugins are deployed in a plugin set, you can begin setting up your plentyShop. [#user-rights] === Assigning rights for back end users :rights-purpose: carry out plentyShop LTS settings and create shop pages :right-one: pass:quotes[*CMS*] :right-two: pass:quotes[*Plugins*] :right-three: pass:quotes[*Setup » Assistants*] include::_includes:page$rights.adoc[] [#240] === Setting up the standard country of delivery Set up a standard country of delivery for each <<#220, activated language>> of your plentyShop. When switching the language in a plentyShop, the country of delivery will automatically adapt in the header and in the checkout. For further information aboutsetting up countries of delivery, refer to the <> manual page. [#250.instruction] Setting up the standard country of delivery: . Go to *Setup » Client » Select client » Orders*. . Select a country of delivery for each language under *Standard country of delivery*. . *Save* the settings. + → The countries of delivery will automatically change when switching the language in your plentyShop. [#260] === Setting up the default shipping method Set up the default shipping method for your plentyShop. This shipping method will be used for calculating the shipping costs in the shopping cart before a customer registers in your plentyShop. The default shipping method is preselected in the checkout. For further information about shipping methods and shipping profiles, refer to the <> manual chapter. [#270.instruction] Setting up the default shipping method: . Go to *Setup » Client » Select client » Orders*. . Select a *default shipping method*. . Select a *default shipping profile*. . *Save* the settings. + → The default shipping method will be used in the shopping cart and is preselected in the checkout. [#280] === Setting up the default payment method Set up the default payment method for your plentyShop. Only link:https://marketplace.plentymarkets.com/plugins/payment[Payment method plugins^]{nbsp}icon:external-link[] can be used in *plentyShop LTS*. The payment method plugins will be available as default payment methods after the setup. Please refer to the corresponding *User guide* of the payment method plugin in the plentyMarketplace. [#290.instruction] Setting up the default payment method: . Go to *Setup » Client » Select client » Orders*. . Select a *default payment method*. + → A payment method plugin must be selected for the use in your plentyShop. *Save* the settings. + → The default payment method is preselected in the checkout. [#300] === Storing legal information plentyShop LTS provides specific templates for your legal information. You can save and display your legal information in different languages. In the *Legal information* menu, you can save your *terms and conditions*, *cancellation rights*, the *cancellation form*, *privacy policy* and *legal disclosure* for your plentyShop. [#310.instruction] Entering the terms and conditions in clear text: . Go to *Setup » Client » Select client » Online store » Legal information*. . Expand a *language*. . Click on the *Terms and conditions* tab. . Click on the *Text* tab. . Enter the text for your terms and conditions. . *Save* the settings. Alternatively, save your legal texts in HTML format. For this purpose, use the features of the HTML editor or enter the HTML as *Source code*. [#320.instruction] Entering the terms and conditions in HTML format: . Go to *Setup » Client » Select client » Online store » Legal information*. . Expand a *language*. . Click on the *Terms and conditions* tab. . Click on the *HTML* tab. . If you want to enter your text as HTML code, click on *Source code*. . Enter the formatted text for your terms and conditions. . *Save* the settings. Enter the texts for the *cancellation rights*, the *cancellation form*, the *privacy policy* and the *legal disclosure* of your plentyShop analogously in the desired languages. Alternatively, upload a PDF file for your <<#70, cancellation form>>. These texts will be displayed on the corresponding pages in *plentyShop LTS*. + [#10] == Setting up the plentyShop LTS plugin After the <<#15, preparation>> for your plentyShop LTS store is done, you can begin setting up the *plentyShop LTS* plugin. The following chapters lead through the setup of the individual tabs of the <<#20, plentyShop LTS configuration>>. You access the plentyShop LTS configuration via the *Plugin overview* by clicking the *plentyShop LTS* plugin. No programming skills are necessary for the setup. [[image-confirg]] .plentyShop LTS configuration image::omni-channel/online-shop/assets/DE-Ceres-einrichten-Konfiguration.png[] [#20] === Carrying out global settings Carry out global settings, which affect the entire template, in the *Global* tab. + Here, you also set up the contact page of your plentyShop and the contact form for customer requests. [#45.instruction] Carrying out global settings: . Go to *Plugins » Plugin overview*. + → The plugin overview will open. . Click on *plentyShop LTS*. + → The plugin will open. → The tab *Global* is preselected. . Carry out the settings. Pay attention to the information given in <>. . *Save* the settings. [[table-global-item-settings]] .Carrying out global settings [cols=""1,3""] |==== |Setting |Explanation | *Company logo* |Select the image file for your company logo. The company logo can be uploaded via the *Select file* button on the right or in the *CMS » Webspace* menu in the *layout* folder. | *Favicon of the online store* |Select the image file for the favicon. The favicon can be uploaded via the *Select file* button on the right. The image file has to be in *.ICO* format. | *Category to display shipping information* |<<#30, Create and link a content category>> for displaying information about shipping costs in the plentyShop. | *B2B customer class* |Enter the ID for the default customer class for business customers. For further information, refer to the <> chapter of the manual. | *Enable Callisto route pattern for items* |Activate to use the Callisto URL route pattern in plentyShop LTS. This is required, for example, when using the <>. We advise you not to activate this setting if you use an unaltered plentyShop plentyShop LTS. | *Contact form email address* |Enter the email address, to which customers can send the contact form. | *Show contact data* |Select one, multiple or *ALL* contact information options to be displayed in the contact data in the plentyShop. The contact information activated here are loaded from the <> of your plentymarkets system. | *Google reCAPTCHA Website key* |Enter the Google reCAPTCHA Website key in order to integrate a Google reCAPTCHA into your contact form. You receive this key when registering your website for link:https://www.google.com/recaptcha/admin#list[Google reCAPTCHA^]{nbsp}icon:external-link[]. Note that you have to select a reCAPTCHA of the type *Hidden reCAPTCHA* during setup. The reCAPTCHA validates the visitor of your plentyShop in the background and remains invisible for your customers. Please note that the Google reCAPTCHA necessitates the inclusion of a reference in your privacy policy. | *Google Maps API key* | Enter the API key from Google Maps, in order to display the location of your store on a Google map. For this, you need an link:https://developers.google.com/maps/documentation/javascript/get-api-key[API key^]{nbsp}icon:external-link[] for Google Maps. Alternatively, enter 0 to hide the map. | *Zoom level* |Enter a zoom level for the Google map. The default value is 16; higher values zoom in, lower values zoom out. | *Show map in mobile view* |Activate to show the map on mobile devices. | *Enable to display checkbox for confirming privacy policy* |Activate to display a checkbox, with which customers can consent to the privacy policy. |==== In the *Global* tab, you also link a *Category to display shipping cost information* in the plentyShop.+ Create a category of the type *Content* first. [#30.instruction] Creating a content category: . Go to *Item » Categories*. . Click on *New category*. + → The *Create new category* window opens. . Enter a name for the category. . Select the category type. . Click on *Create*. + → The new category will be created and displayed in the category tree. . Open the new category in the directory tree on the left. . Select *Content* from the *Type* drop-down list. . Activate the *Client (store)*. . Click on the *Template* tab. . Enter the content that you wish to display in the plentyShop. You can enter either free text or HTML. . *Save* the settings. [IMPORTANT] ==== You enter the content of content categories in the *Template* tab instead of the tabs *Description 1* or *Description 2*. ==== After saving the category settings, the *CategoryTemplates* plugin will be available in the *Plugin » Plugin overview* menu. This plugin provides the contents of content categories for plentyShop LTS. The plugin set has to be deployed by clicking the *Save & publish plugin* button. Afterwards, link the category in the configuration of the *plentyShop LTS* plugin: [#40.instruction] Linking a category: . Go to *Plugins » Plugin overview*. + → The plugin overview will open. . Click on *plentyShop LTS*. + → The plugin will open. . Click on *Configuration* in the directory tree. + → The *Global* tab is pre-selected. . Click on *Search* under *Category to display shipping information*. + → The *Categories* window opens. . Select the previously created category in order to link this category for displaying information about shipping costs. . Click on *Select*. . *Save* the settings. + → The category will be linked. After linking the category, the plugin *CategoryTemplates* has to be set to *Active* in the corresponding plugin set. Deploy the plugin set by clicking the *Save & publish plugin* button. [#50] === Customising the homepage *plentyShop LTS* comes with a default homepage as placeholder. + You customise the homepage of your plentyShop with the <>. Deactivate the default homepage to replace it with the ShopBuilder homepage. [#60.instruction] Deactivating the default homepage: . Go to *Plugins » Plugin overview*. + → The plugin overview will open. . Click on *plentyShop LTS*. + → The plugin will open. . Click on *Configuration* in the directory tree. . Click on the *Homepage* tab. . Deactivate the checkbox *Show default homepage*. . Activate the setting *Display ShopBuilder homepage*. . *Save* the settings. + → The default homepage is deactivated and your ShopBuilder homepage will be displayed. [#65] ==== Creating the plentyShop LTS homepage with the ShopBuilder With the ShopBuilder, you can create and edit the homepage of your plentyShop. This requires only a few steps in your terra back end. Please refer to the ShopBuilder <> for further information on how to set up the ShopBuilder. [#70] === Customising the header and footer (obsolete) [NOTE] ==== The settings for header and footer are only applicable for Ceres versions up to and including 2.14. Beginning with Ceres 2.15, header and footer are set up via the <>. ==== Customise the header and the footer of your design. Display your own logo and design the footer content according to your requirements. The store features, for example, are a great way to highlight the features of your plentyShop, such as free shipping. You can link content categories in the *Footer* tab to display aditional information in the footer of plentyShop. [#80.instruction] Customising the header and footer: . Go to *Plugins » Plugin overview*. + → The plugin overview will open. . Click on *Ceres*. + → The plugin will open. . Click on *Configuration* in the directory tree. . Open the *Header* or the *Footer* tab. . Carry out the settings. Pay attention to the information given in <>. . *Save* the settings. [[table-header-footer]] .Customising the header and footer [cols=""1,3""] |==== |Setting |Explanation 2+|Tab: Header | *Position of the navigation bar* |Select a position. The navigation bar will be displayed at the selected position in your plentyShop. + *At the top* = Display the navigation bar at the top of your plentyShop. + *On the left* = Display the navigation bar on the left of your plentyShop. + *At the top and on the left* = Display the navigation bar at the top and on the left of your plentyShop. | *Fix the navigation bar at the top of the page* |Activate to fix the navigation bar at the top in your plentyShop. | *Type of categories rendered in the navigation* |Select the category types to be displayed in the navigation bar. + *All* = Display item and content categories. + *Item* = Only display item categories. + *Content* = Only display content categories. | *Show shopping cart information* |Select the shopping cart information that will be displayed in the header. + *Value of items* = Display the value of items in the shopping cart. *Quantity of items* = Display the quantity of items in the shopping cart. + *Value and quantity of items* = Display the value and quantity of items in the shopping cart. | *Category levels in mega menu* |Select the number of category levels for the mega menu. The mega menu is a navigational element which can simultaneously display multiple levels as a drop-down menu. + *Inactive* = The mega menu is inactive and will not be displayed. + *2* = Categories of the first and second level will be displayed in the mega menu. + *3* = Categories up to the third level will be displayed in the mega menu. + *4* = Categories up to the fourth level will be displayed in the mega menu. | *Number of categories in level 2* |Enter the number of categories to be displayed in the second category level. 30 categories are displayed in the second level by default. Categories will be sorted by position. | *Number of categories in level 3* |Enter the number of categories to be displayed in the third category level. 3 categories are displayed in the third level by default. Categories will be sorted by position. | *Number of categories in level 4* |Enter the number of categories to be displayed in the fourth category level. 2 categories are displayed in the fourth level by default. Categories will be sorted by position. 2+|Tab: Footer | *Position of the Back-to-top button* |Select a position. The *Back-to-top* button will be displayed at the selected position in the online shop. + *On the right at the bottom* = Display the *Back-to-top* button on the right at the bottom. + *In the middle at the bottom* = Display the *Back-to-top* button in the middle at the bottom. | *Number of store features* |Select the number of online store features to be displayed in the footer of your plentyShop. The store features are a great way to highlight the features of your plentyShop, such as free shipping. You can edit the texts of your store features in the *CMS » Multilingualism* menu. + *0* = Do not display any store features. *1* = Only display the first store feature in the footer. *2* = Display the first and the second store feature in the footer. *3* = Display all three store features in the footer. | *Number of columns* |Select the number of columns to be displayed in the footer of your plentyShop. You can edit the names of the columns in the *CMS » Multilingualism* menu. + *1* = Only display the first column in the footer. *2* = Display the first and the second column in the footer. *3* = Display all three columns in the footer. | *List of category IDs to display in first/second/third column* |Enter the IDs of <<#30, categories>> of the type *Content* to be displayed in the first/second/third footer column of your plentyShop. This way, additional information can be displayed in the footer of your plentyShop. + *_Note:_* Multiple IDs must be separated by commas. | *Use PDF cancellation form* |Activate to use an uploaded PDF file as the cancellation form of your plentyShop. Customers can download the cancellation form by clicking the link in the footer of your plentyShop. | *URL to PDF file* |Enter the URL of the cancellation form. The PDF file can be uploaded in the *CMS » Webspace* menu. Alternatively, enter a URL that leads to the cancellation form. |==== [#90] === Customising the item view Customise the design of the item view in the *Item view* tab. Select the item name and item information to be displayed in plentyShop. Furthermore, select which item variations should be displayed in the category view. For further information about saving the displayed texts in plentymarkets, refer to the <> page. [#100.instruction] Customising the item view: . Go to *Plugins » Plugin overview*. + → The plugin overview will open. . Click on *plentyShop LTS*. + → The plugin will open. . Click on *Configuration* in the directory tree. . Click on the *Item view* tab. . Carry out the settings. Pay attention to the information given in <>. . *Save* the settings. [[table-item-view]] .Customising the item view [cols=""1,3""] |==== |Setting |Explanation | *Name of an item to display* |Select the name of an item to display in plentyShop. + *Item name* = Displays the item name. + *Variation name* = Displays the variation name. If no variation name has been saved, the item name will be displayed. + *Item name and variation name* = Displays a combination of item name and variation name. | *Item name* |Select *Name 1*, *Name 2* or *Name 3*. Texts for these fields are saved in the <> tab of the item. If *Name 2* or *Name 3* is selected, but no name was saved in the text field, *Name 1* will be used as the item name. | *Show item information* |Select one, multiple or *ALL* item information options to be displayed in the *More details* tab of the item view in plentyShop. + *Condition* = Activate to display the item condition. + *Manufacturer* = Activate display the item manufacturer. The external name of the manufacturer will be displayed. + *Manufacturing country* = Activate to display the manufacturing country of the item. + *Age rating* = Activate to display the item's age rating. + *Item ID* = Activate to display the item’s ID. + *Technical data* = Activate to display the *Technical data* tab. If you activate the display of *Technical data* without saving a text in the *Technical data* field in the <> tab of an item, the tab will not be displayed. + *Description* = Activate to display the *Description* tab in the item overview in the shopping cart. If you activate the *Description* without saving a text in the *Description* field in the <> tab of an item, the tab will not be displayed. + *Preview text* = Activate to display the preview text of the item. + *Strikethrough price* = Activate to show the strikethrough price next to the item price. + *Variation name* = Activate to display the variation name. + //*Variation number* = Activate to display the variation number. + *External variation ID* = Activate to display the external variation ID. + *Model* = Activate to display the model. + *Dimensions* = Activate to display the item's dimensions. + *Customs tariff number* = Activate to display the customs tariff number. + *Net weight* = Activate to display the net weight. + *Gross weight* = Activate to display the gross weight. + *Content* = Activate to display the item content. | *Store specials: Number of decimal places for discounts* |Select the number of decimal places for discounts to be displayed for an item in the item list. | *Enable selection of variations without stock in variation dropdown* |Activate to display variations that are not in stock in the drop-down list of variations in the category view. Variations without stock can be selected and will not be greyed out. When selecting a variation without stock, the customer will be forwarded to the single item view of this variation. | *Show variations by type* |Display variations by type in the item overview of a category. + *All* = Select to display active main variations and child variations of items. Inactive main variations and child variations will not be displayed. + *Only main variations* = Select to display only main variations. + *Only child variations* = Select to only display active child variations. Active main variations will not be displayed. Child variations of inactive main variations will not be displayed. + *Dynamically* = Select to display variations dynamically. The listed variations include both active main and child variations. The display of variations in the item list is dependent on the selected sorting option in the front end. | *Enable image carousel in category view* |Activate to display the image carousel in the category view. | *Show image carousel dots in category item list* |Activate to display dots below the image carousel of an item in the category view. These serve for orientation in the image carousel. | *Show image carousel navigation in category item list* |Activate to display navigation arrows in the image carousel of an item in the category view. These serve to browse through the carousel images in the front end. | *Loading animation* |Select a loading animation for the category view. + *Blur* = The category view will be blurred for a short period of time when loading. + *Bars* = When loading the category view, a loading animation with bars will be displayed. + *Spinner* = When loading the category view, a loading animation with a spinner will be displayed. | *Activate to display a preview image in the category view.* |Activate to display the preview image in the category view. The preview image can be uploaded in the *Documents* tab of the category and must be set as image 1. | *Show category description in category view* |Activate to display a description of the category in the category view. The description can be entered in the *Description 1* tab of the category. | *Require all order properties before add to basket* |Activate to allow customers to move items to the shopping cart only after all possible order properties have been selected. | *Display categories as filter options for search results* | Activate to use your item categories as filter options for search results. |==== [#110] === Setting up item lists Items can be grouped into item lists and highlighted on the homepage of your plentyShop and in the single item view. The following item lists can be set up in plentyShop LTS: * Store specials: Lists with new items, special offers, etc. are set up in plentyShop LTS via tags. For further information about setting up tags, refer to the <> page of the manual. For further information on tagging items, refer to the <> chapter of the manual. * Cross-selling: Cross-selling items are displayed in plentyShop via *relations*. For further information, refer to the <> chapter of the manual. * Last seen items: A list of the customer’s last seen items is displayed. [#120.instruction] Setting up item lists: . Go to *Plugins » Plugin overview*. + → The plugin overview will open. . Click on *plentyShop LTS*. + → The plugin will open. . Click on *Configuration* in the directory tree. . Click on the *Item lists* tab. . Carry out the settings. Pay attention to the information given in <>. . *Save* the settings. [[table-item-lists]] .Setting up item lists [cols=""1,3""] |==== |Setting |Explanation | *Last seen items: Number of last seen items* |Select the number of last seen items displayed in item lists of this type. | *Cross-selling: Cross-selling relation* |Select the relation for cross-selling items. Items with this relation will be displayed in an item list of the *Cross-selling* type. + *Similar* = The selected items are similar to the opened item. + *Accessory* = The selected items are accessories of the opened item. + *Replacement part* = The selected items are replacement parts for the opened item. + *Collection* = The selected items are suitable to be sold as a bundle together with the current item. | *Cross-selling: Sorting* |Select the <<#191, Sorting option>> that is selected by default for item sorting in the cross-selling item list. | *Tags: Sorting* |Select the <<#191, Sorting option>> that is selected by default for item sorting in the item list of the tag type. | *First/second/third item list* |Select the type of the item list. You can edit the names of the item lists in the *CMS » Multilingualism* menu. + *Last seen items* = A list of last seen items is displayed in plentyShop. + *Cross-selling* = A list of cross-selling items with the selected relation is displayed in plentyShop. + *Tags* = A list of items with the linked tags is displayed in plentyShop. | *List of IDs of tags for the first/second/third item list* | Enter the IDs of tags. Items linked to these tags will be displayed in the item list of the *Tags* type.+ *_Note:_* Multiple IDs must be separated by commas. |==== Display item lists in a very convenient way in your plentyShop by linking them to *template containers*. Proceed as follows to link the *item list for last seen items* in the single item view of your plentyShop. Link other item lists in the same way. [#130.instruction] Linking an item list: include::../plugins/_textblocks/instructions/plugin-container-verknuepfung-en_gb.adoc[menu-path] . From the drop-down list, select the option *First item list*. + → The type *Last seen* is selected for the first item list by default. . Select one or multiple containers in which you want to display your item list, e.g. *Homepage: Container 7*, *Homepage: Container 9* or *Single item: Container for item lists*. . *Save* the settings. + → The item list will be displayed in the selected containers in plentyShop. Please find a complete list and explanation of the available template containers in our english link:https://developers.plentymarkets.com/dev-doc/template-containers[developers documentation^]{nbsp}icon:external-link[]. This documentation is primarily targeted at experienced users and is not necessary for the basic setup of Ceres. [#140] === Customising the shopping cart Customise the display options of the shopping cart in the *Shopping cart* tab. Select item and price information to be displayed in the shopping cart and customise the shopping cart preview. [#150.instruction] Customising the shopping cart: . Go to *Plugins » Plugin overview*. + → The plugin overview will open. . Click on *plentyShop LTS*. + → The plugin will open. . Click on *Configuration* in the directory tree. . Click on the *Shopping cart* tab. . Carry out the settings. Pay attention to the information given in <>. . *Save* the settings. [[table-customise-shopping-cart]] .Customising the shopping cart [cols=""1,3""] |==== |Setting |Explanation | *Show item information* |Select one, multiple or *ALL* item information options to be displayed in the item overview in the shopping cart store. + *Item ID* = Activate to display the item's ID. + *Item text* = Activate to display the item description. If you activate the *Item text* without saving a text in the *Item text* field in the <> tab of an item, the item description will not be displayed. + *Preview text* = Activate to display the preview text of the item. + *Availability* = Activate to display the item’s availability. *Variation number* = Activate to display the variation number. + *Condition* = Activate to display the item’s condition. | *Display the change variation button* |Activate to display the *Change variation* button in the item overview in the shopping cart. By clicking the *Change variation* button, customers can change an item's variation directly in the shopping cart. If you activate the *Change variation* button, even though the item has no variations, the button will not be displayed. | *Add to shopping cart: Show information* |Select whether to show the overlay of the shopping cart, toggle the shopping cart preview or display no information after clicking on the *Add to shopping cart* button. + | *Type of shopping cart preview* |Select whether the shopping cart preview is displayed on the right or toggled by mouse-over over the shopping cart symbol. + | *Show shipping country selection* |Activate to display the selection of the shipping country in the shopping cart. The selection is displayed as a drop-down list. This option is activated by default. |==== [#190] === Customising the pagination and sorting Customise the pagination, meaning the numbering of pages, of the item overview and plentyShop's item sorting in the *Pagination and sorting* tab. [#200.instruction] Customising the pagination and sorting: . Go to *Plugins » Plugin overview*. + → The plugin overview will open. . Click on *plentyShop LTS*. + → The plugin will open. . Click on *Configuration* in the directory tree. . Click on the *Pagination and sorting* tab. . Carry out the settings. Pay attention to the information given in <>. . *Save* the settings. [[table-pagination-sorting]] .Customising the pagination and sorting [cols=""1,3""] |==== |Setting |Explanation | *Position of the pagination* | Select whether the pagination is displayed above, below or above and below the item list. + | *Always show first page* |Activate to always display the first page in the pagination. | *Always show last page* |Activate to always display the last page in the pagination. | *Number of columns per page* |Enter the number of columns per page. This number is used for calculating the values in the *Items per page* drop-down list. | *Rows per page* |Activate one, multiple or all number values. The activated values are multiplied with the number of columns and displayed in the *Items per page* drop-down list in the item overview. | *SEO: Set the value nindex beginning at page* |Enter the page number, at which search engines stop indexing search results. | *Enable item sorting by* |Activate one, several or *ALL* <<#191, sorting options>> for item sorting. + | *Default sorting value for category view* |Select the <<#191, Sorting option>> that is selected by default for item sorting in the category view. | *Recommended item sorting: First/second/third sorting option* |Select the <<#191, Sorting option>> for the recommended item sorting in the category view. Up to three sorting options can be concatenated, the first of which assumes the highest priority. + | *Default sorting option for item search results* |Select the <<#191, Sorting option>> that is selected by default for the sorting of item search results. | *Recommended search results: First/second/third sorting option* |Select the <<#191, Sorting option>> for the recommended sorting of item search results. Up to three sorting options can be concatenated for the item serach, the first of which assumes the highest priority. + | *Forward to single item view* |Activate to forward cutomers to the single item view when clicking search results. |[#191]*Sorting options* | *Not selected* = Select no value. + *Item ID ⬆* = Display items by item ID in ascending order. + *Item ID ⬇* = Display items by item ID in descending order. + *Item name A-Z* = Display items in alphabetical order by item name (A-Z). + *Item name Z-A* = Display items in alphabetical order by item name (Z-A). + *Price ⬆* = Display items by price in ascending order. + *Price ⬇* = Display items by price in descending order. + *Newest variation* = Display the newest item variations first. + *Oldest variation* = Display the oldest item variations first. + *Variation ID ⬆* = Display item variations by variation ID in ascending order. + *Variation ID ⬇* = Display item variations by variation ID in descending order. + *Variation number ⬆* = Display item variations by variation number in ascending order. + *Variation number ⬇* = Display item variations by variation number in descending order. + *Availability ⬆* = Display item variations by availability in ascending order. + *Availability ⬇* = Display item variations by availability in descending order. + *Last update* = Display the last updated item variation first. + *First update* = Display the first updated item variation first. + //*Variation name A-Z* = Display item variation in alphabetical order by variation name (A-Z). + //*Variation name (Z-A)* = Display item variation in reversed alphabetical order by variation name (Z-A). + *Variation position ⬆* = Display item variation by position number in descending order* *Variation position ⬇* = Display item variation by position number in ascending order. *_Important:_* In order for this function to work, a position number has to be saved for each of the item variations within the variation tab. + //*Active variation ⬆* = Display active item variations in ascending order. + //*Active variation ⬇* = Display active item variations in descending order. + //*Main variation ⬆* = Display main item variations in ascending order. + //*Main variation ⬆* = Display main item variations in descending order. + *Manufacturer A-Z* = Display items in alphabetical order by manufacturer. + *Manufacturer Z-A* = Display items in inverted alphabetical order by manufacturer. + *Manufacturer position ⬆* = Display items by manufacturer position in ascending order. + *Manufacturer position ⬇* = Display items by manufacturer position in descending order. + *Stock ⬆* = Display items by stock in ascending order. + *Stock ⬇* = Display items by stock in descending order.+ *Random* = Display items in random order. |==== [#160] === Customising the checkout and the My account area Customise the display options of the checkout in the *Checkout and My account* tab. Select the fields to be displayed and validated in the address form. Here, you also set up the *My account* area and returns for your plentyShop. Returns will be displayed in the return history and can be processed in the *My account* area of plentyShop. [#170.instruction] Customising the My account area: . Go to *Plugins » Plugin overview*. + → The plugin overview will open. . Click on *plentyShop LTS*. + → The plugin will open. . Click on *Configuration* in the directory tree. . Click on the *Checkout and My account* tab. . Carry out the settings. Pay attention to the information given in <>. . *Save* the settings. [[table-my-account]] .Customising the My account area [cols=""1,3""] |==== |Setting |Explanation | *Number of orders per page in order history* |Enter the number of orders to be displayed per page in the order history. | *Allow returns in My account* |Activate to allow customers to return items in the order history of the *My account* area in plentyShop. | *Number of days to return items of an order* |Enter the number of days to return items of an order. Customers will be able to return items of an order within this time period. This time period begins when the order is created. After the specified time period, the *Return items* button will be hidden in the order history in the *My Account* area of plentyShop. Customers will not be able to return items of an order after this time period. | *Default status for returns* |Enter the default status for returns. For further information about order statuses, refer to <>. | *Allow customers to change the payment method* |Activate to allow customers to change the payment method after the checkout. If deactivated, any change is impossible. + *_Note:_* This setting is selected by default. | *Forward to login page after clicking link in order confirmation* |Activate to forward registered customers to the login page after clicking the link in the order confirmation. After logging in successfully the order confirmation page will be displayed. + *_Note:_* Customers ordering as a guest are not affected by this setting. Guests will be directly forwarded to the order confirmation page. |==== [#180.instruction] Customising the checkout: . Go to *Plugins » Plugin overview*. + → The plugin overview will open. . Click on *plentyShop LTS*. + → The plugin will open. . Click on *Configuration* in the directory tree. . Click on the *Checkout and My account* tab. . Carry out the settings. Pay attention to the information given in <>. . *Save* the settings. [[table-customise-checkout]] .Customising the checkout [cols=""1,3""] |==== |Setting |Explanation | *Show invoice address fields in address form (DE)* |Select one, multiple or *ALL* <<#181, address fields>> to be displayed in the address form for the country of delivery *Germany* of the checkout. + | *Enable invoice address field validation (DE)* |Select one, multiple or *ALL* <<#181, address fields>> to validate these fields when entering the address. + | *Show delivery address fields in address form (DE)* |Select one, multiple or *ALL* <<#181, address fields>> to be displayed in the address form for the country of delivery *Germany* of the checkout. + | *Enable delivery address field validation (DE)* |Select one, multiple or *ALL* <<#181, address fields>> to validate these fields when entering the address. + | *Show invoice address fields in address form (UK)* |Select one, multiple or *ALL* <<#181, address fields>> to be displayed in the address form for the country of delivery *United Kingdom* of the checkout. + | *Enable invoice address field validation (UK)* |Select one, multiple or *ALL* <<#181, address fields>> to validate these fields when entering the address. + | *Show delivery address fields in address form (UK)* |Select one, multiple or *ALL* <<#181, address fields>> to be displayed in the address form for the country of delivery *United Kingdom* of the checkout. + | *Enable delivery address field validation (UK)* |Select one, multiple or *ALL* <<#181, address fields>> to validate these fields when entering the address. + |[#181]*Address fields* | *Company* + *VAT number* + *Form of address* + *Title* + *Date of birth* + *Name affix* + *Phone* + *Additional address 1* + *Additional address 2* + *State* + *Address 2* + *Address 3* + *Address 4* + //*County* = Activate to display the field *County*. |==== [#220] === Setting up languages Carry out language settings in the *Languages* tab. By default plentyShop is available in German, English, French, Dutch, and Polish. Select these languages in the header area of your plentyShop. *plentyShop LTS* supports all plentymarkets system languages. You can <<#231, translate>> your plentyShop and your items into other languages. [#230.instruction] Setting up plentyShop languages: . Go to *Plugins » Plugin overview*. + → The plugin overview will open. . Click on *plentyShop LTS*. + → The plugin will open. . Click on *Configuration* in the directory tree. . Click on the *Language* tab. . Activate additional languages under *Active languages*. . *Save* the settings. + → The selected languages will be displayed in the language selection of your plentyShop. [#201] === Carrying out currency settings In the *Currencies* tab, you carry out settings for the availability and display of currencies in your plentyShop. Here, you specify, e.g. whether your customers are allowed to change the currency in the plentyShop. You also activate the available currencies and determine how these currencies are displayed. [#202.instruction] Carrying out currency settings: . Go to *Plugins » Plugin overview*. + → The plugin overview will open. . Click on *plentyShop LTS*. + → The plugin will open. . Click on *Configuration* in the directory tree. . Click on the *Currencies* tab. . Carry out the settings. Pay attention to the information given in <>. . *Save* the settings. [[table-currency-settings]] .Carrying out currency settings [cols=""1,3""] |==== |Setting |Explanation | *Format of currencies* |Select the format of currencies. The selected currency format will be used globally in plentyShop. + *ISO code* = Display the currency as ISO code in plentyShop. For the currency Euro the ISO code *EUR* will be displayed. + *Symbol* = Display currency as a symbol in plentyShop. For the currency Euro the symbol *€* will be displayed. | *Allow customer to change the currency* |Activate to allow customers to select a different currency in the header of plentyShop. Select the available currencies below. | *Format of currencies in header* |Select the format of currencies for the header. + *ISO code and symbol* = Display the currency as ISO code in the header. + *Symbol* = Display currency as a symbol in the header. + *ISO code and symbol* = Display currency as ISO code and symbol in the header. The currency symbol will be displayed in brackets next to the ISO code. | *Available currencies* |Activate currencies available to customers in the header of plentyShop. For further information about supported currencies, refer to the <> manual page. |==== [#203] === Carrying out settings for search engine optimisation In the *SEO* tab you carry out settings for optimising your plentyShop for search engines. Enter a meta description for the static pages of your plentyShop, for example, and control access to your plentyShop pages by robots. [#204.instruction] Carrying out settings for search engine optimisation: . Go to *Plugins » Plugin overview*. + → The plugin overview will open. . Click on *plentyShop LTS*. + → The plugin will open. . Click on *Configuration* in the directory tree. . Click on the *SEO* tab. . Carry out the settings. Pay attention to the information given in <>. . *Save* the settings. [[table-seo-settings]] .Carrying out settings for search engine optimisation [cols=""1,3""] |==== |Setting |Explanation | *Robots for homepage* |Select *All*, *index*, *nofollow*, *noindex* or *nofollow, noindex* to control access to the homepage of your online store by robots. Values of the meta element Robots are analysed by search engine crawlers. These values tell the crawler how to deal with the page and any links on that page. + *All* = Include the homepage of your plentyShop in the search engine index and follow links on the page. + *index* = Include in the search engine index. + *nofollow* = Do not follow links on the page. + *noindex* = Do not include in the search engine index. + *Nofollow, noindex* = Do not follow links and do not include the homepage of your plentyShop in the search enginge index. | *Specify availabilities for search engines* |This setting provides a mapping with which the availabilites set in the *Setup » Item » Availability* menu can be mapped onto the Schema.org availabilites. This serves to improve SEO omptimisation. | *Select source for the brand in Rich Snippets of the item page* |With this setting you can determine if you want to provide the *brand* of an item as a Rich Snippet to search engines. + *Do not display* = The brand is not provided as a Rich Snippet. + *External name of the manufacturer* = The **external name** of the manufacturer linked to the item is provided as a Rich Snippet. + *Use brand name from variation property of the type short text* = You can use a property of the type ""short text"" to define a brand name you want to provide as a Rich Snippet. If you select this option, enter the ID of the property in the subsequent field *Take ID from variation property of the type short text*. |*Select source for the manufacturer in Rich Snippets of the item page* |With this setting you can determine if you want to provide the *manufacturer* of an item as a Rich Snippet to search engines. + *Do not display* = The manufacturer is not provided as a Rich Snippet. + *External name of the manufacturer* = The **external name** of the manufacturer linked to the item is provided as a Rich Snippet. + *Name of the manufacturer* = The **name** of the manufacturer linked to the item is provided as a Rich Snippet. + |*Select source for GTIN barcode in Rich Snippets of the item page* |With this setting you can determine if you want to provide the *GTIN barcode* of an item as a Rich Snippet to search engines. + *Do not display* = The GTIN barcode is not provided as a Rich Snippet. + *Take specific GTIN barcode by ID* = Select this option and enter an ID of a GTIN barcode you created in the *Setup » Item » Barcodes* menu in the following input field *Take ID from variation barcode* to provide this barcode as a Rich Snippet. + *Take first GTIN from variation barcode* = Select this option to provide the variation's GTIN barcode that is listed first as a Rich Snippet. + |*Select source for GTIN-8 barcode in Rich Snippets of the item page* |With this setting you can determine if you want to provide the *GTIN-8 barcode* of an item as a Rich Snippet to search engines. + *Do not display* = The GTIN-8 barcode is not provided as a Rich Snippet. + *Take specific GTIN-8 barcode by ID* = Select this option and enter an ID of a GTIN-8 barcode you created in the *Setup » Item » Barcodes* menu in the following input field *Take ID from variation barcode* to provide this barcode as a Rich Snippet. + *Take first GTIN from variation barcode* = Select this option to provide the variation's GTIN-8 barcode that is listed first as a Rich Snippet. + |*Select source for GTIN-13 barcode in Rich Snippets of the item page* |With this setting you can determine if you want to provide the *GTIN-13 barcode* of an item as a Rich Snippet to search engines. + *Do not display* = The GTIN-13 barcode is not provided as a Rich Snippet. + *Take specific GTIN-13 barcode by ID* = Select this option and enter an ID of a GTIN-13 barcode you created in the *Setup » Item » Barcodes* menu in the following input field *Take ID from variation barcode* to provide this barcode as a Rich Snippet. + *Take first GTIN from variation barcode* = Select this option to provide the variation's GTIN-13 barcode that is listed first as a Rich Snippet. + |*Select source for ISBN barcode in Rich Snippets of the item page* |With this setting you can determine if you want to provide the *ISBN barcode* of an item as a Rich Snippet to search engines. + *Do not display* = The ISBN barcode is not provided as a Rich Snippet. + *Take specific ISBN barcode by ID* = Select this option and enter an ID of an ISBN barcode you created in the *Setup » Item » Barcodes* menu in the following input field *isbnID* to provide this barcode as a Rich Snippet. + *Take first GTIN from variation barcode* = Select this option to provide the variation's ISBN barcode that is listed first as a Rich Snippet. + |*Select source for MPN barcode in Rich Snippets of the item page* |With this setting you can determine if you want to provide the *MPN barcode* of an item as a Rich Snippet to search engines. + *Do not display* = The MPN barcode is not provided as a Rich Snippet. + *Show external variation ID* = The external variation ID is provided as a Rich Snippet. + *Use MPN from variation property of the type short text* = You can use a property of the type ""short text"" to define an MPN barcode you want to provide as a Rich Snippet. If you select this option, enter the ID of the property in the subsequent field *Take ID from variation property of the type short text*. |*Select source for price validity in Rich Snippets of the item page* |*Take ID from variation property of the type short text or date*: You can use a property of the type ""short text"" or ""date"" to define the prive vailidty you want to provide as a Rich Snippet. Enter the ID of the property in the field *Take ID from variation property of the type short text or date*. |*skuMapping* |With this setting you can determine if you want to provide the *SKU* (Stock Keeping Unit) of an item as a Rich Snippet to search engines. + *Use variation ID* = Die ID der Variante wird als Rich Snippet weitergeben. + *Use variation number* = Die Nummer der Variante wird als Rich Snippet weitergeben. + *Use SKU from variation property of the type short text* = You can use a property of the type ""short text"" to define a SKU you want to provide as a Rich Snippet. If you select this option, enter the ID of the property in the subsequent field *Take ID from variation property of the type short text*. |==== In the *CMS » Multilingualism* menu, you can enter meta descriptions for the static pages of your plentyShop. Carry out the SEO settings for the *contact page* as well as the pages *cancellation rights*, *cancellation form*, *legal disclosure*, *privacy policy* and *terms and conditions* in the same way. [#2040] ==== Editing trailing slashes You can carry out settings pertaining to trailing slashes of the URLs of your plentyShop in the *Setup » Client » Select client » SEO » URL structure* menu. [#2041.instruction] Editing trailing slashes: . Go to *Setup » Client » Select client » SEO » URL structure » Other*. . Select the desired option from the *Trailing slash* drop-down list. . *Save* the settings. If you select *Do not change*, the URLs of your plentyShop will remain accessible with and without an appended trailing slash. The option *Always remove* removes all trailing slashes from your URLs. The option *Always append* will equip all of your URLs with a trailing slash. [NOTE] ==== This feature is currently in its beta phase. Changing this setting may initially have negative effects on the SEO ranking of your plentyShop. ==== [#205] === Carrying out settings for the design of your plentyShop In the *Design* tab you carry out design settings for your plentyShop. Here you can set the colour schemes for buttons and notifications in your plentyShop. [#206.instruction] Carrying out settings for the design of your plentyShop: . Go to *Plugins » Plugin overview*. + → The plugin overview will open. . Click on *plentyShop LTS*. + → The plugin will open. . Click on *Configuration* in the directory tree. . Click on the *Design* tab. . Carry out the settings. Pay attention to the information given in <>. . *Save* the settings. [[table-design-settings]] .Carrying out design settings [cols=""1,3""] |==== |Setting |Explanation | *Primary colour* | Select the primary colour of your plentyShop. This determines the colouring of the buttons in your plentyShop. Enter the hex value of the colour you want to use into the input field. | *Secondary colour* | Select the secondary colour of your plentyShop. This determines the colouring of the category preview. Enter the hex value of the colour you want to use into the input field. | *Success colour* | Select the colour for success notifications in your plentyShop. Enter the hex value of the colour you want to use into the input field. | *Information colour* | Select the colour for information notifications in your plentyShop. Enter the hex value of the colour you want to use into the input field. | *Warning colour* | Select the colour for warning notifications in your plentyShop. Enter the hex value of the colour you want to use into the input field. | *Danger colour* | Select the colour for danger notifications in your plentyShop. Enter the hex value of the colour you want to use into the input field. |==== [NOTE] .Deploying the plugin set again ==== Please note that changes to the design settings necessitate that you deploy the plugin set again before the changes can be displayed in plentyShop. ==== [#207] === Settings for plugin developers Settings specifically targeted at plugin developers are available in the *Logging and performance* tab. Here, you can set the information to be logged during plugin development and the performance mode for plentyShop. [#210.instruction] Carrying out settings for plugin development: . Go to *Plugins » Plugin overview*. + → The plugin overview will open. . Click on *plentyShop LTS*. + → The plugin will open. . Click on *Configuration* in the directory tree. . Click on the *Logging and performance* tab. . Carry out the settings. Pay attention to the information given in <>. . *Save* the settings. [[table-plugin-development]] .Carrying out settings for plugin development [cols=""1,3""] |==== |Setting |Explanation | *Activate logging options* |Activate one, multiple or *ALL* logging options. + *Print errors* = Print error messages in plentyShop. + *Print success* = Display success messages in plentyShop. + *Print warnings* = Display warnings in plentyShop. + *Print information* =Display information in plentyShop. + *Print stack trace* = Display the stack trace. + *Log messages* = Log messages. + *Show error codes* = Display error codes. | *Performance level* |Select a performance level. + *Live* = Select the live mode when using plentyShop as a productive system. Files will be minified and bundled. + *Development* = Select the development mode to use debugging functionality. Files will not be minified and bundled. |==== == Carry out additional settings The following chapters cover shop-relevant settings that you cannot carry out via the plentyShop LTS configuration. This includes the <<#321, Editing of plentyShop texts>>, the setup of <<#330, Filters>> and <<#340, Order properties>>. [#231] === Editing plentyShop texts You can manage language-dependent texts of your plentyShop, such as the name of your plentyShop or SEO-relevant meta descriptions, in the *CMS » Multilingualism* menu. Select the *plugin set* for which you want to edit text elements from the drop-down list on the left. Select a *Source language* on the left side of the bilingual view and a *Target language* on the right side of the bilingual view. Here you can import and export language files, add new languages, edit individual text elements or reset translations to the default value. The language entries of each plugin are grouped together and are categorised in *sections*. The individual sections can be expanded and collapsed via the arrow on the right. + In order to display the edited texts in plentyShop, the selected language has to be set to <<#220, active>>. It is possible that certain entries of the source language, such as brand names, are *locked* for translation. [IMPORTANT] .Deploying the plugin set ==== In order to display the translated entries in plentyShop, you have to deploy the plugin set via the *Save & Publish plugin set* button after you have modified the language files. ==== [#232.instruction] Adding a language for your plentyShop: - Go to *CMS » Multilingualism*. + → The bilingual view opens. - Select a target language for which no translations have been saved from the target language drop-down list. + → The language will be added. - *Save* the settings. [#233.instruction] Editing individual text elements of plentyShop languages: . Go to *CMS » Multilingualism*. + → The bilingual view opens. . Select the *Source language* from the drop-down list on the left side. . Select the *Target language* from the drop-down list on the right side. . Click on an input field of the *target language* to edit a text element. . Enter the text. . *Save* the settings. You can export the language file so that an external translation agency can prepare translations for your plentyShop. You can import the translations via the *Import*button in the target language area. The files are imported and exported in CSV format. When you *export* a language file, the translations are collated into a single file, even if the language data comprises multiple plugins. [#234.instruction] Exporting language files: . Go to *CMS » Multilingualism*. + → The bilingual view opens. . Click on *Export* next to the drop-down list of the source language. + → The language data is exported as a CSV file. [#235.instruction] Importing language files: . Go to *CMS » Multilingualism*. + → The bilingual view opens. . Select a target language for which you want to import translations from the drop-down list on the right side. . Click on the *Import* button next to the drop-down list. . Select the CSV file you want to import. + → If no translations have been saved for the selected target language, the language is added and the edited texts are saved. + → If translations have been saved for the selected language, you are required to confirm that the import overwrites any existing translations. . Confirm the import. . *Save* the settings. [NOTE] ==== If the imported file contains additional entries that were not included in the language file of the source language, a notification will open. This will inform you that the import has been successful, but the additional entries will be ignored. ==== You can *reset* the changes to the default values at any time. If a plugin does not include translations for the selected language, resetting the values will delete them. If a plugin includes translations for the selected language, these constitute the default values. [#236.instruction] Resetting translations to their default values: . Go to *CMS » Multilingualism*. + → The bilingual view opens. . Click on *Reset* on the right side of an input field of the target language. + → The value is reset. . If you want to reset all translations of the target language, click on *Reset* next to the drop-down list of the target language. + → A notification opens. . Confirm that all translations of the target language are reset to their default values. + → All values of the target language are reset. . *Save* the settings. [#330] === Setting up filters Set up the filters for the search and category view of *plentyShop LTS* with the help of facets of the *Attribute/property* type. Set up attributes and properties first and link them with your items. Set up the filters for the search and category view of plentyShop LTS with the help of facets of the Attribute/property type. Set up attributes and properties first and link them with your items. For further information about *attributes*, refer to the <> chapter. For further information about *properties*, refer to the <> chapter. Then, create facets for your attributes and properties. For further information about *facets*, refer to the <> chapter. You can find detailed instructions about setting up filters in our <>. [#340] === Setting up order characteristics With order properties, you allow your customers to enter a text when ordering an item that is linked to the order characteristic. For example, customers choose an individual text that will be printed on an item. Set up order characteristics first and link the characteristics with your items. For further information about characteristics, refer to the <> chapter. You can find detailed instructions about setting up order characteristics in our <>. [#650] === Automatically sending order confirmations Set up an <> to automatically send your customers an order confirmation. [.collapseBox] .Setting up an event procedure -- . Go to *Setup » Orders » Events*. . Click on *Add event procedure*. + → The *Create new event procedure* window opens. . Enter a name. . Select the *event* listed in <> below. . *Save* the settings. . Configure the settings as described in <>. . Place a check mark next to the option *Active*. . *Save* the settings. -- [[table-automatic-order-confirmation]] .Event procedure for automatically sending order confirmations [cols=""1,3,3""] |==== | Setting | Option | Selection | *Event* | *Order generation: New order* | | *Procedure*| *Customer > Send email* |Email template *Online store: Confirmation of store order*; + *Select customer* |==== [#700] === Final check [%interactive] * [] Did you purchase, install and deploy the necessary plugins and did you assign position numbers to the plugins? * [] Did you set up a default country of delivery, a default shipping method and a default shipping profile? * [] Did you set up and deploy a payment plugin and set it up as the default payment method? * [] Did you prepare your legal texts? * [] Did you enter the content of your content categories (e.g. for displaying shipping information) in the *Template* tab of the category? * [] Did you deactivate the plentyShop LTS default homepage and activate the ShopBuilder homepage? * [] Did you carry out all settings for every tab of the plentyShop LTS configuration? * [] Did you prepare your plentyShop texts in multiple languages (if applicable)? * [] Did you set up filters and order properties? * [] Did you set up an event procedure for automatically sending order confirmations? * [] Did you unlock your shop? * [] Did you save and deploy the plugin set after making changes to the plugins? [#900] == Certifying your plentyShop plentyShop LTS with Trusted Shops [[image-trusted-shops]] .Trusted Shops Certified Software image::omni-channel/online-shop/assets/DE-Ceres-einrichten-eTrusted-Partner-Certified-Software.png[] You want to certify your plentyShop with Trusted Shops? plentyShop LTS has been pre-certified by Trusted Shops, so your Trusted Shops certification will be handled as fast and easy as possible. Find all necessary information link:https://www.trustedshops.de/shopbetreiber/bestellen.html?shopsoftware=PLENTYMARKETS[here^]{nbsp}icon:external-link[]. [#960] == Activating the ShopBooster link:https://www.plentymarkets.eu/blog/Volle-Kraft-voraus-ShopBooster-bringt-deinen-Ceres-Shop-auf-Hochtouren/b-2125/[ShopBooster^]{nbsp}icon:external-link[] is an additional module, via which online shop content of plentyShops are written into the cache in order to achieve better loading times. The ShopBooster is available for Ceres versions 2.14 and higher. [IMPORTANT] .Additional costs ==== Activating the ShopBooster entails additional costs in the amount of 0,004€ per 100 page accesses and changes (per client). A page access is the process in which a visitor or web crawler accesses a URL of your online shop; a page change is effected by one of the following processes: - Updating category of item data - Updating ShopBuilder pages - Saving and deploying plugin sets - Saving settings in the plentyShop LTS configuration - Invalidating the cache by deactivating the ShopBooster The additional costs of the ShopBooster module amount to a *maximum* of 100 € per month per client. ==== [.instruction] Activating the ShopBooster: . Go to the *Setup » Client » Select client» Webshop » ShopBooster* menu. - Click on *Activate ShopBooster* + → A window is opened, informing you about additional costs. . Click on *Confirm* to activate the ShopBooster. + → The message *ShopBooster has been activated* is displayed. You can deactivate the ShopBooster in the same way. [.instruction] Deactivating the ShopBooster: . Go to the *Setup » Client » Select client» Webshop » ShopBooster* menu. - Click on *Deactivate ShopBooster* + → A window is opened, informing you about additional costs. . Click on *Confirm* to deactivate the ShopBooster. + → The message *ShopBooster has been deactivated* is displayed. === Deactivating the invalidation In the *Deactivate invalidation*, you can suspend the invalidation of the ShopBooster until the chosen date and time. As a result, your item data will be exclusively loaded from the cache until the chosen time, without the cache being deleted or updated. Therefore, your plentyShop will be able to achieve better loading times. + Note that deactivating the invalidation will also affect the visibility of items in your online shop: The visibility of your items will no longer be automatically updated as long as the invalidation is inactive; it is therefore possible, that items appear as available even though they are already sold out. However, it is not possible for your customers to purchase items that are not available. + [.instruction] Deactivate the invalidation: . Go to the *Setup » Client » Select client» Webshop » ShopBooster* menu. . Enter the date until which you want to deactivate the invalidation. . Enter the time until which you want to deactivate the invalidation. . *Save* your inputs. [#1000] == Customising plentyShop LTS Various possibilities are available to customise the *plentyShop LTS* template plugin and tailor it to meet your needs. [#1100] === Creating an individual template *plentyShop LTS* is a public project and available on link:https://github.com/plentymarkets/plugin-ceres[GitHub]{nbsp}icon:external-link[]. You can use the plugin code to create your own template plugin. Please note the following when creating your own template on the basis of *plentyShop LTS*: * Register with link:https://github.com/join?source=header-home[GitHub^]{nbsp}icon:external-link[] * Open the link:https://github.com/plentymarkets/plugin-ceres[plentyShop LTS project^]{nbsp}icon:external-link[] * Create your own fork of the project * Customise the source code For further information about changing the source code, refer to our link:https://developers.plentymarkets.com/dev-doc/template-plugins[template guide^]{nbsp}icon:external-link[]. [WARNING] .Updating fork ==== Note that you have to update your template manually if you want to use features of a newer version of the *plentyShop LTS* plugin. Automatic plugin updates are only available for plugins purchased on plentyMarketplace. ==== [#1200] === Purchasing a theme on plentyMarketplace Theme plugins are an easy way of customising the looks of *plentyShop LTS*. Various link:https://marketplace.plentymarkets.com/plugins/themes[themes^]{nbsp}icon:external-link[] for *plentyShop LTS* are available on plentyMarketplace. Changes made to the theme plugin have no impact on future updates of the template plugin *plentyShop LTS*. [#1300] === Creating an individual theme Learn how to create your own theme plugin and how to fully customise *plentyShop LTS* in our link:https://developers.plentymarkets.com/dev-doc/theme-plugins[theme guide^]{nbsp}icon:external-link[]. [#1400] === Integrating additional plugins In addition to theme plugins, which serve to modify the design of plentyShop, the link:https://marketplace.plentymarkets.com/[marketplace^] offers a multitude of different plugins which can be used to tailor the functionality of plentyShop to your personal needs. Apart from the integration of link:https://marketplace.plentymarkets.com/plugins/markets[marketplaces^], you can find link:https://marketplace.plentymarkets.com/plugins/widgets[widgets^], such as the GoogleAnalytics and customer feedback plugins, link:https://marketplace.plentymarkets.com/plugins/payment[payment plugins^] for the implementation of additional payment methods and link:https://marketplace.plentymarkets.com/plugins/integration[integration plugins]{nbsp}icon:external-link[], such as the plugins of shipping providers DHL and DPD. + Proceed as described below to purchase and install a plugin: [.instruction] Purchasing a plugin: . Open the link:http://marketplace.plentymarkets.com/de/[plentyMarketplace^]{nbsp}icon:external-link[]. . Click on *Sign in*. . Enter your email adress or your plentyId. + → Use your account information from the service centre. . Enter your password. . Click on **Sign in**. . Select a plugin from a category. . Click on **Purchase plugin** in the detail view of the plugin. + → The **Checkout** window opens. . Accept the terms and conditions. . Click on **Order now**. + → The purchased plugin is now available in the **Plugins » Plugin overview** menu. After you have purchased the plugins, you have to *install* and *activate* the plugins in a plugin set. [.instruction] Installing a plugin: . Go to *Plugins » Plugin overview*. . Select a *Plugin set*. . Activate the filter checkbox *Not installed*. . Click on *Search*. → All uninstalled plugins are listed. . For the plugin you want to install, click on *Install plugin* in the *Action* column. + → The *Install plugin* window opens. . Select the *Version to be installed* and click on *Install*. → The plugin will be installed. After you have installed the plugin, you need to activate it in a plugin set. [.instruction] Activating a plugin: . Go to *Plugins » Plugin overview*. . In the line of the plugin you want to activate, click on the globe button in the *Active* column. + → The globe icon changes to blue. The plugin is now activated. . Click on *Save & publish plugins*. ",16260,True,3076.6691712262436,median "------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Ada Modeling Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2011-2012, Vadim Godunko -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- ""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 COPYRIGHT -- -- HOLDER 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. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with AMF.Elements; with AMF.Internals.Element_Collections; with AMF.Internals.Helpers; with AMF.Internals.Tables.UML_Attributes; with AMF.Visitors.UML_Iterators; with AMF.Visitors.UML_Visitors; with League.Strings.Internals; with Matreshka.Internals.Strings; package body AMF.Internals.UML_Association_Classes is ------------------- -- Enter_Element -- ------------------- overriding procedure Enter_Element (Self : not null access constant UML_Association_Class_Proxy; Visitor : in out AMF.Visitors.Abstract_Visitor'Class; Control : in out AMF.Visitors.Traverse_Control) is begin if Visitor in AMF.Visitors.UML_Visitors.UML_Visitor'Class then AMF.Visitors.UML_Visitors.UML_Visitor'Class (Visitor).Enter_Association_Class (AMF.UML.Association_Classes.UML_Association_Class_Access (Self), Control); end if; end Enter_Element; ------------------- -- Leave_Element -- ------------------- overriding procedure Leave_Element (Self : not null access constant UML_Association_Class_Proxy; Visitor : in out AMF.Visitors.Abstract_Visitor'Class; Control : in out AMF.Visitors.Traverse_Control) is begin if Visitor in AMF.Visitors.UML_Visitors.UML_Visitor'Class then AMF.Visitors.UML_Visitors.UML_Visitor'Class (Visitor).Leave_Association_Class (AMF.UML.Association_Classes.UML_Association_Class_Access (Self), Control); end if; end Leave_Element; ------------------- -- Visit_Element -- ------------------- overriding procedure Visit_Element (Self : not null access constant UML_Association_Class_Proxy; Iterator : in out AMF.Visitors.Abstract_Iterator'Class; Visitor : in out AMF.Visitors.Abstract_Visitor'Class; Control : in out AMF.Visitors.Traverse_Control) is begin if Iterator in AMF.Visitors.UML_Iterators.UML_Iterator'Class then AMF.Visitors.UML_Iterators.UML_Iterator'Class (Iterator).Visit_Association_Class (Visitor, AMF.UML.Association_Classes.UML_Association_Class_Access (Self), Control); end if; end Visit_Element; ------------------ -- Get_End_Type -- ------------------ overriding function Get_End_Type (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Types.Collections.Ordered_Set_Of_UML_Type is begin return AMF.UML.Types.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_End_Type (Self.Element))); end Get_End_Type; -------------------- -- Get_Is_Derived -- -------------------- overriding function Get_Is_Derived (Self : not null access constant UML_Association_Class_Proxy) return Boolean is begin return AMF.Internals.Tables.UML_Attributes.Internal_Get_Is_Derived (Self.Element); end Get_Is_Derived; -------------------- -- Set_Is_Derived -- -------------------- overriding procedure Set_Is_Derived (Self : not null access UML_Association_Class_Proxy; To : Boolean) is begin AMF.Internals.Tables.UML_Attributes.Internal_Set_Is_Derived (Self.Element, To); end Set_Is_Derived; -------------------- -- Get_Member_End -- -------------------- overriding function Get_Member_End (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Properties.Collections.Ordered_Set_Of_UML_Property is begin return AMF.UML.Properties.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Member_End (Self.Element))); end Get_Member_End; ----------------------------- -- Get_Navigable_Owned_End -- ----------------------------- overriding function Get_Navigable_Owned_End (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Properties.Collections.Set_Of_UML_Property is begin return AMF.UML.Properties.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Navigable_Owned_End (Self.Element))); end Get_Navigable_Owned_End; ------------------- -- Get_Owned_End -- ------------------- overriding function Get_Owned_End (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Properties.Collections.Ordered_Set_Of_UML_Property is begin return AMF.UML.Properties.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Owned_End (Self.Element))); end Get_Owned_End; ------------------------- -- Get_Related_Element -- ------------------------- overriding function Get_Related_Element (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Elements.Collections.Set_Of_UML_Element is begin return AMF.UML.Elements.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Related_Element (Self.Element))); end Get_Related_Element; ------------------- -- Get_Attribute -- ------------------- overriding function Get_Attribute (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Properties.Collections.Set_Of_UML_Property is begin return AMF.UML.Properties.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Attribute (Self.Element))); end Get_Attribute; --------------------------- -- Get_Collaboration_Use -- --------------------------- overriding function Get_Collaboration_Use (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Collaboration_Uses.Collections.Set_Of_UML_Collaboration_Use is begin return AMF.UML.Collaboration_Uses.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Collaboration_Use (Self.Element))); end Get_Collaboration_Use; ----------------- -- Get_Feature -- ----------------- overriding function Get_Feature (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Features.Collections.Set_Of_UML_Feature is begin return AMF.UML.Features.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Feature (Self.Element))); end Get_Feature; ----------------- -- Get_General -- ----------------- overriding function Get_General (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Classifiers.Collections.Set_Of_UML_Classifier is begin return AMF.UML.Classifiers.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_General (Self.Element))); end Get_General; ------------------------ -- Get_Generalization -- ------------------------ overriding function Get_Generalization (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Generalizations.Collections.Set_Of_UML_Generalization is begin return AMF.UML.Generalizations.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Generalization (Self.Element))); end Get_Generalization; -------------------------- -- Get_Inherited_Member -- -------------------------- overriding function Get_Inherited_Member (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Named_Elements.Collections.Set_Of_UML_Named_Element is begin return AMF.UML.Named_Elements.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Inherited_Member (Self.Element))); end Get_Inherited_Member; --------------------- -- Get_Is_Abstract -- --------------------- overriding function Get_Is_Abstract (Self : not null access constant UML_Association_Class_Proxy) return Boolean is begin return AMF.Internals.Tables.UML_Attributes.Internal_Get_Is_Abstract (Self.Element); end Get_Is_Abstract; --------------------------------- -- Get_Is_Final_Specialization -- --------------------------------- overriding function Get_Is_Final_Specialization (Self : not null access constant UML_Association_Class_Proxy) return Boolean is begin return AMF.Internals.Tables.UML_Attributes.Internal_Get_Is_Final_Specialization (Self.Element); end Get_Is_Final_Specialization; --------------------------------- -- Set_Is_Final_Specialization -- --------------------------------- overriding procedure Set_Is_Final_Specialization (Self : not null access UML_Association_Class_Proxy; To : Boolean) is begin AMF.Internals.Tables.UML_Attributes.Internal_Set_Is_Final_Specialization (Self.Element, To); end Set_Is_Final_Specialization; ---------------------------------- -- Get_Owned_Template_Signature -- ---------------------------------- overriding function Get_Owned_Template_Signature (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Redefinable_Template_Signatures.UML_Redefinable_Template_Signature_Access is begin return AMF.UML.Redefinable_Template_Signatures.UML_Redefinable_Template_Signature_Access (AMF.Internals.Helpers.To_Element (AMF.Internals.Tables.UML_Attributes.Internal_Get_Owned_Template_Signature (Self.Element))); end Get_Owned_Template_Signature; ---------------------------------- -- Set_Owned_Template_Signature -- ---------------------------------- overriding procedure Set_Owned_Template_Signature (Self : not null access UML_Association_Class_Proxy; To : AMF.UML.Redefinable_Template_Signatures.UML_Redefinable_Template_Signature_Access) is begin AMF.Internals.Tables.UML_Attributes.Internal_Set_Owned_Template_Signature (Self.Element, AMF.Internals.Helpers.To_Element (AMF.Elements.Element_Access (To))); end Set_Owned_Template_Signature; ------------------------ -- Get_Owned_Use_Case -- ------------------------ overriding function Get_Owned_Use_Case (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Use_Cases.Collections.Set_Of_UML_Use_Case is begin return AMF.UML.Use_Cases.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Owned_Use_Case (Self.Element))); end Get_Owned_Use_Case; -------------------------- -- Get_Powertype_Extent -- -------------------------- overriding function Get_Powertype_Extent (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Generalization_Sets.Collections.Set_Of_UML_Generalization_Set is begin return AMF.UML.Generalization_Sets.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Powertype_Extent (Self.Element))); end Get_Powertype_Extent; ------------------------------ -- Get_Redefined_Classifier -- ------------------------------ overriding function Get_Redefined_Classifier (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Classifiers.Collections.Set_Of_UML_Classifier is begin return AMF.UML.Classifiers.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Redefined_Classifier (Self.Element))); end Get_Redefined_Classifier; ------------------------ -- Get_Representation -- ------------------------ overriding function Get_Representation (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Collaboration_Uses.UML_Collaboration_Use_Access is begin return AMF.UML.Collaboration_Uses.UML_Collaboration_Use_Access (AMF.Internals.Helpers.To_Element (AMF.Internals.Tables.UML_Attributes.Internal_Get_Representation (Self.Element))); end Get_Representation; ------------------------ -- Set_Representation -- ------------------------ overriding procedure Set_Representation (Self : not null access UML_Association_Class_Proxy; To : AMF.UML.Collaboration_Uses.UML_Collaboration_Use_Access) is begin AMF.Internals.Tables.UML_Attributes.Internal_Set_Representation (Self.Element, AMF.Internals.Helpers.To_Element (AMF.Elements.Element_Access (To))); end Set_Representation; ---------------------- -- Get_Substitution -- ---------------------- overriding function Get_Substitution (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Substitutions.Collections.Set_Of_UML_Substitution is begin return AMF.UML.Substitutions.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Substitution (Self.Element))); end Get_Substitution; ---------------------------- -- Get_Template_Parameter -- ---------------------------- overriding function Get_Template_Parameter (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Classifier_Template_Parameters.UML_Classifier_Template_Parameter_Access is begin return AMF.UML.Classifier_Template_Parameters.UML_Classifier_Template_Parameter_Access (AMF.Internals.Helpers.To_Element (AMF.Internals.Tables.UML_Attributes.Internal_Get_Template_Parameter (Self.Element))); end Get_Template_Parameter; ---------------------------- -- Set_Template_Parameter -- ---------------------------- overriding procedure Set_Template_Parameter (Self : not null access UML_Association_Class_Proxy; To : AMF.UML.Classifier_Template_Parameters.UML_Classifier_Template_Parameter_Access) is begin AMF.Internals.Tables.UML_Attributes.Internal_Set_Template_Parameter (Self.Element, AMF.Internals.Helpers.To_Element (AMF.Elements.Element_Access (To))); end Set_Template_Parameter; ------------------ -- Get_Use_Case -- ------------------ overriding function Get_Use_Case (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Use_Cases.Collections.Set_Of_UML_Use_Case is begin return AMF.UML.Use_Cases.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Use_Case (Self.Element))); end Get_Use_Case; ------------------------ -- Get_Element_Import -- ------------------------ overriding function Get_Element_Import (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Element_Imports.Collections.Set_Of_UML_Element_Import is begin return AMF.UML.Element_Imports.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Element_Import (Self.Element))); end Get_Element_Import; ------------------------- -- Get_Imported_Member -- ------------------------- overriding function Get_Imported_Member (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Packageable_Elements.Collections.Set_Of_UML_Packageable_Element is begin return AMF.UML.Packageable_Elements.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Imported_Member (Self.Element))); end Get_Imported_Member; ---------------- -- Get_Member -- ---------------- overriding function Get_Member (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Named_Elements.Collections.Set_Of_UML_Named_Element is begin return AMF.UML.Named_Elements.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Member (Self.Element))); end Get_Member; ---------------------- -- Get_Owned_Member -- ---------------------- overriding function Get_Owned_Member (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Named_Elements.Collections.Set_Of_UML_Named_Element is begin return AMF.UML.Named_Elements.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Owned_Member (Self.Element))); end Get_Owned_Member; -------------------- -- Get_Owned_Rule -- -------------------- overriding function Get_Owned_Rule (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Constraints.Collections.Set_Of_UML_Constraint is begin return AMF.UML.Constraints.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Owned_Rule (Self.Element))); end Get_Owned_Rule; ------------------------ -- Get_Package_Import -- ------------------------ overriding function Get_Package_Import (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Package_Imports.Collections.Set_Of_UML_Package_Import is begin return AMF.UML.Package_Imports.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Package_Import (Self.Element))); end Get_Package_Import; --------------------------- -- Get_Client_Dependency -- --------------------------- overriding function Get_Client_Dependency (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Dependencies.Collections.Set_Of_UML_Dependency is begin return AMF.UML.Dependencies.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Client_Dependency (Self.Element))); end Get_Client_Dependency; ------------------------- -- Get_Name_Expression -- ------------------------- overriding function Get_Name_Expression (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.String_Expressions.UML_String_Expression_Access is begin return AMF.UML.String_Expressions.UML_String_Expression_Access (AMF.Internals.Helpers.To_Element (AMF.Internals.Tables.UML_Attributes.Internal_Get_Name_Expression (Self.Element))); end Get_Name_Expression; ------------------------- -- Set_Name_Expression -- ------------------------- overriding procedure Set_Name_Expression (Self : not null access UML_Association_Class_Proxy; To : AMF.UML.String_Expressions.UML_String_Expression_Access) is begin AMF.Internals.Tables.UML_Attributes.Internal_Set_Name_Expression (Self.Element, AMF.Internals.Helpers.To_Element (AMF.Elements.Element_Access (To))); end Set_Name_Expression; ------------------- -- Get_Namespace -- ------------------- overriding function Get_Namespace (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Namespaces.UML_Namespace_Access is begin return AMF.UML.Namespaces.UML_Namespace_Access (AMF.Internals.Helpers.To_Element (AMF.Internals.Tables.UML_Attributes.Internal_Get_Namespace (Self.Element))); end Get_Namespace; ------------------------ -- Get_Qualified_Name -- ------------------------ overriding function Get_Qualified_Name (Self : not null access constant UML_Association_Class_Proxy) return AMF.Optional_String is begin declare use type Matreshka.Internals.Strings.Shared_String_Access; Aux : constant Matreshka.Internals.Strings.Shared_String_Access := AMF.Internals.Tables.UML_Attributes.Internal_Get_Qualified_Name (Self.Element); begin if Aux = null then return (Is_Empty => True); else return (False, League.Strings.Internals.Create (Aux)); end if; end; end Get_Qualified_Name; ----------------- -- Get_Package -- ----------------- overriding function Get_Package (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Packages.UML_Package_Access is begin return AMF.UML.Packages.UML_Package_Access (AMF.Internals.Helpers.To_Element (AMF.Internals.Tables.UML_Attributes.Internal_Get_Package (Self.Element))); end Get_Package; ----------------- -- Set_Package -- ----------------- overriding procedure Set_Package (Self : not null access UML_Association_Class_Proxy; To : AMF.UML.Packages.UML_Package_Access) is begin AMF.Internals.Tables.UML_Attributes.Internal_Set_Package (Self.Element, AMF.Internals.Helpers.To_Element (AMF.Elements.Element_Access (To))); end Set_Package; ----------------------------------- -- Get_Owning_Template_Parameter -- ----------------------------------- overriding function Get_Owning_Template_Parameter (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Template_Parameters.UML_Template_Parameter_Access is begin return AMF.UML.Template_Parameters.UML_Template_Parameter_Access (AMF.Internals.Helpers.To_Element (AMF.Internals.Tables.UML_Attributes.Internal_Get_Owning_Template_Parameter (Self.Element))); end Get_Owning_Template_Parameter; ----------------------------------- -- Set_Owning_Template_Parameter -- ----------------------------------- overriding procedure Set_Owning_Template_Parameter (Self : not null access UML_Association_Class_Proxy; To : AMF.UML.Template_Parameters.UML_Template_Parameter_Access) is begin AMF.Internals.Tables.UML_Attributes.Internal_Set_Owning_Template_Parameter (Self.Element, AMF.Internals.Helpers.To_Element (AMF.Elements.Element_Access (To))); end Set_Owning_Template_Parameter; ---------------------------- -- Get_Template_Parameter -- ---------------------------- overriding function Get_Template_Parameter (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Template_Parameters.UML_Template_Parameter_Access is begin return AMF.UML.Template_Parameters.UML_Template_Parameter_Access (AMF.Internals.Helpers.To_Element (AMF.Internals.Tables.UML_Attributes.Internal_Get_Template_Parameter (Self.Element))); end Get_Template_Parameter; ---------------------------- -- Set_Template_Parameter -- ---------------------------- overriding procedure Set_Template_Parameter (Self : not null access UML_Association_Class_Proxy; To : AMF.UML.Template_Parameters.UML_Template_Parameter_Access) is begin AMF.Internals.Tables.UML_Attributes.Internal_Set_Template_Parameter (Self.Element, AMF.Internals.Helpers.To_Element (AMF.Elements.Element_Access (To))); end Set_Template_Parameter; ---------------------------------- -- Get_Owned_Template_Signature -- ---------------------------------- overriding function Get_Owned_Template_Signature (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Template_Signatures.UML_Template_Signature_Access is begin return AMF.UML.Template_Signatures.UML_Template_Signature_Access (AMF.Internals.Helpers.To_Element (AMF.Internals.Tables.UML_Attributes.Internal_Get_Owned_Template_Signature (Self.Element))); end Get_Owned_Template_Signature; ---------------------------------- -- Set_Owned_Template_Signature -- ---------------------------------- overriding procedure Set_Owned_Template_Signature (Self : not null access UML_Association_Class_Proxy; To : AMF.UML.Template_Signatures.UML_Template_Signature_Access) is begin AMF.Internals.Tables.UML_Attributes.Internal_Set_Owned_Template_Signature (Self.Element, AMF.Internals.Helpers.To_Element (AMF.Elements.Element_Access (To))); end Set_Owned_Template_Signature; -------------------------- -- Get_Template_Binding -- -------------------------- overriding function Get_Template_Binding (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Template_Bindings.Collections.Set_Of_UML_Template_Binding is begin return AMF.UML.Template_Bindings.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Template_Binding (Self.Element))); end Get_Template_Binding; ----------------- -- Get_Is_Leaf -- ----------------- overriding function Get_Is_Leaf (Self : not null access constant UML_Association_Class_Proxy) return Boolean is begin return AMF.Internals.Tables.UML_Attributes.Internal_Get_Is_Leaf (Self.Element); end Get_Is_Leaf; ----------------- -- Set_Is_Leaf -- ----------------- overriding procedure Set_Is_Leaf (Self : not null access UML_Association_Class_Proxy; To : Boolean) is begin AMF.Internals.Tables.UML_Attributes.Internal_Set_Is_Leaf (Self.Element, To); end Set_Is_Leaf; --------------------------- -- Get_Redefined_Element -- --------------------------- overriding function Get_Redefined_Element (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Redefinable_Elements.Collections.Set_Of_UML_Redefinable_Element is begin return AMF.UML.Redefinable_Elements.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Redefined_Element (Self.Element))); end Get_Redefined_Element; ------------------------------ -- Get_Redefinition_Context -- ------------------------------ overriding function Get_Redefinition_Context (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Classifiers.Collections.Set_Of_UML_Classifier is begin return AMF.UML.Classifiers.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Redefinition_Context (Self.Element))); end Get_Redefinition_Context; ------------------- -- Get_Extension -- ------------------- overriding function Get_Extension (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Extensions.Collections.Set_Of_UML_Extension is begin return AMF.UML.Extensions.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Extension (Self.Element))); end Get_Extension; ------------------- -- Get_Is_Active -- ------------------- overriding function Get_Is_Active (Self : not null access constant UML_Association_Class_Proxy) return Boolean is begin return AMF.Internals.Tables.UML_Attributes.Internal_Get_Is_Active (Self.Element); end Get_Is_Active; ------------------- -- Set_Is_Active -- ------------------- overriding procedure Set_Is_Active (Self : not null access UML_Association_Class_Proxy; To : Boolean) is begin AMF.Internals.Tables.UML_Attributes.Internal_Set_Is_Active (Self.Element, To); end Set_Is_Active; --------------------------- -- Get_Nested_Classifier -- --------------------------- overriding function Get_Nested_Classifier (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Classifiers.Collections.Ordered_Set_Of_UML_Classifier is begin return AMF.UML.Classifiers.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Nested_Classifier (Self.Element))); end Get_Nested_Classifier; ------------------------- -- Get_Owned_Attribute -- ------------------------- overriding function Get_Owned_Attribute (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Properties.Collections.Ordered_Set_Of_UML_Property is begin return AMF.UML.Properties.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Owned_Attribute (Self.Element))); end Get_Owned_Attribute; ------------------------- -- Get_Owned_Operation -- ------------------------- overriding function Get_Owned_Operation (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Operations.Collections.Ordered_Set_Of_UML_Operation is begin return AMF.UML.Operations.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Owned_Operation (Self.Element))); end Get_Owned_Operation; ------------------------- -- Get_Owned_Reception -- ------------------------- overriding function Get_Owned_Reception (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Receptions.Collections.Set_Of_UML_Reception is begin return AMF.UML.Receptions.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Owned_Reception (Self.Element))); end Get_Owned_Reception; --------------------- -- Get_Super_Class -- --------------------- overriding function Get_Super_Class (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Classes.Collections.Set_Of_UML_Class is begin return AMF.UML.Classes.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Super_Class (Self.Element))); end Get_Super_Class; ----------------------------- -- Get_Classifier_Behavior -- ----------------------------- overriding function Get_Classifier_Behavior (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Behaviors.UML_Behavior_Access is begin return AMF.UML.Behaviors.UML_Behavior_Access (AMF.Internals.Helpers.To_Element (AMF.Internals.Tables.UML_Attributes.Internal_Get_Classifier_Behavior (Self.Element))); end Get_Classifier_Behavior; ----------------------------- -- Set_Classifier_Behavior -- ----------------------------- overriding procedure Set_Classifier_Behavior (Self : not null access UML_Association_Class_Proxy; To : AMF.UML.Behaviors.UML_Behavior_Access) is begin AMF.Internals.Tables.UML_Attributes.Internal_Set_Classifier_Behavior (Self.Element, AMF.Internals.Helpers.To_Element (AMF.Elements.Element_Access (To))); end Set_Classifier_Behavior; ------------------------------- -- Get_Interface_Realization -- ------------------------------- overriding function Get_Interface_Realization (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Interface_Realizations.Collections.Set_Of_UML_Interface_Realization is begin return AMF.UML.Interface_Realizations.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Interface_Realization (Self.Element))); end Get_Interface_Realization; ------------------------ -- Get_Owned_Behavior -- ------------------------ overriding function Get_Owned_Behavior (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Behaviors.Collections.Set_Of_UML_Behavior is begin return AMF.UML.Behaviors.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Owned_Behavior (Self.Element))); end Get_Owned_Behavior; -------------------- -- Get_Owned_Port -- -------------------- overriding function Get_Owned_Port (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Ports.Collections.Set_Of_UML_Port is begin return AMF.UML.Ports.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Owned_Port (Self.Element))); end Get_Owned_Port; ------------------------- -- Get_Owned_Connector -- ------------------------- overriding function Get_Owned_Connector (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Connectors.Collections.Set_Of_UML_Connector is begin return AMF.UML.Connectors.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Owned_Connector (Self.Element))); end Get_Owned_Connector; -------------- -- Get_Part -- -------------- overriding function Get_Part (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Properties.Collections.Set_Of_UML_Property is begin return AMF.UML.Properties.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Part (Self.Element))); end Get_Part; -------------- -- Get_Role -- -------------- overriding function Get_Role (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Connectable_Elements.Collections.Set_Of_UML_Connectable_Element is begin return AMF.UML.Connectable_Elements.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Role (Self.Element))); end Get_Role; -------------- -- End_Type -- -------------- overriding function End_Type (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Types.Collections.Ordered_Set_Of_UML_Type is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, ""End_Type unimplemented""); raise Program_Error with ""Unimplemented procedure UML_Association_Class_Proxy.End_Type""; return End_Type (Self); end End_Type; ------------------ -- All_Features -- ------------------ overriding function All_Features (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Features.Collections.Set_Of_UML_Feature is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, ""All_Features unimplemented""); raise Program_Error with ""Unimplemented procedure UML_Association_Class_Proxy.All_Features""; return All_Features (Self); end All_Features; ----------------- -- Conforms_To -- ----------------- overriding function Conforms_To (Self : not null access constant UML_Association_Class_Proxy; Other : AMF.UML.Classifiers.UML_Classifier_Access) return Boolean is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, ""Conforms_To unimplemented""); raise Program_Error with ""Unimplemented procedure UML_Association_Class_Proxy.Conforms_To""; return Conforms_To (Self, Other); end Conforms_To; ------------- -- General -- ------------- overriding function General (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Classifiers.Collections.Set_Of_UML_Classifier is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, ""General unimplemented""); raise Program_Error with ""Unimplemented procedure UML_Association_Class_Proxy.General""; return General (Self); end General; ----------------------- -- Has_Visibility_Of -- ----------------------- overriding function Has_Visibility_Of (Self : not null access constant UML_Association_Class_Proxy; N : AMF.UML.Named_Elements.UML_Named_Element_Access) return Boolean is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, ""Has_Visibility_Of unimplemented""); raise Program_Error with ""Unimplemented procedure UML_Association_Class_Proxy.Has_Visibility_Of""; return Has_Visibility_Of (Self, N); end Has_Visibility_Of; ------------- -- Inherit -- ------------- overriding function Inherit (Self : not null access constant UML_Association_Class_Proxy; Inhs : AMF.UML.Named_Elements.Collections.Set_Of_UML_Named_Element) return AMF.UML.Named_Elements.Collections.Set_Of_UML_Named_Element is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, ""Inherit unimplemented""); raise Program_Error with ""Unimplemented procedure UML_Association_Class_Proxy.Inherit""; return Inherit (Self, Inhs); end Inherit; ------------------------- -- Inheritable_Members -- ------------------------- overriding function Inheritable_Members (Self : not null access constant UML_Association_Class_Proxy; C : AMF.UML.Classifiers.UML_Classifier_Access) return AMF.UML.Named_Elements.Collections.Set_Of_UML_Named_Element is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, ""Inheritable_Members unimplemented""); raise Program_Error with ""Unimplemented procedure UML_Association_Class_Proxy.Inheritable_Members""; return Inheritable_Members (Self, C); end Inheritable_Members; ---------------------- -- Inherited_Member -- ---------------------- overriding function Inherited_Member (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Named_Elements.Collections.Set_Of_UML_Named_Element is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, ""Inherited_Member unimplemented""); raise Program_Error with ""Unimplemented procedure UML_Association_Class_Proxy.Inherited_Member""; return Inherited_Member (Self); end Inherited_Member; ----------------- -- Is_Template -- ----------------- overriding function Is_Template (Self : not null access constant UML_Association_Class_Proxy) return Boolean is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, ""Is_Template unimplemented""); raise Program_Error with ""Unimplemented procedure UML_Association_Class_Proxy.Is_Template""; return Is_Template (Self); end Is_Template; ------------------------- -- May_Specialize_Type -- ------------------------- overriding function May_Specialize_Type (Self : not null access constant UML_Association_Class_Proxy; C : AMF.UML.Classifiers.UML_Classifier_Access) return Boolean is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, ""May_Specialize_Type unimplemented""); raise Program_Error with ""Unimplemented procedure UML_Association_Class_Proxy.May_Specialize_Type""; return May_Specialize_Type (Self, C); end May_Specialize_Type; ------------------------ -- Exclude_Collisions -- ------------------------ overriding function Exclude_Collisions (Self : not null access constant UML_Association_Class_Proxy; Imps : AMF.UML.Packageable_Elements.Collections.Set_Of_UML_Packageable_Element) return AMF.UML.Packageable_Elements.Collections.Set_Of_UML_Packageable_Element is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, ""Exclude_Collisions unimplemented""); raise Program_Error with ""Unimplemented procedure UML_Association_Class_Proxy.Exclude_Collisions""; return Exclude_Collisions (Self, Imps); end Exclude_Collisions; ------------------------- -- Get_Names_Of_Member -- ------------------------- overriding function Get_Names_Of_Member (Self : not null access constant UML_Association_Class_Proxy; Element : AMF.UML.Named_Elements.UML_Named_Element_Access) return AMF.String_Collections.Set_Of_String is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, ""Get_Names_Of_Member unimplemented""); raise Program_Error with ""Unimplemented procedure UML_Association_Class_Proxy.Get_Names_Of_Member""; return Get_Names_Of_Member (Self, Element); end Get_Names_Of_Member; -------------------- -- Import_Members -- -------------------- overriding function Import_Members (Self : not null access constant UML_Association_Class_Proxy; Imps : AMF.UML.Packageable_Elements.Collections.Set_Of_UML_Packageable_Element) return AMF.UML.Packageable_Elements.Collections.Set_Of_UML_Packageable_Element is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, ""Import_Members unimplemented""); raise Program_Error with ""Unimplemented procedure UML_Association_Class_Proxy.Import_Members""; return Import_Members (Self, Imps); end Import_Members; --------------------- -- Imported_Member -- --------------------- overriding function Imported_Member (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Packageable_Elements.Collections.Set_Of_UML_Packageable_Element is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, ""Imported_Member unimplemented""); raise Program_Error with ""Unimplemented procedure UML_Association_Class_Proxy.Imported_Member""; return Imported_Member (Self); end Imported_Member; --------------------------------- -- Members_Are_Distinguishable -- --------------------------------- overriding function Members_Are_Distinguishable (Self : not null access constant UML_Association_Class_Proxy) return Boolean is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, ""Members_Are_Distinguishable unimplemented""); raise Program_Error with ""Unimplemented procedure UML_Association_Class_Proxy.Members_Are_Distinguishable""; return Members_Are_Distinguishable (Self); end Members_Are_Distinguishable; ------------------ -- Owned_Member -- ------------------ overriding function Owned_Member (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Named_Elements.Collections.Set_Of_UML_Named_Element is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, ""Owned_Member unimplemented""); raise Program_Error with ""Unimplemented procedure UML_Association_Class_Proxy.Owned_Member""; return Owned_Member (Self); end Owned_Member; ------------------------- -- All_Owning_Packages -- ------------------------- overriding function All_Owning_Packages (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Packages.Collections.Set_Of_UML_Package is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, ""All_Owning_Packages unimplemented""); raise Program_Error with ""Unimplemented procedure UML_Association_Class_Proxy.All_Owning_Packages""; return All_Owning_Packages (Self); end All_Owning_Packages; ----------------------------- -- Is_Distinguishable_From -- ----------------------------- overriding function Is_Distinguishable_From (Self : not null access constant UML_Association_Class_Proxy; N : AMF.UML.Named_Elements.UML_Named_Element_Access; Ns : AMF.UML.Namespaces.UML_Namespace_Access) return Boolean is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, ""Is_Distinguishable_From unimplemented""); raise Program_Error with ""Unimplemented procedure UML_Association_Class_Proxy.Is_Distinguishable_From""; return Is_Distinguishable_From (Self, N, Ns); end Is_Distinguishable_From; --------------- -- Namespace -- --------------- overriding function Namespace (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Namespaces.UML_Namespace_Access is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, ""Namespace unimplemented""); raise Program_Error with ""Unimplemented procedure UML_Association_Class_Proxy.Namespace""; return Namespace (Self); end Namespace; ----------------- -- Conforms_To -- ----------------- overriding function Conforms_To (Self : not null access constant UML_Association_Class_Proxy; Other : AMF.UML.Types.UML_Type_Access) return Boolean is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, ""Conforms_To unimplemented""); raise Program_Error with ""Unimplemented procedure UML_Association_Class_Proxy.Conforms_To""; return Conforms_To (Self, Other); end Conforms_To; ------------------------ -- Is_Compatible_With -- ------------------------ overriding function Is_Compatible_With (Self : not null access constant UML_Association_Class_Proxy; P : AMF.UML.Parameterable_Elements.UML_Parameterable_Element_Access) return Boolean is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, ""Is_Compatible_With unimplemented""); raise Program_Error with ""Unimplemented procedure UML_Association_Class_Proxy.Is_Compatible_With""; return Is_Compatible_With (Self, P); end Is_Compatible_With; --------------------------- -- Is_Template_Parameter -- --------------------------- overriding function Is_Template_Parameter (Self : not null access constant UML_Association_Class_Proxy) return Boolean is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, ""Is_Template_Parameter unimplemented""); raise Program_Error with ""Unimplemented procedure UML_Association_Class_Proxy.Is_Template_Parameter""; return Is_Template_Parameter (Self); end Is_Template_Parameter; ---------------------------- -- Parameterable_Elements -- ---------------------------- overriding function Parameterable_Elements (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Parameterable_Elements.Collections.Set_Of_UML_Parameterable_Element is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, ""Parameterable_Elements unimplemented""); raise Program_Error with ""Unimplemented procedure UML_Association_Class_Proxy.Parameterable_Elements""; return Parameterable_Elements (Self); end Parameterable_Elements; ------------------------ -- Is_Consistent_With -- ------------------------ overriding function Is_Consistent_With (Self : not null access constant UML_Association_Class_Proxy; Redefinee : AMF.UML.Redefinable_Elements.UML_Redefinable_Element_Access) return Boolean is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, ""Is_Consistent_With unimplemented""); raise Program_Error with ""Unimplemented procedure UML_Association_Class_Proxy.Is_Consistent_With""; return Is_Consistent_With (Self, Redefinee); end Is_Consistent_With; ----------------------------------- -- Is_Redefinition_Context_Valid -- ----------------------------------- overriding function Is_Redefinition_Context_Valid (Self : not null access constant UML_Association_Class_Proxy; Redefined : AMF.UML.Redefinable_Elements.UML_Redefinable_Element_Access) return Boolean is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, ""Is_Redefinition_Context_Valid unimplemented""); raise Program_Error with ""Unimplemented procedure UML_Association_Class_Proxy.Is_Redefinition_Context_Valid""; return Is_Redefinition_Context_Valid (Self, Redefined); end Is_Redefinition_Context_Valid; --------------- -- Extension -- --------------- overriding function Extension (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Extensions.Collections.Set_Of_UML_Extension is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, ""Extension unimplemented""); raise Program_Error with ""Unimplemented procedure UML_Association_Class_Proxy.Extension""; return Extension (Self); end Extension; ----------------- -- Super_Class -- ----------------- overriding function Super_Class (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Classes.Collections.Set_Of_UML_Class is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, ""Super_Class unimplemented""); raise Program_Error with ""Unimplemented procedure UML_Association_Class_Proxy.Super_Class""; return Super_Class (Self); end Super_Class; ---------------- -- Owned_Port -- ---------------- overriding function Owned_Port (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Ports.Collections.Set_Of_UML_Port is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, ""Owned_Port unimplemented""); raise Program_Error with ""Unimplemented procedure UML_Association_Class_Proxy.Owned_Port""; return Owned_Port (Self); end Owned_Port; ---------- -- Part -- ---------- overriding function Part (Self : not null access constant UML_Association_Class_Proxy) return AMF.UML.Properties.Collections.Set_Of_UML_Property is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, ""Part unimplemented""); raise Program_Error with ""Unimplemented procedure UML_Association_Class_Proxy.Part""; return Part (Self); end Part; end AMF.Internals.UML_Association_Classes; ",12249,True,3192.361215474058,median "[[indexing_querying]] = Indexing and Querying == Overview {brandname} supports indexing and searching of Java Pojo(s) or objects encoded via link:https://developers.google.com/protocol-buffers/[Protocol Buffers] stored in the grid using powerful search APIs which complement its main Map-like API. Querying is possible both in link:#query_library[library] and link:#query_remote[client/server mode] (for Java, C#, Node.js and other clients), and {brandname} can index data using link:http://lucene.apache.org/[Apache Lucene], offering an efficient link:https://en.wikipedia.org/wiki/Full-text_search[full-text] capable search engine in order to cover a wide range of data retrieval use cases. Indexing configuration relies on a schema definition, and for that {brandname} can use annotated Java classes when in library mode, and protobuf schemas for remote clients written in other languages. By standardizing on protobuf, {brandname} allows full interoperability between Java and non-Java clients. Apart from indexed queries, {brandname} can run queries over non-indexed or partially indexed data. In terms of Search APIs, {brandname} has its own query language called _link:#query_ickle[Ickle]_, which is string-based and adds support for full-text querying. The link:#query_dsl[Query DSL] can be used for both embedded and remote java clients when full-text is not required; for Java embedded clients {brandname} offers the link:#query_hibernatesearch[Hibernate Search Query API] which supports running Lucene queries in the grid, apart from advanced search capabilities like Faceted and Spatial search. Finally, {brandname} has support for link:#query_continuous[Continuous Queries], which works in a reverse manner to the other APIs: instead of creating, executing a query and obtain results, it allows a client to register queries that will be evaluated continuously as data in the cluster changes, generating notifications whenever the changed data matches the queries. [[query_library]] == Embedded Querying Embedded querying is available when {brandname} is used as a library. No protobuf mapping is required, and both indexing and searching are done on top of Java objects. When in library mode, it is possible to run Lucene queries directly and use all the available link:#query_apis[Query APIs] and it also allows flexible indexing configurations to keep latency to a minimal. === Quick example We're going to store _Book_ instances in an {brandname} cache called ""books"". _Book_ instances will be indexed, so we enable indexing for the cache, letting {brandname} link:#query_autoconfig[configure the indexing automatically]: {brandname} configuration: .infinispan.xml [source,xml,options=""nowrap"",subs=attributes+] ---- include::config_examples/infinispan_distributed_cache_books.xml[] ---- Obtaining the cache: [source,java] ---- import org.infinispan.Cache; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.manager.EmbeddedCacheManager; EmbeddedCacheManager manager = new DefaultCacheManager(""infinispan.xml""); Cache cache = manager.getCache(""books""); ---- Each _Book_ will be defined as in the following example; we have to choose which properties are indexed, and for each property we can optionally choose advanced indexing options using the annotations defined in the Hibernate Search project. [source,java] .Book.java ---- import org.hibernate.search.annotations.*; import java.util.Date; import java.util.HashSet; import java.util.Set; //Values you want to index need to be annotated with @Indexed, then you pick which fields and how they are to be indexed: @Indexed public class Book { @Field String title; @Field String description; @Field @DateBridge(resolution=Resolution.YEAR) Date publicationYear; @IndexedEmbedded Set authors = new HashSet(); } ---- [source,java] .Author.java ---- public class Author { @Field String name; @Field String surname; // hashCode() and equals() omitted } ---- Now assuming we stored several _Book_ instances in our {brandname} _Cache_ , we can search them for any matching field as in the following example. Using a Lucene Query: [source,java] ---- // get the search manager from the cache: SearchManager searchManager = org.infinispan.query.Search.getSearchManager(cache); // create any standard Lucene query, via Lucene's QueryParser or any other means: org.apache.lucene.search.Query fullTextQuery = //any Apache Lucene Query // convert the Lucene query to a CacheQuery: CacheQuery cacheQuery = searchManager.getQuery( fullTextQuery ); // get the results: List found = cacheQuery.list(); ---- A Lucene Query is often created by parsing a query in text format such as ""title:infinispan AND authors.name:sanne"", or by using the query builder provided by Hibernate Search. [source,java] ---- // get the search manager from the cache: SearchManager searchManager = org.infinispan.query.Search.getSearchManager( cache ); // you could make the queries via Lucene APIs, or use some helpers: QueryBuilder queryBuilder = searchManager.buildQueryBuilderForClass(Book.class).get(); // the queryBuilder has a nice fluent API which guides you through all options. // this has some knowledge about your object, for example which Analyzers // need to be applied, but the output is a fairly standard Lucene Query. org.apache.lucene.search.Query luceneQuery = queryBuilder.phrase() .onField(""description"") .andField(""title"") .sentence(""a book on highly scalable query engines"") .createQuery(); // the query API itself accepts any Lucene Query, and on top of that // you can restrict the result to selected class types: CacheQuery query = searchManager.getQuery(luceneQuery, Book.class); // and there are your results! List objectList = query.list(); for (Object book : objectList) { System.out.println(book); } ---- Apart from _list()_ you have the option for streaming results, or use pagination. For searches that do not require Lucene or full-text capabilities and are mostly about aggregation and exact matches, we can use the {brandname} Query DSL API: [source,java] ---- import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.Query; import org.infinispan.query.Search; // get the query factory: QueryFactory queryFactory = Search.getQueryFactory(cache); Query q = queryFactory.from(Book.class) .having(""author.surname"").eq(""King"") .build(); List list = q.list(); ---- Finally, we can use an link:#query_ickle[Ickle] query directly, allowing for Lucene syntax in one or more predicates: [source,java] ---- import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.Query; // get the query factory: QueryFactory queryFactory = Search.getQueryFactory(cache); Query q = queryFactory.create(""from Book b where b.author.name = 'Stephen' and "" + ""b.description : (+'dark' -'tower')""); List list = q.list(); ---- === Indexing Indexing in {brandname} happens on a per-cache basis and by default a cache is not indexed. Enabling indexing is not mandatory but queries using an index will have a vastly superior performance. On the other hand, enabling indexing can impact negatively the write throughput of a cluster, so make sure to check the link:#query_performance[query performance guide] for some strategies to minimize this impact depending on the cache type and use case. ==== Configuration ===== General format To enable indexing via XML, you need to add the `` element to your cache configuration, and optionally pass additional properties. [source,xml,options=""nowrap"",subs=attributes+] ---- include::config_examples/indexing.xml[] ---- Programmatic: [source,java] ---- import org.infinispan.configuration.cache.*; ConfigurationBuilder cacheCfg = ... cacheCfg.indexing().enable() .addProperty(""property name"", ""propery value"") ---- ===== Index names Each property inside the `index` element is prefixed with the index name, for the index named `org.infinispan.sample.Car` the `directory_provider` is `local-heap`: [source,xml,options=""nowrap"",subs=attributes+] ---- include::config_examples/indexing_property.xml[] ---- [source,java] ---- cacheCfg.indexing() .enable() .addProperty(""org.infinispan.sample.Car.directory_provider"", ""local-heap"") ---- {brandname} creates an index for each entity existent in a cache, and it allows to configure those indexes independently. For a class annotated with `@Indexed`, the index name is the fully qualified class name, unless overridden with the `name` argument in the annotation. In the snippet below, the default storage for all entities is `infinispan`, but `Boat` instances will be stored on `local-heap` in an index named `boatIndex`. `Airplane` entities will also be stored in `local-heap`. Any other entity's index will be configured with the property prefixed by `default`. [source,java] ---- package org.infinispan.sample; @Indexed(name = ""boatIndex"") public class Boat { } @Indexed public class Airplane { } ---- [source,xml,options=""nowrap"",subs=attributes+] ---- include::config_examples/indexing_property_entity.xml[] ---- ===== Specifying indexed Entities {brandname} can automatically recognize and manage indexes for different entity types in a cache. Future versions of {brandname} will remove this capability so it's recommended to declare upfront which types are going to be indexed (list them by their fully qualified class name). This can be done via xml: [source,xml,options=""nowrap"",subs=attributes+] ---- include::config_examples/indexed_entities.xml[] ---- or programmatically: [source,java] ---- cacheCfg.indexing() .enable() .addIndexedEntity(Car.class) .addIndexedEntity(Truck.class) ---- In server mode, the class names listed under the 'indexed-entities' element must use the 'extended' class name format which is composed of a JBoss Modules module identifier, a slot name, and the fully qualified class name, these three components being separated by the ':' character, (eg. ""com.acme.my-module-with-entity-classes:my-slot:com.acme.query.test.Car""). The entity classes must be located in the referenced module, which can be either a user supplied module deployed in the 'modules' folder of your server or a plain jar deployed in the 'deployments' folder. The module in question will become an automatic dependency of your Cache, so its eventual redeployment will cause the cache to be restarted. NOTE: Only for server, if you fail to follow the requirement of using 'extended' class names and use a plain class name its resolution will fail due to missing class because the wrong ClassLoader is being used (the {brandname}'s internal class path is being used). [[query_index_manager]] ==== Index Managers Index managers are central components in {brandname} Querying responsible for the indexing configuration, distribution and internal lifecycle of several query components such as Lucene's _IndexReader_ and _IndexWriter_. Each Index Manager is associated with a _Directory Provider_, which defines the physical storage of the index. Regarding index distribution, {brandname} can be configured with shared or non-shared indexes. [[query_shared_index]] ==== Shared indexes A shared index is a single, distributed, cluster-wide index for a certain cache. The main advantage is that the index is visible from every node and can be queried as if the index were local, there is no need to link:#query_clustered_query_api[broadcast] queries to all members and aggregate the results. The downside is that Lucene does not allow more than a single process writing to the index at the same time, and the coordination of lock acquisitions needs to be done by a proper shared index capable index manager. In any case, having a single write lock cluster-wise can lead to some degree of contention under heavy writing. {brandname} supports a shared index leveraging the Infinispan Directory Provider, which stores indexes in a separate set of caches, called InfinispanIndexManager. ===== InfinispanIndexManager This index manager uses the {brandname} Directory Provider, and is suitable for creating shared indexes. Configuration: [source,xml,options=""nowrap"",subs=attributes+] ---- include::config_examples/index_manager.xml[] ---- Indexes are stored in a set of clustered caches, called by default _LuceneIndexesData_, _LuceneIndexesMetadata_ and _LuceneIndexesLocking_. The _LuceneIndexesLocking_ cache is used to store Lucene locks, and it is a very small cache: it will contain one entry per entity (index). The _LuceneIndexesMetadata_ cache is used to store info about the logical files that are part of the index, such as names, chunks and sizes and it is also small in size. The _LuceneIndexesData_ cache is where most of the index is located: it is much bigger then the other two but should be smaller than the data in the cache itself, thanks to Lucene's efficient storing techniques. It's not necessary to redefine the configuration of those 3 cases, {brandname} will pick sensible defaults. Reasons re-define them would be performance tuning for a specific scenario, or for example to make them persistent by configuring a cache store. In order to avoid index corruption when two or more nodes of the cluster try to write to the index at the same time, the _InfinispanIndexManager_ internally elects a master in the cluster (which is the JGroups coordinator) and forwards all indexing works to this master. [[query_non_shared_index]] ==== Non-shared indexes Non-shared indexes are independent indexes at each node. This setup is particularly advantageous for replicated caches where each node has all the cluster data and thus can hold all the indexes as well, offering optimal query performance with zero network latency when querying. Another advantage is, since the index is local to each node, there is less contention during writes due to the fact that each node is subjected to its own index lock, not a cluster wide one. Since each node might hold a partial index, it may be necessary to link#query_clustered_query_api[broadcast] queries in order to get correct search results, which can add latency. If the cache is REPL, though, the broadcast is not necessary: each node can hold a full local copy of the index and queries runs at optimal speed taking advantage of a local index. {brandname} has two index managers suitable for non-shared indexes: `directory-based` and `near-real-time`. Storage wise, non-shared indexes can be located in ram, filesystem, or {brandname} local caches. [[query_directory_based]] ===== directory-based index manager This is the default Index Manager used when no index manager is configured. The `directory-based` index manager is used to manage indexes backed by a local lucene directory. It supports _ram_, _filesystem_ and non-clustered _infinispan_ storage. [small]*Filesystem storage* This is the default storage, and used when index manager configuration is omitted. The index is stored in the filesystem using a link:https://lucene.apache.org/core/6_0_0/core/org/apache/lucene/store/MMapDirectory.html[MMapDirectory]. It is the recommended storage for local indexes. Although indexes are persistent on disk, they get memory mapped by Lucene and thus offer decent query performance. Configuration: [source,xml,options=""nowrap"",subs=attributes+] ---- include::config_examples/indexing_filesystem.xml[] ---- {brandname} will create a different folder under `default.indexBase` for each entity (index) present in the cache. [small]*Ram storage* Index is stored in memory using a link:https://lucene.apache.org/core/6_0_0/core/org/apache/lucene/store/RAMDirectory.html[Lucene RAMDirectory]. Not recommended for large indexes or highly concurrent situations. Indexes stored in Ram are not persistent, so after a cluster shutdown a link:#query_massindexer[re-index] is needed. Configuration: [source,xml,options=""nowrap"",subs=attributes+] ---- include::config_examples/indexing_local_heap.xml[] ---- [small]*{brandname} storage* {brandname} storage makes use of the {brandname} Lucene directory that saves the indexes to a set of caches; those caches can be configured like any other {brandname} cache, for example by adding a cache store to have indexes persisted elsewhere apart from memory. In order to use {brandname} storage with a non-shared index, it's necessary to use LOCAL caches for the indexes: [source,xml,options=""nowrap"",subs=attributes+] ---- include::config_examples/indexing_lucene_storage.xml[] ---- ===== near-real-time index manager Similar to the `directory-based` index manager but takes advantage of the Near-Real-Time features of Lucene. It has better write performance than the `directory-based` because it flushes the index to the underlying store less often. The drawback is that unflushed index changes can be lost in case of a non-clean shutdown. Can be used in conjunction with `local-heap`, `filesystem` and local infinispan storage. Configuration for each different storage type is the same as the link:#query_directory_based[directory-based] index manager. Example with ram: [source,xml,options=""nowrap"",subs=attributes+] ---- include::config_examples/indexing_near_real_time.xml[] ---- Example with filesystem: [source,xml,options=""nowrap"",subs=attributes+] ---- include::config_examples/indexing_near_real_time_fs.xml[] ---- ==== External indexes Apart from having shared and non-shared indexes managed by {brandname} itself, it is possible to offload indexing to a third party search engine: currently {brandname} supports Elasticsearch as a external index storage. ===== Elasticsearch IndexManager (experimental) This index manager forwards all indexes to an external Elasticsearch server. This is an experimental integration and some features may not be available, for example `indexNullAs` for `@IndexedEmbedded` annotations is link:https://hibernate.atlassian.net/browse/HSEARCH-2389[not currently supported]. Configuration: [source,xml,options=""nowrap"",subs=attributes+] ---- include::config_examples/indexing_elasticsearch.xml[] ---- More information about Elasticsearch integration, including the full description of the configuration properties can be found at the link:https://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/#elasticsearch-integration[Hibernate Search manual]. [[query_autoconfig]] ==== Automatic configuration The attribute auto-config provides a simple way of configuring indexing based on the cache type. For replicated and local caches, the indexing is configured to be persisted on disk and not shared with any other processes. Also, it is configured so that minimum delay exists between the moment an object is indexed and the moment it is available for searches (near real time). [source,xml,options=""nowrap"",subs=attributes+] ---- include::config_examples/indexing_auto_config.xml[] ---- NOTE: it is possible to redefine any property added via auto-config, and also add new properties, allowing for advanced tuning. The auto config adds the following properties for replicated and local caches: [options=""header""] |============================================================================== | Property name | value | description | default.directory_provider | filesystem | Filesystem based index. More details at link:http://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/#search-configuration-directory[Hibernate Search documentation] | default.exclusive_index_use | true | indexing operation in exclusive mode, allowing Hibernate Search to optimize writes | default.indexmanager | near-real-time | make use of Lucene near real time feature, meaning indexed objects are promptly available to searches | default.reader.strategy | shared | Reuse index reader across several queries, thus avoiding reopening it |============================================================================== For distributed caches, the auto-config configure indexes in {brandname} itself, internally handled as a master-slave mechanism where indexing operations are sent to a single node which is responsible to write to the index. The auto config properties for distributed caches are: [options=""header""] |============================================================================== | Property name | value | description | default.directory_provider | infinispan | Indexes stored in {brandname}. More details at link:http://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/#infinispan-directories[Hibernate Search documentation] | default.exclusive_index_use | true | indexing operation in exclusive mode, allowing Hibernate Search to optimize writes | default.indexmanager | org.infinispan.query.indexmanager.InfinispanIndexManager | Delegates index writing to a single node in the {brandname} cluster | default.reader.strategy | shared | Reuse index reader across several queries, avoiding reopening it |============================================================================== [[query_massindexer]] ==== Re-indexing Occasionally you might need to rebuild the Lucene index by reconstructing it from the data stored in the Cache. You need to rebuild the index if you change the definition of what is indexed on your types, or if you change for example some _Analyzer_ parameter, as Analyzers affect how the index is written. Also, you might need to rebuild the index if you had it destroyed by some system administration mistake. To rebuild the index just get a reference to the MassIndexer and start it; beware it might take some time as it needs to reprocess all data in the grid! [source,java] ---- // Blocking execution SearchManager searchManager = Search.getSearchManager(cache); searchManager.getMassIndexer().start(); // Non blocking execution CompletableFuture future = searchManager.getMassIndexer().startAsync(); ---- TIP: This is also available as a `start` JMX operation on the link:{javadocroot}/jmxComponents.html#MassIndexer[MassIndexer MBean] registered under the name `org.infinispan:type=Query,manager=""{name-of-cache-manager}"",cache=""{name-of-cache}"",component=MassIndexer`. //TODO //[[query_indexless]] //==== Indexless //TODO //[[query_hybrid]] //==== Hybrid ==== Mapping Entities {brandname} relies on the rich API of link:http://hibernate.org/search/[Hibernate Search] in order to define fine grained configuration for indexing at entity level. This configuration includes which fields are annotated, which analyzers should be used, how to map nested objects and so on. Detailed documentation is available at link:https://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/#search-mapping[the Hibernate Search manual]. ===== @DocumentId Unlike Hibernate Search, using _@DocumentId_ to mark a field as identifier does not apply to {brandname} values; in {brandname} the identifier for all _@Indexed_ objects is the key used to store the value. You can still customize how the key is indexed using a combination of _@Transformable_ , custom types and custom _FieldBridge_ implementations. ===== @Transformable keys The key for each value needs to be indexed as well, and the key instance must be transformed in a _String_. {brandname} includes some default transformation routines to encode common primitives, but to use a custom key you must provide an implementation of _org.infinispan.query.Transformer_ . [small]*Registering a key Transformer via annotations* You can annotate your key class with _org.infinispan.query.Transformable_ and your custom transformer implementation will be picked up automatically: [source,java] ---- @Transformable(transformer = CustomTransformer.class) public class CustomKey { ... } public class CustomTransformer implements Transformer { @Override public Object fromString(String s) { ... return new CustomKey(...); } @Override public String toString(Object customType) { CustomKey ck = (CustomKey) customType; return ... } } ---- [small]*Registering a key Transformer via the cache indexing configuration* You can use the _key-transformers_ xml element in both embedded and server config: [source,xml,options=""nowrap"",subs=attributes+] ---- include::config_examples/indexing_key_transformer.xml[] ---- or alternatively, you can achieve the same effect by using the Java configuration API (embedded mode): [source,java] ---- ConfigurationBuilder builder = ... builder.indexing().autoConfig(true) .addKeyTransformer(CustomKey.class, CustomTransformer.class); ---- [small]*Registering a Transformer programmatically at runtime* Using this technique, you don't have to annotate your custom key type and you also do not add the transformer to the, cache indexing configuration, instead, you can add it to the _SearchManagerImplementor_ dynamically at runtime by invoking _org.infinispan.query.spi.SearchManagerImplementor.registerKeyTransformer(Class, Class)_: [source,java] ---- org.infinispan.query.spi.SearchManagerImplementor manager = Search.getSearchManager(cache).unwrap(SearchManagerImplementor.class); manager.registerKeyTransformer(keyClass, keyTransformerClass); ---- NOTE: This approach is deprecated since 10.0 because it can lead to situations when a newly started node receives cache entries via initial state transfer and is not able to index them because the needed key transformers are not yet registered (and can only be registered after the Cache has been fully started). This undesirable situation is avoided if you register your key transformers using the other available approaches (configuration and annotation). [[query_configuration_api]] ===== Programmatic mapping Instead of using annotations to map an entity to the index, it's also possible to configure it programmatically. In the following example we map an object _Author_ which is to be stored in the grid and made searchable on two properties but without annotating the class. [source,java] ---- import org.apache.lucene.search.Query; import org.hibernate.search.cfg.Environment; import org.hibernate.search.cfg.SearchMapping; import org.hibernate.search.query.dsl.QueryBuilder; import org.infinispan.Cache; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.Index; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.query.CacheQuery; import org.infinispan.query.Search; import org.infinispan.query.SearchManager; import java.io.IOException; import java.lang.annotation.ElementType; import java.util.Properties; SearchMapping mapping = new SearchMapping(); mapping.entity(Author.class).indexed() .property(""name"", ElementType.METHOD).field() .property(""surname"", ElementType.METHOD).field(); Properties properties = new Properties(); properties.put(Environment.MODEL_MAPPING, mapping); properties.put(""hibernate.search.[other options]"", ""[...]""); Configuration infinispanConfiguration = new ConfigurationBuilder() .indexing().index(Index.NONE) .withProperties(properties) .build(); DefaultCacheManager cacheManager = new DefaultCacheManager(infinispanConfiguration); Cache cache = cacheManager.getCache(); SearchManager sm = Search.getSearchManager(cache); Author author = new Author(1, ""Manik"", ""Surtani""); cache.put(author.getId(), author); QueryBuilder qb = sm.buildQueryBuilderForClass(Author.class).get(); Query q = qb.keyword().onField(""name"").matching(""Manik"").createQuery(); CacheQuery cq = sm.getQuery(q, Author.class); assert cq.getResultSize() == 1; ---- [[query_apis]] === Querying APIs You can query {brandname} using: * Lucene or Hibernate Search Queries. {brandname} exposes the Hibernate Search DSL, which produces Lucene queries. You can run Lucene queries on single nodes or broadcast queries to multiple nodes in an {brandname} cluster. * Ickle queries, a custom string-based query language with full-text extensions. [[query_hibernatesearch]] ==== Hibernate Search Apart from supporting Hibernate Search annotations to configure indexing, it's also possible to query the cache using other Hibernate Search APIs ===== Running Lucene queries To run a Lucene query directly, simply create and wrap it in a _CacheQuery_: [source,java] ---- import org.apache.lucene.search.Query; import org.infinispan.query.CacheQuery; import org.infinispan.query.Search; import org.infinispan.query.SearchManager; SearchManager searchManager = Search.getSearchManager(cache); Query query = searchManager.buildQueryBuilderForClass(Book.class).get() .keyword().wildcard().onField(""description"").matching(""*test*"").createQuery(); CacheQuery cacheQuery = searchManager.getQuery(query); ---- ===== Using the Hibernate Search DSL The Hibernate Search DSL can be used to create the Lucene Query, example: [source,java] ---- import org.infinispan.query.Search; import org.infinispan.query.SearchManager; import org.apache.lucene.search.Query; Cache cache = ... SearchManager searchManager = Search.getSearchManager(cache); Query luceneQuery = searchManager .buildQueryBuilderForClass(Book.class).get() .range().onField(""year"").from(2005).to(2010) .createQuery(); List results = searchManager.getQuery(luceneQuery).list(); ---- For a detailed description of the query capabilities of this DSL, see the relevant section of the link:https://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/#section-building-lucene-queries[Hibernate Search manual]. ===== Faceted Search {brandname} support link:https://en.wikipedia.org/wiki/Faceted_search[Faceted Searches] by using the Hibernate Search `FacetManager`: [source,java] ---- // Cache is indexed Cache cache = ... // Obtain the Search Manager SearchManager searchManager = Search.getSearchManager(cache); // Create the query builder QueryBuilder queryBuilder = searchManager.buildQueryBuilderForClass(Book.class).get(); // Build any Lucene Query. Here it's using the DSL to do a Lucene term query on a book name Query luceneQuery = queryBuilder.keyword().wildcard().onField(""name"").matching(""bitcoin"").createQuery(); // Wrap into a cache Query CacheQuery query = searchManager.getQuery(luceneQuery); // Define the Facet characteristics FacetingRequest request = queryBuilder.facet() .name(""year_facet"") .onField(""year"") .discrete() .orderedBy(FacetSortOrder.COUNT_ASC) .createFacetingRequest(); // Associated the FacetRequest with the query FacetManager facetManager = query.getFacetManager().enableFaceting(request); // Obtain the facets List facetList = facetManager.getFacets(""year_facet""); ---- A Faceted search like above will return the number books that match 'bitcoin' released on a yearly basis, for example: -------------------------------------- AbstractFacet{facetingName='year_facet', fieldName='year', value='2008', count=1} AbstractFacet{facetingName='year_facet', fieldName='year', value='2009', count=1} AbstractFacet{facetingName='year_facet', fieldName='year', value='2010', count=1} AbstractFacet{facetingName='year_facet', fieldName='year', value='2011', count=1} AbstractFacet{facetingName='year_facet', fieldName='year', value='2012', count=1} AbstractFacet{facetingName='year_facet', fieldName='year', value='2016', count=1} AbstractFacet{facetingName='year_facet', fieldName='year', value='2015', count=2} AbstractFacet{facetingName='year_facet', fieldName='year', value='2013', count=3} -------------------------------------- For more info about Faceted Search, see link:http://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/#query-faceting[Hibernate Search Faceting] [[query_spatial]] ===== Spatial Queries {brandname} also supports link:https://en.wikipedia.org/wiki/Spatial_query[Spatial Queries], allowing to combining full-text with restrictions based on distances, geometries or geographic coordinates. Example, we start by using the `@Spatial` annotation in our entity that will be searched, together with `@Latitude` and `@Longitude`: [source,java] ---- @Indexed @Spatial public class Restaurant { @Latitude private Double latitude; @Longitude private Double longitude; @Field(store = Store.YES) String name; // Getters, Setters and other members omitted } ---- to run spatial queries, the Hibernate Search DSL can be used: [source,java] ---- // Cache is configured as indexed Cache cache = ... // Obtain the SearchManager Searchmanager searchManager = Search.getSearchManager(cache); // Build the Lucene Spatial Query Query query = Search.getSearchManager(cache).buildQueryBuilderForClass(Restaurant.class).get() .spatial() .within( 2, Unit.KM ) .ofLatitude( centerLatitude ) .andLongitude( centerLongitude ) .createQuery(); // Wrap in a cache Query CacheQuery cacheQuery = searchManager.getQuery(query); List nearBy = cacheQuery.list(); ---- More info on link:http://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/#spatial[Hibernate Search manual] [[query_clustered_query_api]] ===== IndexedQueryMode It's possible to specify a query mode for indexed queries. IndexedQueryMode.BROADCAST allows to broadcast a query to each node of the cluster, retrieve the results and combine them before returning to the caller. It is suitable for use in conjunction with link:#query_non_shared_index[non-shared indexes], since each node's local index will have only a subset of the data indexed. IndexedQueryMode.FETCH will execute the query in the caller. If all the indexes for the cluster wide data are available locally, performance will be optimal, otherwise this query mode may involve fetching indexes data from remote nodes. The _IndexedQueryMode_ is supported for Ickle queries and Lucene Queries (but not for Query DSL). Example: [source,java] ---- CacheQuery broadcastQuery = Search.getSearchManager(cache).getQuery(new MatchAllDocsQuery(), IndexedQueryMode.BROADCAST); List result = broadcastQuery.list(); ---- [[query_dsl]] ==== {brandname} Query DSL NOTE: The Query DSL (QueryBuilder and related interfaces) are deprecated and will be removed in next major version. Please use Ickle queries instead. {brandname} provides its own query DSL, independent of Lucene and Hibernate Search. Decoupling the query API from the underlying query and indexing mechanism makes it possible to introduce new alternative engines in the future, besides Lucene, and still being able to use the same uniform query API. The current implementation of indexing and searching is still based on Hibernate Search and Lucene so all indexing related aspects presented in this chapter still apply. The new API simplifies the writing of queries by not exposing the user to the low level details of constructing Lucene query objects and also has the advantage of being available to remote Hot Rod clients. But before delving into further details, let's examine first a simple example of writing a query for the _Book_ entity from the previous example. .Query example using {brandname}'s query DSL [source,java] ---- import org.infinispan.query.dsl.*; // get the DSL query factory from the cache, to be used for constructing the Query object: QueryFactory qf = org.infinispan.query.Search.getQueryFactory(cache); // create a query for all the books that have a title which contains ""engine"": org.infinispan.query.dsl.Query query = qf.from(Book.class) .having(""title"").like(""%engine%"") .build(); // get the results: List list = query.list(); ---- The API is located in the _org.infinispan.query.dsl_ package. A query is created with the help of the _QueryFactory_ instance which is obtained from the per-cache _SearchManager_. Each _QueryFactory_ instance is bound to the same _Cache_ instance as the _SearchManager_, but it is otherwise a stateless and thread-safe object that can be used for creating multiple queries in parallel. Query creation starts with the invocation of the `from(Class entityType)` method which returns a _QueryBuilder_ object that is further responsible for creating queries targeted to the specified entity class from the given cache. NOTE: A query will always target a single entity type and is evaluated over the contents of a single cache. Running a query over multiple caches or creating queries that target several entity types (joins) is not supported. The _QueryBuilder_ accumulates search criteria and configuration specified through the invocation of its DSL methods and is ultimately used to build a _Query_ object by the invocation of the `QueryBuilder.build()` method that completes the construction. Being a stateful object, it cannot be used for constructing multiple queries at the same time (except for link:#nested_conditions[nested queries]) but can be reused afterwards. NOTE: This _QueryBuilder_ is different from the one from Hibernate Search but has a somewhat similar purpose, hence the same name. We are considering renaming it in near future to prevent ambiguity. Executing the query and fetching the results is as simple as invoking the `list()` method of the _Query_ object. Once executed the _Query_ object is not reusable. If you need to re-execute it in order to obtain fresh results then a new instance must be obtained by calling `QueryBuilder.build()`. ===== Filtering operators Constructing a query is a hierarchical process of composing multiple criteria and is best explained following this hierarchy. The simplest possible form of a query criteria is a restriction on the values of an entity attribute according to a filtering operator that accepts zero or more arguments. The entity attribute is specified by invoking the `having(String attributePath)` method of the query builder which returns an intermediate context object (link:{javadocroot}/org/infinispan/query/dsl/FilterConditionEndContext.html[_FilterConditionEndContext_]) that exposes all the available operators. Each of the methods defined by _FilterConditionEndContext_ is an operator that accepts an argument, except for `between` which has two arguments and `isNull` which has no arguments. The arguments are statically evaluated at the time the query is constructed, so if you're looking for a feature similar to SQL's correlated sub-queries, that is not currently available. [source,java] ---- // a single query criterion QueryBuilder qb = ... qb.having(""title"").eq(""Hibernate Search in Action""); ---- ._FilterConditionEndContext_ exposes the following filtering operators: [options=""header""] |============================================================================== | Filter | Arguments | Description | in | Collection values | Checks that the left operand is equal to one of the elements from the Collection of values given as argument. | in | Object... values | Checks that the left operand is equal to one of the (fixed) list of values given as argument. | contains | Object value | Checks that the left argument (which is expected to be an array or a Collection) contains the given element. | containsAll | Collection values | Checks that the left argument (which is expected to be an array or a Collection) contains all the elements of the given collection, in any order. | containsAll | Object... values | Checks that the left argument (which is expected to be an array or a Collection) contains all of the the given elements, in any order. | containsAny | Collection values | Checks that the left argument (which is expected to be an array or a Collection) contains any of the elements of the given collection. | containsAny | Object... values | Checks that the left argument (which is expected to be an array or a Collection) contains any of the the given elements. | isNull | | Checks that the left argument is null. | like | String pattern | Checks that the left argument (which is expected to be a String) matches a wildcard pattern that follows the JPA rules. | eq | Object value | Checks that the left argument is equal to the given value. | equal | Object value | Alias for eq. | gt | Object value | Checks that the left argument is greater than the given value. | gte | Object value | Checks that the left argument is greater than or equal to the given value. | lt | Object value | Checks that the left argument is less than the given value. | lte | Object value | Checks that the left argument is less than or equal to the given value. | between | Object from, Object to | Checks that the left argument is between the given range limits. |============================================================================== It's important to note that query construction requires a multi-step chaining of method invocation that must be done in the proper sequence, must be properly completed exactly _once_ and must not be done twice, or it will result in an error. The following examples are invalid, and depending on each case they lead to criteria being ignored (in benign cases) or an exception being thrown (in more serious ones). [source,java] ---- // Incomplete construction. This query does not have any filter on ""title"" attribute yet, // although the author may have intended to add one. QueryBuilder qb1 = ... qb1.having(""title""); Query q1 = qb1.build(); // consequently, this query matches all Book instances regardless of title! // Duplicated completion. This results in an exception at run-time. // Maybe the author intended to connect two conditions with a boolean operator, // but this does NOT actually happen here. QueryBuilder qb2 = ... qb2.having(""title"").like(""%Data Grid%""); qb2.having(""description"").like(""%clustering%""); // will throw java.lang.IllegalStateException: Sentence already started. Cannot use 'having(..)' again. Query q2 = qb2.build(); ---- ===== Filtering based on attributes of embedded entities The `having` method also accepts dot separated attribute paths for referring to _embedded entity_ attributes, so the following is a valid query: [source,java] ---- // match all books that have an author named ""Manik"" Query query = queryFactory.from(Book.class) .having(""author.name"").eq(""Manik"") .build(); ---- Each part of the attribute path must refer to an existing indexed attribute in the corresponding entity or embedded entity class respectively. It's possible to have multiple levels of embedding. ===== Boolean conditions Combining multiple attribute conditions with logical conjunction (`and`) and disjunction (`or`) operators in order to create more complex conditions is demonstrated in the following example. The well known operator precedence rule for boolean operators applies here, so the order of DSL method invocations during construction is irrelevant. Here `and` operator still has higher priority than `or` even though `or` was invoked first. [source,java] ---- // match all books that have ""Data Grid"" in their title // or have an author named ""Manik"" and their description contains ""clustering"" Query query = queryFactory.from(Book.class) .having(""title"").like(""%Data Grid%"") .or().having(""author.name"").eq(""Manik"") .and().having(""description"").like(""%clustering%"") .build(); ---- Boolean negation is achieved with the `not` operator, which has highest precedence among logical operators and applies only to the next simple attribute condition. [source,java] ---- // match all books that do not have ""Data Grid"" in their title and are authored by ""Manik"" Query query = queryFactory.from(Book.class) .not().having(""title"").like(""%Data Grid%"") .and().having(""author.name"").eq(""Manik"") .build(); ---- ===== Nested conditions Changing the precedence of logical operators is achieved with nested filter conditions. Logical operators can be used to connect two simple attribute conditions as presented before, but can also connect a simple attribute condition with the subsequent complex condition created with the same query factory. [source,java] ---- // match all books that have an author named ""Manik"" and their title contains // ""Data Grid"" or their description contains ""clustering"" Query query = queryFactory.from(Book.class) .having(""author.name"").eq(""Manik"") .and(queryFactory.having(""title"").like(""%Data Grid%"") .or().having(""description"").like(""%clustering%"")) .build(); ---- ===== Projections In some use cases returning the whole domain object is overkill if only a small subset of the attributes are actually used by the application, especially if the domain entity has embedded entities. The query language allows you to specify a subset of attributes (or attribute paths) to return - the projection. If projections are used then the `Query.list()` will not return the whole domain entity but will return a _List_ of _Object[]_, each slot in the array corresponding to a projected attribute. //TODO document what needs to be configured for an attribute to be available for projection. [source,java] ---- // match all books that have ""Data Grid"" in their title or description // and return only their title and publication year Query query = queryFactory.from(Book.class) .select(""title"", ""publicationYear"") .having(""title"").like(""%Data Grid%"") .or().having(""description"").like(""%Data Grid%"")) .build(); ---- ===== Sorting Ordering the results based on one or more attributes or attribute paths is done with the `QueryBuilder.orderBy( )` method which accepts an attribute path and a sorting direction. If multiple sorting criteria are specified, then the order of invocation of `orderBy` method will dictate their precedence. But you have to think of the multiple sorting criteria as acting together on the tuple of specified attributes rather than in a sequence of individual sorting operations on each attribute. //TODO document what needs to be configured for an attribute to be available for sorting. [source,java] ---- // match all books that have ""Data Grid"" in their title or description // and return them sorted by the publication year and title Query query = queryFactory.from(Book.class) .orderBy(""publicationYear"", SortOrder.DESC) .orderBy(""title"", SortOrder.ASC) .having(""title"").like(""%Data Grid%"") .or().having(""description"").like(""%Data Grid%"")) .build(); ---- ===== Pagination You can limit the number of returned results by setting the _maxResults_ property of _QueryBuilder_. This can be used in conjunction with setting the _startOffset_ in order to achieve pagination of the result set. [source,java] ---- // match all books that have ""clustering"" in their title // sorted by publication year and title // and return 3'rd page of 10 results Query query = queryFactory.from(Book.class) .orderBy(""publicationYear"", SortOrder.DESC) .orderBy(""title"", SortOrder.ASC) .startOffset(20) .maxResults(10) .having(""title"").like(""%clustering%"") .build(); ---- NOTE: Even if the results being fetched are limited to _maxResults_ you can still find the total number of matching results by calling `Query.getResultSize()`. //TODO Does pagination make sense if no stable sort criteria is defined? Luckily when running on Lucene and no sort criteria is specified we still have the order of relevance, but this has to be defined for other search engines. ===== Grouping and Aggregation {brandname} has the ability to group query results according to a set of grouping fields and construct aggregations of the results from each group by applying an aggregation function to the set of values that fall into each group. Grouping and aggregation can only be applied to projection queries. The supported aggregations are: avg, sum, count, max, min. The set of grouping fields is specified with the _groupBy(field)_ method, which can be invoked multiple times. The order used for defining grouping fields is not relevant. All fields selected in the projection must either be grouping fields or else they must be aggregated using one of the grouping functions described below. A projection field can be aggregated and used for grouping at the same time. A query that selects only grouping fields but no aggregation fields is legal. ⁠ Example: Grouping Books by author and counting them. [source,java] ---- Query query = queryFactory.from(Book.class) .select(Expression.property(""author""), Expression.count(""title"")) .having(""title"").like(""%engine%"") .groupBy(""author"") .build(); ---- NOTE: A projection query in which all selected fields have an aggregation function applied and no fields are used for grouping is allowed. In this case the aggregations will be computed globally as if there was a single global group. ===== Aggregations The following aggregation functions may be applied to a field: avg, sum, count, max, min * avg() - Computes the average of a set of numbers. Accepted values are primitive numbers and instances of _java.lang.Number_. The result is represented as _java.lang.Double_. If there are no non-null values the result is _null_ instead. * count() - Counts the number of non-null rows and returns a _java.lang.Long_. If there are no non-null values the result is _0_ instead. * max() - Returns the greatest value found. Accepted values must be instances of _java.lang.Comparable_. If there are no non-null values the result is _null_ instead. * min() - Returns the smallest value found. Accepted values must be instances of _java.lang.Comparable_. If there are no non-null values the result is _null_ instead. * sum() - Computes the sum of a set of Numbers. If there are no non-null values the result is _null_ instead. The following table indicates the return type based on the specified field. .Table sum return type |=== |Field Type |Return Type |Integral (other than BigInteger) |Long |Float or Double |Double |BigInteger |BigInteger |BigDecimal |BigDecimal |=== ===== Evaluation of queries with grouping and aggregation Aggregation queries can include filtering conditions, like usual queries. Filtering can be performed in two stages: before and after the grouping operation. All filter conditions defined before invoking the _groupBy_ method will be applied before the grouping operation is performed, directly to the cache entries (not to the final projection). These filter conditions may reference any fields of the queried entity type, and are meant to restrict the data set that is going to be the input for the grouping stage. All filter conditions defined after invoking the _groupBy_ method will be applied to the projection that results from the projection and grouping operation. These filter conditions can either reference any of the _groupBy_ fields or aggregated fields. Referencing aggregated fields that are not specified in the select clause is allowed; however, referencing non-aggregated and non-grouping fields is forbidden. Filtering in this phase will reduce the amount of groups based on their properties. Sorting may also be specified similar to usual queries. The ordering operation is performed after the grouping operation and can reference any of the _groupBy_ fields or aggregated fields. ===== Using Named Query Parameters Instead of building a new Query object for every execution it is possible to include named parameters in the query which can be substituted with actual values before execution. This allows a query to be defined once and be efficiently executed many times. Parameters can only be used on the right-hand side of an operator and are defined when the query is created by supplying an object produced by the _org.infinispan.query.dsl.Expression.param(String paramName)_ method to the operator instead of the usual constant value. Once the parameters have been defined they can be set by invoking either _Query.setParameter(parameterName, value)_ or _Query.setParameters(parameterMap)_ as shown in the examples below. ⁠ [source,java,tile=""Using Named Parameters""] ---- import org.infinispan.query.Search; import org.infinispan.query.dsl.*; [...] QueryFactory queryFactory = Search.getQueryFactory(cache); // Defining a query to search for various authors and publication years Query query = queryFactory.from(Book.class) .select(""title"") .having(""author"").eq(Expression.param(""authorName"")) .and() .having(""publicationYear"").eq(Expression.param(""publicationYear"")) .build(); // Set actual parameter values query.setParameter(""authorName"", ""Doe""); query.setParameter(""publicationYear"", 2010); // Execute the query List found = query.list(); ---- Alternatively, multiple parameters may be set at once by supplying a map of actual parameter values: ⁠ [source,java,title=""Setting multiple named parameters at once""] ---- import java.util.Map; import java.util.HashMap; [...] Map parameterMap = new HashMap<>(); parameterMap.put(""authorName"", ""Doe""); parameterMap.put(""publicationYear"", 2010); query.setParameters(parameterMap); ---- NOTE: A significant portion of the query parsing, validation and execution planning effort is performed during the first execution of a query with parameters. This effort is not repeated during subsequent executions leading to better performance compared to a similar query using constant values instead of query parameters. ===== More Query DSL samples Probably the best way to explore using the Query DSL API is to have a look at our tests suite. link:https://github.com/infinispan/infinispan/blob/master/query/src/test/java/org/infinispan/query/dsl/embedded/QueryDslConditionsTest.java[QueryDslConditionsTest] is a fine example. [[query_ickle]] ==== Ickle Create relational and full-text queries in both Library and Remote Client-Server mode with the Ickle query language. Ickle is string-based and has the following characteristics: * Query Java classes and supports Protocol Buffers. * Queries can target a single entity type. * Queries can filter on properties of embedded objects, including collections. * Supports projections, aggregations, sorting, named parameters. * Supports indexed and non-indexed execution. * Supports complex boolean expressions. * Supports full-text queries. * Does not support computations in expressions, such as `user.age > sqrt(user.shoeSize+3)`. * Does not support joins. * Does not support subqueries. * Is supported across various {brandname} APIs. Whenever a Query is produced by the QueryBuilder is accepted, including continuous queries or in event filters for listeners. To use the API, first obtain a QueryFactory to the cache and then call the .create() method, passing in the string to use in the query. For instance: [source,java,tile=""Using Ickle""] ---- QueryFactory qf = Search.getQueryFactory(remoteCache); Query q = qf.create(""from sample_bank_account.Transaction where amount > 20""); ---- When using Ickle all fields used with full-text operators must be both `Indexed` and `Analysed`. ===== Ickle Query Language Parser Syntax The parser syntax for the Ickle query language has some notable rules: * Whitespace is not significant. * Wildcards are not supported in field names. * A field name or path must always be specified, as there is no default field. * `&&` and `||` are accepted instead of `AND` or `OR` in both full-text and JPA predicates. * `!` may be used instead of `NOT`. * A missing boolean operator is interpreted as `OR`. * String terms must be enclosed with either single or double quotes. * Fuzziness and boosting are not accepted in arbitrary order; fuzziness always comes first. * `!=` is accepted instead of `<>`. * Boosting cannot be applied to `>`,`>=`,`<`,`⇐` operators. Ranges may be used to achieve the same result. ===== Fuzzy Queries To execute a fuzzy query add `~` along with an integer, representing the distance from the term used, after the term. For instance [source,java,tile=""Fuzzy Queries in Ickle""] ---- Query fuzzyQuery = qf.create(""from sample_bank_account.Transaction where description : 'cofee'~2""); ---- ===== Range Queries To execute a range query define the given boundaries within a pair of braces, as seen in the following example: [source,java,tile=""Range queries with Ickle""] ---- Query rangeQuery = qf.create(""from sample_bank_account.Transaction where amount : [20 to 50]""); ---- ===== Phrase Queries A group of words may be searched by surrounding them in quotation marks, as seen in the following example: [source,java,tile=""Phrase queries with Ickle""] ---- Query q = qf.create(""from sample_bank_account.Transaction where description : 'bus fare'""); ---- ===== Proximity Queries To execute a proximity query, finding two terms within a specific distance, add a `~` along with the distance after the phrase. For instance, the following example will find the words canceling and fee provided they are not more than 3 words apart: [source,java,tile=""Proximity queries with Ickle""] ---- Query proximityQuery = qf.create(""from sample_bank_account.Transaction where description : 'canceling fee'~3 ""); ---- ===== Wildcard Queries Both single-character and multi-character wildcard searches may be performed: * A single-character wildcard search may be used with the ? character. * A multi-character wildcard search may be used with the * character. To search for text or test the following single-character wildcard search would be used: [source,java,tile=""Single-character wildcard queries with Ickle""] ---- Query wildcardQuery = qf.create(""from sample_bank_account.Transaction where description : 'te?t'""); ---- To search for test, tests, or tester the following multi-character wildcard search would be useD: [source,java,tile=""Multi-character wildcard queries with Ickle""] ---- Query wildcardQuery = qf.create(""from sample_bank_account.Transaction where description : 'test*'""); ---- ===== Regular Expression Queries Regular expression queries may be performed by specifing a pattern between /. Ickle uses Lucene’s regular expression syntax, so to search for the words moat or boat the following could be used: [source,java,tile=""Regular Expression queries with Ickle""] ---- Query regExpQuery = qf.create(""from sample_library.Book where title : /[mb]oat/""); ---- ===== Boosting Queries Terms may be boosted by adding a ^ after the term to increase their relevance in a given query, the higher the boost factor the more relevant the term will be. For instance to search for titles containing beer and wine with a higher relevance on beer, by a factor of 3, the following could be used: [source,java,tile=""Boosting queries with Ickle""] ---- Query boostedQuery = qf.create(""from sample_library.Book where title : beer^3 OR wine""); ---- [[query_continuous]] ==== Continuous Query Continuous Queries allow an application to register a listener which will receive the entries that currently match a query filter, and will be continuously notified of any changes to the queried data set that result from further cache operations. This includes incoming matches, for values that have joined the set, updated matches, for matching values that were modified and continue to match, and outgoing matches, for values that have left the set. By using a Continuous Query the application receives a steady stream of events instead of having to repeatedly execute the same query to discover changes, resulting in a more efficient use of resources. For instance, all of the following use cases could utilize Continuous Queries: * Return all persons with an age between 18 and 25 (assuming the Person entity has an _age_ property and is updated by the user application). * Return all transactions higher than $2000. * Return all times where the lap speed of F1 racers were less than 1:45.00s (assuming the cache contains Lap entries and that laps are entered live during the race). ===== Continuous Query Execution A continuous query uses a listener that is notified when: * An entry starts matching the specified query, represented by a _Join_ event. * A matching entry is updated and continues to match the query, represented by an _Update_ event. * An entry stops matching the query, represented by a _Leave_ event. When a client registers a continuous query listener it immediately begins to receive the results currently matching the query, received as _Join_ events as described above. In addition, it will receive subsequent notifications when other entries begin matching the query, as _Join_ events, or stop matching the query, as _Leave_ events, as a consequence of any cache operations that would normally generate creation, modification, removal, or expiration events. Updated cache entries will generate _Update_ events if the entry matches the query filter before and after the operation. To summarize, the logic used to determine if the listener receives a _Join_, _Update_ or _Leave_ event is: . If the query on both the old and new values evaluate false, then the event is suppressed. . If the query on the old value evaluates false and on the new value evaluates true, then a _Join_ event is sent. . If the query on both the old and new values evaluate true, then an _Update_ event is sent. . If the query on the old value evaluates true and on the new value evaluates false, then a _Leave_ event is sent. . If the query on the old value evaluates true and the entry is removed or expired, then a _Leave_ event is sent. NOTE: Continuous Queries can use the full power of the Query DSL except: grouping, aggregation, and sorting operations. ===== Running Continuous Queries To create a continuous query you'll start by creating a Query object first. This is described in link:#query_dsl[the Query DSL section]. Then you'll need to obtain the ContinuousQuery (_org.infinispan.query.api.continuous.ContinuousQuery_) object of your cache and register the query and a continuous query listener (_org.infinispan.query.api.continuous.ContinuousQueryListener_) with it. A ContinuousQuery object associated to a cache can be obtained by calling the static method _org.infinispan.client.hotrod.Search.getContinuousQuery(RemoteCache cache)_ if running in remote mode or _org.infinispan.query.Search.getContinuousQuery(Cache cache)_ when running in embedded mode. Once the listener has been created it may be registered by using the addContinuousQueryListener method of ContinuousQuery: [source,java] ---- continuousQuery.addContinuousQueryListener(query, listener); ---- The following example demonstrates a simple continuous query use case in embedded mode: ⁠ [source,java,title=""Registering a Continuous Query""] ---- import org.infinispan.query.api.continuous.ContinuousQuery; import org.infinispan.query.api.continuous.ContinuousQueryListener; import org.infinispan.query.Search; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.Query; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; [...] // We have a cache of Persons Cache cache = ... // We begin by creating a ContinuousQuery instance on the cache ContinuousQuery continuousQuery = Search.getContinuousQuery(cache); // Define our query. In this case we will be looking for any Person instances under 21 years of age. QueryFactory queryFactory = Search.getQueryFactory(cache); Query query = queryFactory.from(Person.class) .having(""age"").lt(21) .build(); final Map matches = new ConcurrentHashMap(); // Define the ContinuousQueryListener ContinuousQueryListener listener = new ContinuousQueryListener() { @Override public void resultJoining(Integer key, Person value) { matches.put(key, value); } @Override public void resultUpdated(Integer key, Person value) { // we do not process this event } @Override public void resultLeaving(Integer key) { matches.remove(key); } }; // Add the listener and the query continuousQuery.addContinuousQueryListener(query, listener); [...] // Remove the listener to stop receiving notifications continuousQuery.removeContinuousQueryListener(listener); ---- As Person instances having an age less than 21 are added to the cache they will be received by the listener and will be placed into the _matches_ map, and when these entries are removed from the cache or their age is modified to be greater or equal than 21 they will be removed from _matches_. ===== Removing Continuous Queries To stop the query from further execution just remove the listener: [source,java] ---- continuousQuery.removeContinuousQueryListener(listener); ---- ===== Notes on performance of Continuous Queries Continuous queries are designed to provide a constant stream of updates to the application, potentially resulting in a very large number of events being generated for particularly broad queries. A new temporary memory allocation is made for each event. This behavior may result in memory pressure, potentially leading to _OutOfMemoryErrors_ (especially in remote mode) if queries are not carefully designed. To prevent such issues it is strongly recommended to ensure that each query captures the minimal information needed both in terms of number of matched entries and size of each match (projections can be used to capture the interesting properties), and that each _ContinuousQueryListener_ is designed to quickly process all received events without blocking and to avoid performing actions that will lead to the generation of new matching events from the cache it listens to. [[query_remote]] == Remote Querying Apart from supporting indexing and searching of Java entities to embedded clients, {brandname} introduced support for remote, language neutral, querying. This leap required two major changes: * Since non-JVM clients cannot benefit from directly using link:http://lucene.apache.org/[Apache Lucene]'s Java API, {brandname} defines its own new link:#query_dsl[query language], based on an internal DSL that is easily implementable in all languages for which we currently have an implementation of the Hot Rod client. * In order to enable indexing, the entities put in the cache by clients can no longer be opaque binary blobs understood solely by the client. Their structure has to be known to both server and client, so a common way of encoding structured data had to be adopted. Furthermore, allowing multi-language clients to access the data requires a language and platform-neutral encoding. Google's link:http://code.google.com/p/protobuf/[Protocol Buffers] was elected as an encoding format for both over-the-wire and storage due to its efficiency, robustness, good multi-language support and support for schema evolution. [[storing_protobuf]] === Storing Protobuf encoded entities Remote clients that want to be able to index and query their stored entities must do so using the ProtoStream marshaller. This is _key_ for the search capability to work. But it's also possible to store Protobuf entities just for gaining the benefit of platform independence and not enable indexing if you do not need it. [[enable_indexing]] === Indexing of Protobuf encoded entries After configuring the client as described in the previous section you can start configuring indexing for your caches on the server side. Activating indexing and the various indexing specific configurations is identical to embedded mode and is detailed in the link:#query_configuration_api[Querying {brandname}] chapter. There is however an extra configuration step involved. While in embedded mode the indexing metadata is obtained via Java reflection by analyzing the presence of various Hibernate Search annotations on the entry's class, this is obviously not possible if the entry is protobuf encoded. The server needs to obtain the relevant metadata from the same descriptor (.proto file) as the client. The descriptors are stored in a dedicated cache on the server named _'___protobuf_metadata'_. Both keys and values in this cache are plain strings. Registering a new schema is therefore as simple as performing a _put_ operation on this cache using the schema's name as key and the schema file itself as the value. Alternatively you can use the CLI (via the cache-container=*:register-proto-schemas() operation), the Management Console or the _ProtobufMetadataManager_ MBean via JMX. Be aware that, when security is enabled, access to the schema cache via the remote protocols requires that the user belongs to the pass:['___schema_manager'] role. NOTE: Even if indexing is enabled for a cache no fields of Protobuf encoded entries will be indexed unless you use the _@Indexed_ and _@Field_ protobuf schema documentation annotations in order to specify what fields need to get indexed. === A remote query example In this example, we will show you how to configure the client to utilise the example link:#protostream[LibraryInitializerImpl], put some data in the cache and then try to search for it. Note, the following example assumes that link:#enable_indexing[Indexing has been enabled] by registering the required .proto files with the `___protobuf_metadata` cache. [source,java] ---- include::code_examples/RemoteQuery.java[] ---- The key part of creating a query is obtaining the _QueryFactory_ for the remote cache using the _org.infinispan.client.hotrod.Search.getQueryFactory()_ method. Once you have this creating the query is similar to embedded mode which is covered in link:#query_dsl[this] section. [[analysis]] === Analysis Analysis is a process that converts input data into one or more terms that you can index and query. ==== Default Analyzers {brandname} provides a set of default analyzers as follows: [%header,cols=2*] |=== | Definition | Description | `standard` | Splits text fields into tokens, treating whitespace and punctuation as delimiters. | `simple` | Tokenizes input streams by delimiting at non-letters and then converting all letters to lowercase characters. Whitespace and non-letters are discarded. | `whitespace` | Splits text streams on whitespace and returns sequences of non-whitespace characters as tokens. | `keyword` | Treats entire text fields as single tokens. | `stemmer` | Stems English words using the Snowball Porter filter. | `ngram` | Generates n-gram tokens that are 3 grams in size by default. | `filename` | Splits text fields into larger size tokens than the `standard` analyzer, treating whitespace as a delimiter and converts all letters to lowercase characters. |=== These analyzer definitions are based on Apache Lucene and are provided ""as-is"". For more information about tokenizers, filters, and CharFilters, see the appropriate Lucene documentation. ==== Using Analyzer Definitions To use analyzer definitions, reference them by name in the _.proto_ schema file. . Include the `Analyze.YES` attribute to indicate that the property is analyzed. . Specify the analyzer definition with the `@Analyzer` annotation. The following example shows referenced analyzer definitions: [source,protobuf,options=""nowrap""] ---- /* @Indexed */ message TestEntity { /* @Field(store = Store.YES, analyze = Analyze.YES, analyzer = @Analyzer(definition = ""keyword"")) */ optional string id = 1; /* @Field(store = Store.YES, analyze = Analyze.YES, analyzer = @Analyzer(definition = ""simple"")) */ optional string name = 2; } ---- ==== Creating Custom Analyzer Definitions If you require custom analyzer definitions, do the following: . Create an implementation of the `ProgrammaticSearchMappingProvider` interface packaged in a `JAR` file. . Provide a file named `org.infinispan.query.spi.ProgrammaticSearchMappingProvider` in the `META-INF/services/` directory of your `JAR`. This file should contain the fully qualified class name of your implementation. . Copy the `JAR` to the `standalone/deployments` directory of your {brandname} installation. + [IMPORTANT] ==== Your deployment must be available to the {brandname} server during startup. You cannot add the deployment if the server is already running. ==== + The following is an example implementation of the `ProgrammaticSearchMappingProvider` interface: + [source,java,options=""nowrap""] ---- import org.apache.lucene.analysis.core.LowerCaseFilterFactory; import org.apache.lucene.analysis.core.StopFilterFactory; import org.apache.lucene.analysis.standard.StandardFilterFactory; import org.apache.lucene.analysis.standard.StandardTokenizerFactory; import org.hibernate.search.cfg.SearchMapping; import org.infinispan.Cache; import org.infinispan.query.spi.ProgrammaticSearchMappingProvider; public final class MyAnalyzerProvider implements ProgrammaticSearchMappingProvider { @Override public void defineMappings(Cache cache, SearchMapping searchMapping) { searchMapping .analyzerDef(""standard-with-stop"", StandardTokenizerFactory.class) .filter(StandardFilterFactory.class) .filter(LowerCaseFilterFactory.class) .filter(StopFilterFactory.class); } } ---- + . Specify the `JAR` in the cache container configuration, for example: + [source,xml,options=""nowrap"",subs=attributes+] ---- include::config_examples/custom_deployment_analyzers_jar.xml[] ---- == Statistics Query link:http://docs.jboss.org/hibernate/search/5.7/api/org/hibernate/search/stat/Statistics.html[_Statistics_] can be obtained from the _SearchManager_, as demonstrated in the following code snippet. [source,java] ---- SearchManager searchManager = Search.getSearchManager(cache); org.hibernate.search.stat.Statistics statistics = searchManager.getStatistics(); ---- TIP: This data is also available via JMX through the link:https://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/#_statisticsinfombean[Hibernate Search StatisticsInfoMBean] registered under the name `org.infinispan:type=Query,manager=""{name-of-cache-manager}"",cache=""{name-of-cache}"",component=Statistics`. Please note this MBean is always registered by {brandname} but the statistics are collected only if statistics collection is enabled at cache level. WARNING: Hibernate Search has its own configuration properties `hibernate.search.jmx_enabled` and `hibernate.search.generate_statistics` for JMX statistics as explained link:https://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/#search-monitoring[here]. Using them with {brandname} Query is forbidden as it will only lead to duplicated MBeans and unpredictable results. [[query_performance]] == Performance Tuning === Batch writing in SYNC mode By default, the link:#query_index_manager[Index Managers] work in sync mode, meaning when data is written to {brandname}, it will perform the indexing operations synchronously. This synchronicity guarantees indexes are always consistent with the data (and thus visible in searches), but can slowdown write operations since it will also perform a commit to the index. Committing is an extremely expensive operation in Lucene, and for that reason, multiple writes from different nodes can be automatically batched into a single commit to reduce the impact. So, when doing data loads to {brandname} with index enabled, try to use multiple threads to take advantage of this batching. If using multiple threads does not result in the required performance, an alternative is to load data with indexing temporarily disabled and run a link:#query_massindexer[re-indexing] operation afterwards. This can be done writing data with the `SKIP_INDEXING` flag: [source,java] ---- cache.getAdvancedCache().withFlags(Flag.SKIP_INDEXING).put(""key"",""value""); ---- === Writing using async mode If it's acceptable a small delay between data writes and when that data is visible in queries, an index manager can be configured to work in *async mode*. The async mode offers much better writing performance, since in this mode commits happen at a configurable interval. Configuration: [source,xml,options=""nowrap"",subs=attributes+] ---- include::config_examples/indexing_async.xml[] ---- === Index reader async strategy Lucene internally works with snapshots of the index: once an _IndexReader_ is opened, it will only see the index changes up to the point it was opened; further index changes will not be visible until the _IndexReader_ is refreshed. The Index Managers used in {brandname} by default will check the freshness of the index readers before every query and refresh them if necessary. It is possible to tune this strategy to relax this freshness checking to a pre-configured interval by using the `reader.strategy` configuration set as `async`: [source,xml,options=""nowrap"",subs=attributes+] ---- include::config_examples/indexing_async_reader_strategy.xml[] ---- === Lucene Options It is possible to apply tuning options in Lucene directly. For more details, see the link:++https://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/#_lucene_configuration++[Hibernate Search manual]. ",16320,True,2856.443858181375,median "[role=""xpack""] [[security-settings]] === Security settings in {es} ++++ Security settings ++++ By default, the {es} {security-features} are disabled when you have a basic or trial license. To enable {security-features}, use the `xpack.security.enabled` setting. You configure `xpack.security` settings to <> and perform message authentication, <>, <>, <>, and <>. All of these settings can be added to the `elasticsearch.yml` configuration file, with the exception of the secure settings, which you add to the {es} keystore. For more information about creating and updating the {es} keystore, see <>. [float] [[general-security-settings]] ==== General security settings `xpack.security.enabled`:: Set to `true` to enable {es} {security-features} on the node. + + -- If set to `false`, which is the default value for basic and trial licenses, {security-features} are disabled. It also affects all {kib} instances that connect to this {es} instance; you do not need to disable {security-features} in those `kibana.yml` files. For more information about disabling {security-features} in specific {kib} instances, see {kibana-ref}/security-settings-kb.html[{kib} security settings]. TIP: If you have gold or higher licenses, the default value is `true`; we recommend that you explicitly add this setting to avoid confusion. -- `xpack.security.hide_settings`:: A comma-separated list of settings that are omitted from the results of the <>. You can use wildcards to include multiple settings in the list. For example, the following value hides all the settings for the ad1 active_directory realm: `xpack.security.authc.realms.active_directory.ad1.*`. The API already omits all `ssl` settings, `bind_dn`, and `bind_password` due to the sensitive nature of the information. `xpack.security.fips_mode.enabled`:: Enables fips mode of operation. Set this to `true` if you run this {es} instance in a FIPS 140-2 enabled JVM. For more information, see <>. Defaults to `false`. [float] [[password-hashing-settings]] ==== Password hashing settings `xpack.security.authc.password_hashing.algorithm`:: Specifies the hashing algorithm that is used for secure user credential storage. See <>. Defaults to `bcrypt`. [float] [[anonymous-access-settings]] ==== Anonymous access settings You can configure the following anonymous access settings in `elasticsearch.yml`. For more information, see <>. `xpack.security.authc.anonymous.username`:: The username (principal) of the anonymous user. Defaults to `_es_anonymous_user`. `xpack.security.authc.anonymous.roles`:: The roles to associate with the anonymous user. Required. `xpack.security.authc.anonymous.authz_exception`:: When `true`, an HTTP 403 response is returned if the anonymous user does not have the appropriate permissions for the requested action. The user is not prompted to provide credentials to access the requested resource. When set to `false`, an HTTP 401 response is returned and the user can provide credentials with the appropriate permissions to gain access. Defaults to `true`. [float] [[security-automata-settings]] ==== Automata Settings In places where the {security-features} accept wildcard patterns (e.g. index patterns in roles, group matches in the role mapping API), each pattern is compiled into an Automaton. The follow settings are available to control this behaviour. `xpack.security.automata.max_determinized_states`:: The upper limit on how many automaton states may be created by a single pattern. This protects against too-difficult (e.g. exponentially hard) patterns. Defaults to `100,000`. `xpack.security.automata.cache.enabled`:: Whether to cache the compiled automata. Compiling automata can be CPU intensive and may slowdown some operations. The cache reduces the frequency with which automata need to be compiled. Defaults to `true`. `xpack.security.automata.cache.size`:: The maximum number of items to retain in the automata cache. Defaults to `10,000`. `xpack.security.automata.cache.ttl`:: The length of time to retain in an item in the automata cache (based on most recent usage). Defaults to `48h` (48 hours). [float] [[field-document-security-settings]] ==== Document and field level security settings You can set the following document and field level security settings in `elasticsearch.yml`. For more information, see <>. `xpack.security.dls_fls.enabled`:: Set to `false` to prevent document and field level security from being configured. Defaults to `true`. `xpack.security.dls.bitset.cache.ttl`:: The time-to-live for cached `BitSet` entries for document level security. Document level security queries may depend on Lucene BitSet objects, and these are automatically cached to improve performance. Defaults to expire entries that are unused for `168h` (7 days). `xpack.security.dls.bitset.cache.size`:: The maximum memory usage of cached `BitSet` entries for document level security. Document level security queries may depend on Lucene BitSet objects, and these are automatically cached to improve performance. Defaults to `50mb`, after which least-recently-used entries will be evicted. [float] [[token-service-settings]] ==== Token service settings You can set the following token service settings in `elasticsearch.yml`. `xpack.security.authc.token.enabled`:: Set to `false` to disable the built-in token service. Defaults to `true` unless `xpack.security.http.ssl.enabled` is `false`. This prevents sniffing the token from a connection over plain http. `xpack.security.authc.token.timeout`:: The length of time that a token is valid for. By default this value is `20m` or 20 minutes. The maximum value is 1 hour. [float] [[api-key-service-settings]] ==== API key service settings You can set the following API key service settings in `elasticsearch.yml`. `xpack.security.authc.api_key.enabled`:: Set to `false` to disable the built-in API key service. Defaults to `true` unless `xpack.security.http.ssl.enabled` is `false`. This prevents sniffing the API key from a connection over plain http. `xpack.security.authc.api_key.hashing.algorithm`:: Specifies the hashing algorithm that is used for securing API key credentials. See <>. Defaults to `pbkdf2`. `xpack.security.authc.api_key.cache.ttl`:: The time-to-live for cached API key entries. A API key id and a hash of its API key are cached for this period of time. Specify the time period using the standard {es} <>. Defaults to `1d`. `xpack.security.authc.api_key.cache.max_keys`:: The maximum number of API key entries that can live in the cache at any given time. Defaults to 10,000. `xpack.security.authc.api_key.cache.hash_algo`:: (Expert Setting) The hashing algorithm that is used for the in-memory cached API key credentials. For possible values, see <>. Defaults to `ssha256`. [float] [[realm-settings]] ==== Realm settings You configure realm settings in the `xpack.security.authc.realms` namespace in `elasticsearch.yml`. For example: [source,yaml] ---------------------------------------- xpack.security.authc.realms: native.realm1: order: 0 ... ldap.realm2: order: 1 ... active_directory.realm3: order: 2 ... ... ---------------------------------------- The valid settings vary depending on the realm type. For more information, see <>. [float] [[ref-realm-settings]] ===== Settings valid for all realms `type`:: The type of the realm: `native`, `ldap`, `active_directory`, `pki`, or `file`. Required. `order`:: The priority of the realm within the realm chain. Realms with a lower order are consulted first. Although not required, use of this setting is strongly recommended when you configure multiple realms. Defaults to `Integer.MAX_VALUE`. `enabled`:: Indicates whether a realm is enabled. You can use this setting to disable a realm without removing its configuration information. Defaults to `true`. [[ref-native-settings]] [float] ===== Native realm settings For a native realm, the `type` must be set to `native`. In addition to the <>, you can specify the following optional settings: `cache.ttl`:: The time-to-live for cached user entries. A user and a hash of its credentials are cached for this period of time. Specify the time period using the standard {es} <>. Defaults to `20m`. `cache.max_users`:: The maximum number of user entries that can live in the cache at any given time. Defaults to 100,000. `cache.hash_algo`:: (Expert Setting) The hashing algorithm that is used for the in-memory cached user credentials. For possible values, see <>. Defaults to `ssha256`. `authentication.enabled`:: If set to `false`, disables authentication support in this realm, so that it only supports user lookups. (See the <> and <> features). Defaults to `true`. [[ref-users-settings]] [float] ===== File realm settings The `type` setting must be set to `file`. In addition to the <>, you can specify the following settings: `cache.ttl`:: The time-to-live for cached user entries. A user and a hash of its credentials are cached for this configured period of time. Defaults to `20m`. Specify values using the standard {es} <>. Defaults to `20m`. `cache.max_users`:: The maximum number of user entries that can live in the cache at a given time. Defaults to 100,000. `cache.hash_algo`:: (Expert Setting) The hashing algorithm that is used for the in-memory cached user credentials. See <>. Defaults to `ssha256`. `authentication.enabled`:: If set to `false`, disables authentication support in this realm, so that it only supports user lookups. (See the <> and <> features). Defaults to `true`. [[ref-ldap-settings]] [float] ===== LDAP realm settings The `type` setting must be set to `ldap`. In addition to the <>, you can specify the following settings: `url`:: One or more LDAP URLs in the `ldap[s]://:` format. Required. + To provide multiple URLs, use a YAML array (`[""ldap://server1:636"", ""ldap://server2:636""]`) or comma-separated string (`""ldap://server1:636, ldap://server2:636""`). + While both are supported, you can't mix the `ldap` and `ldaps` protocols. `load_balance.type`:: The behavior to use when there are multiple LDAP URLs defined. For supported values see <>. Defaults to `failover`. `load_balance.cache_ttl`:: When using `dns_failover` or `dns_round_robin` as the load balancing type, this setting controls the amount of time to cache DNS lookups. Defaults to `1h`. `bind_dn`:: The DN of the user that is used to bind to the LDAP and perform searches. Only applicable in user search mode. If not specified, an anonymous bind is attempted. Defaults to Empty. Due to its potential security impact, `bind_dn` is not exposed via the <>. `bind_password`:: deprecated[6.3] Use `secure_bind_password` instead. The password for the user that is used to bind to the LDAP directory. Defaults to Empty. Due to its potential security impact, `bind_password` is not exposed via the <>. `secure_bind_password` (<>):: The password for the user that is used to bind to the LDAP directory. Defaults to Empty. `user_dn_templates`:: The DN template that replaces the user name with the string `{0}`. This setting is multivalued; you can specify multiple user contexts. Required to operate in user template mode. If `user_search.base_dn` is specified, this setting is not valid. For more information on the different modes, see <>. `authorization_realms`:: The names of the realms that should be consulted for delegated authorization. If this setting is used, then the LDAP realm does not perform role mapping and instead loads the user from the listed realms. The referenced realms are consulted in the order that they are defined in this list. See <>. + -- NOTE: If any settings starting with `user_search` are specified, the `user_dn_templates` settings are ignored. -- `user_group_attribute`:: Specifies the attribute to examine on the user for group membership. If any `group_search` settings are specified, this setting is ignored. Defaults to `memberOf`. `user_search.base_dn`:: Specifies a container DN to search for users. Required to operated in user search mode. If `user_dn_templates` is specified, this setting is not valid. For more information on the different modes, see <>. `user_search.scope`:: The scope of the user search. Valid values are `sub_tree`, `one_level` or `base`. `one_level` only searches objects directly contained within the `base_dn`. `sub_tree` searches all objects contained under `base_dn`. `base` specifies that the `base_dn` is the user object, and that it is the only user considered. Defaults to `sub_tree`. `user_search.filter`:: Specifies the filter used to search the directory in attempts to match an entry with the username provided by the user. Defaults to `(uid={0})`. `{0}` is substituted with the username provided when searching. `user_search.attribute`:: deprecated[5.6] Use `user_search.filter` instead. The attribute to match with the username sent with the request. Defaults to `uid`. `user_search.pool.enabled`:: Enables or disables connection pooling for user search. If set to `false`, a new connection is created for every search. The default is `true` when `bind_dn` is set. `user_search.pool.size`:: The maximum number of connections to the LDAP server to allow in the connection pool. Defaults to `20`. `user_search.pool.initial_size`:: The initial number of connections to create to the LDAP server on startup. Defaults to `0`. If the LDAP server is down, values greater than `0` could cause startup failures. `user_search.pool.health_check.enabled`:: Enables or disables a health check on LDAP connections in the connection pool. Connections are checked in the background at the specified interval. Defaults to `true`. `user_search.pool.health_check.dn`:: The distinguished name that is retrieved as part of the health check. Defaults to the value of `bind_dn` if present; if not, falls back to `user_search.base_dn`. `user_search.pool.health_check.interval`:: The interval to perform background checks of connections in the pool. Defaults to `60s`. `group_search.base_dn`:: The container DN to search for groups in which the user has membership. When this element is absent, {es} searches for the attribute specified by `user_group_attribute` set on the user in order to determine group membership. `group_search.scope`:: Specifies whether the group search should be `sub_tree`, `one_level` or `base`. `one_level` only searches objects directly contained within the `base_dn`. `sub_tree` searches all objects contained under `base_dn`. `base` specifies that the `base_dn` is a group object, and that it is the only group considered. Defaults to `sub_tree`. `group_search.filter`:: Specifies a filter to use to look up a group. When not set, the realm searches for `group`, `groupOfNames`, `groupOfUniqueNames`, or `posixGroup` with the attributes `member`, `memberOf`, or `memberUid`. Any instance of `{0}` in the filter is replaced by the user attribute defined in `group_search.user_attribute`. `group_search.user_attribute`:: Specifies the user attribute that is fetched and provided as a parameter to the filter. If not set, the user DN is passed into the filter. Defaults to Empty. `unmapped_groups_as_roles`:: If set to `true`, the names of any unmapped LDAP groups are used as role names and assigned to the user. A group is considered to be _unmapped_ if it is not referenced in a <>. API-based role mappings are not considered. Defaults to `false`. `files.role_mapping`:: The <> for the <>. Defaults to `ES_PATH_CONF/role_mapping.yml`. `follow_referrals`:: Specifies whether {es} should follow referrals returned by the LDAP server. Referrals are URLs returned by the server that are to be used to continue the LDAP operation (for example, search). Defaults to `true`. `metadata`:: A list of additional LDAP attributes that should be loaded from the LDAP server and stored in the authenticated user's metadata field. `timeout.tcp_connect`:: The TCP connect timeout period for establishing an LDAP connection. An `s` at the end indicates seconds, or `ms` indicates milliseconds. Defaults to `5s` (5 seconds ). `timeout.tcp_read`:: The TCP read timeout period after establishing an LDAP connection. An `s` at the end indicates seconds, or `ms` indicates milliseconds. Defaults to `5s` (5 seconds ). `timeout.ldap_search`:: The LDAP Server enforced timeout period for an LDAP search. An `s` at the end indicates seconds, or `ms` indicates milliseconds. Defaults to `5s` (5 seconds ). `ssl.key`:: Path to a PEM encoded file containing the private key, which is used if the LDAP server requires client authentication. `ssl.key` and `ssl.keystore.path` cannot be used at the same time. `ssl.key_passphrase`:: The passphrase that is used to decrypt the private key. This value is optional as the key may not be encrypted. `ssl.secure_key_passphrase` (<>):: The passphrase that is used to decrypt the private key. `ssl.certificate`:: Path to a PEM encoded file containing the certificate (or certificate chain) that will be presented to clients when they connect. `ssl.certificate_authorities`:: List of paths to PEM encoded certificate files that should be trusted. `ssl.certificate_authorities` and `ssl.truststore.path` cannot be used at the same time. `ssl.keystore.path`:: The path to the Java Keystore file that contains a private key and certificate. `ssl.key` and `ssl.keystore.path` may not be used at the same time. `ssl.keystore.type`:: The format of the keystore file. Should be `jks` to use the Java Keystore format, `PKCS12` to use PKCS#12 files, or `PKCS11` to use a PKCS#11 token. The default is `jks`. `ssl.keystore.password`:: The password to the keystore. `ssl.keystore.secure_password` (<>):: The password to the keystore. `ssl.keystore.key_password`:: The password for the key in the keystore. Defaults to the keystore password. `ssl.keystore.secure_key_password`:: The password for the key in the keystore. Defaults to the keystore password. `ssl.truststore.path`:: The path to the Java Keystore file that contains the certificates to trust. `ssl.certificate_authorities` and `ssl.truststore.path` cannot be used at the same time. `ssl.truststore.password`:: The password to the truststore. `ssl.truststore.secure_password` (<>):: The password to the truststore. `ssl.truststore.type`:: The format of the keystore file. Should be `jks` to use the Java Keystore format, `PKCS12` to use PKCS#12 files, or `PKCS11` to use a PKCS#11 token. The default is `jks`. `ssl.verification_mode`:: Indicates the type of verification when using `ldaps` to protect against man in the middle attacks and certificate forgery. Values are `none`, `certificate`, and `full`. Defaults to `full`. + See <> for an explanation of these values. `ssl.supported_protocols`:: Supported protocols for TLS/SSL (with versions). Defaults to `TLSv1.3,TLSv1.2,TLSv1.1`. `ssl.cipher_suites`:: Specifies the cipher suites that should be supported when communicating with the LDAP server. Supported cipher suites can be found in Oracle's http://docs.oracle.com/javase/8/docs/technotes/guides/security/SunProviders.html[ Java Cryptography Architecture documentation]. See <> for the default value. `cache.ttl`:: Specifies the time-to-live for cached user entries. A user and a hash of its credentials are cached for this period of time. Use the standard {es} <>. Defaults to `20m`. `cache.max_users`:: Specifies the maximum number of user entries that the cache can contain. Defaults to `100000`. `cache.hash_algo`:: (Expert Setting) Specifies the hashing algorithm that is used for the in-memory cached user credentials. See <>. Defaults to `ssha256`. `authentication.enabled`:: If set to `false`, disables authentication support in this realm, so that it only supports user lookups. (See the <> and <> features). Defaults to `true`. [[ref-ad-settings]] [float] ===== Active Directory realm settings The `type` setting must be set to `active_directory`. In addition to the <>, you can specify the following settings: `url`:: One or more LDAP URLs in the `ldap[s]://:` format. Defaults to `ldap://:389`. This setting is required when connecting using SSL/TLS or when using a custom port. + To provide multiple URLs, use a YAML array (`[""ldap://server1:636"", ""ldap://server2:636""]`) or comma-separated string (`""ldap://server1:636, ldap://server2:636""`). + While both are supported, you can't mix the `ldap` and `ldaps` protocols. + If no URL is provided, {es} uses a default of `ldap://:389`. This default uses the `domain_name` setting value and assumes an unencrypted connection to port 389. `load_balance.type`:: The behavior to use when there are multiple LDAP URLs defined. For supported values see <>. Defaults to `failover`. `load_balance.cache_ttl`:: When using `dns_failover` or `dns_round_robin` as the load balancing type, this setting controls the amount of time to cache DNS lookups. Defaults to `1h`. `domain_name`:: The domain name of Active Directory. If the `url` and the `user_search_dn` settings are not specified, the cluster can derive those values from this setting. Required. `bind_dn`:: The DN of the user that is used to bind to Active Directory and perform searches. Defaults to Empty. Due to its potential security impact, `bind_dn` is not exposed via the <>. `bind_password`:: deprecated[6.3] Use `secure_bind_password` instead. The password for the user that is used to bind to Active Directory. Defaults to Empty. Due to its potential security impact, `bind_password` is not exposed via the <>. `secure_bind_password` (<>):: The password for the user that is used to bind to Active Directory. Defaults to Empty. `unmapped_groups_as_roles`:: If set to `true`, the names of any unmapped Active Directory groups are used as role names and assigned to the user. A group is considered _unmapped_ when it is not referenced in any role-mapping files. API-based role mappings are not considered. Defaults to `false`. `files.role_mapping`:: The <> for the YAML role mapping configuration file. Defaults to `ES_PATH_CONF/role_mapping.yml`. `user_search.base_dn`:: The context to search for a user. Defaults to the root of the Active Directory domain. `user_search.scope`:: Specifies whether the user search should be `sub_tree`, `one_level` or `base`. `one_level` only searches users directly contained within the `base_dn`. `sub_tree` searches all objects contained under `base_dn`. `base` specifies that the `base_dn` is a user object, and that it is the only user considered. Defaults to `sub_tree`. `user_search.filter`:: Specifies a filter to use to lookup a user given a username. The default filter looks up `user` objects with either `sAMAccountName` or `userPrincipalName`. If specified, this must be a valid LDAP user search filter. For example `(&(objectClass=user)(sAMAccountName={0}))`. For more information, see https://msdn.microsoft.com/en-us/library/aa746475(v=vs.85).aspx[Search Filter Syntax]. `user_search.upn_filter`:: Specifies a filter to use to lookup a user given a user principal name. The default filter looks up `user` objects with a matching `userPrincipalName`. If specified, this must be a valid LDAP user search filter. For example, `(&(objectClass=user)(userPrincipalName={1}))`. `{1}` is the full user principal name provided by the user. For more information, see https://msdn.microsoft.com/en-us/library/aa746475(v=vs.85).aspx[Search Filter Syntax]. `user_search.down_level_filter`:: Specifies a filter to use to lookup a user given a down level logon name (DOMAIN\\user). The default filter looks up `user` objects with a matching `sAMAccountName` in the domain provided. If specified, this must be a valid LDAP user search filter. For example, `(&(objectClass=user)(sAMAccountName={0}))`. For more information, see https://msdn.microsoft.com/en-us/library/aa746475(v=vs.85).aspx[Search Filter Syntax]. `user_search.pool.enabled`:: Enables or disables connection pooling for user search. When disabled a new connection is created for every search. The default is `true` when `bind_dn` is provided. `user_search.pool.size`:: The maximum number of connections to the Active Directory server to allow in the connection pool. Defaults to `20`. `user_search.pool.initial_size`:: The initial number of connections to create to the Active Directory server on startup. Defaults to `0`. If the LDAP server is down, values greater than 0 could cause startup failures. `user_search.pool.health_check.enabled`:: Enables or disables a health check on Active Directory connections in the connection pool. Connections are checked in the background at the specified interval. Defaults to `true`. `user_search.pool.health_check.dn`:: The distinguished name to be retrieved as part of the health check. Defaults to the value of `bind_dn` if that setting is present. Otherwise, it defaults to the value of the `user_search.base_dn` setting. `user_search.pool.health_check.interval`:: The interval to perform background checks of connections in the pool. Defaults to `60s`. `group_search.base_dn`:: The context to search for groups in which the user has membership. Defaults to the root of the Active Directory domain. `group_search.scope`:: Specifies whether the group search should be `sub_tree`, `one_level` or `base`. `one_level` searches for groups directly contained within the `base_dn`. `sub_tree` searches all objects contained under `base_dn`. `base` specifies that the `base_dn` is a group object, and that it is the only group considered. Defaults to `sub_tree`. `metadata`:: A list of additional LDAP attributes that should be loaded from the LDAP server and stored in the authenticated user's metadata field. `timeout.tcp_connect`:: The TCP connect timeout period for establishing an LDAP connection. An `s` at the end indicates seconds, or `ms` indicates milliseconds. Defaults to `5s` (5 seconds ). `timeout.tcp_read`:: The TCP read timeout period after establishing an LDAP connection. An `s` at the end indicates seconds, or `ms` indicates milliseconds. Defaults to `5s` (5 seconds ). `timeout.ldap_search`:: The LDAP Server enforced timeout period for an LDAP search. An `s` at the end indicates seconds, or `ms` indicates milliseconds. Defaults to `5s` (5 seconds ). `ssl.certificate`:: Path to a PEM encoded file containing the certificate (or certificate chain) that will be presented to clients when they connect. `ssl.certificate_authorities`:: List of paths to PEM encoded certificate files that should be trusted. `ssl.certificate_authorities` and `ssl.truststore.path` cannot be used at the same time. `ssl.key`:: Path to the PEM encoded file containing the private key, which is used when the Active Directory server requires client authentication. `ssl.key` and `ssl.keystore.path` cannot be used at the same time. `ssl.key_passphrase`:: The passphrase that is used to decrypt the private key. This value is optional as the key might not be encrypted. `ssl.secure_key_passphrase` (<>):: The passphrase that is used to decrypt the private key. This value is optional as the key might not be encrypted. `ssl.keystore.key_password`:: The password for the key in the keystore. Defaults to the keystore password. `ssl.keystore.secure_key_password` (<>):: The password for the key in the keystore. Defaults to the keystore password. `ssl.keystore.password`:: The password to the keystore. `ssl.secure_keystore.password` (<>):: The password to the keystore. `ssl.keystore.path`:: The path to the Java Keystore file that contains a private key and certificate. `ssl.key` and `ssl.keystore.path` cannot be used at the same time. `ssl.keystore.type`:: The format of the keystore file. Should be `jks` to use the Java Keystore format, `PKCS12` to use PKCS#12 files, or `PKCS11` to use a PKCS#11 token. The default is `jks`. `ssl.truststore.password`:: The password to the truststore. `ssl.truststore.secure_password` (<>):: The password to the truststore. `ssl.truststore.path`:: The path to the Java Keystore file that contains the certificates to trust. `ssl.certificate_authorities` and `ssl.truststore.path` cannot be used at the same time. `ssl.truststore.type`:: The format of the truststore file. Should be `jks` to use the Java Keystore format, `PKCS12` to use PKCS#12 files, or `PKCS11` to use a PKCS#11 token. The default is `jks`. `ssl.verification_mode`:: Indicates the type of verification when using `ldaps` to protect against man in the middle attacks and certificate forgery. Values are `none`, `certificate`, and `full`. Defaults to `full`. + See <> for an explanation of these values. `ssl.supported_protocols`:: Supported protocols for TLS/SSL (with versions). Defaults to `TLSv1.3,TLSv1.2,TLSv1.1`. `ssl.cipher_suites`:: Specifies the cipher suites that should be supported when communicating with the Active Directory server. Supported cipher suites can be found in Oracle's http://docs.oracle.com/javase/8/docs/technotes/guides/security/SunProviders.html[ Java Cryptography Architecture documentation]. See <> for the default values. `cache.ttl`:: Specifies the time-to-live for cached user entries. A user and a hash of its credentials are cached for this configured period of time. Use the standard Elasticsearch <>). Defaults to `20m`. `cache.max_users`:: Specifies the maximum number of user entries that the cache can contain. Defaults to `100000`. `cache.hash_algo`:: (Expert Setting) Specifies the hashing algorithm that is used for the in-memory cached user credentials. See <>. Defaults to `ssha256`. `authentication.enabled`:: If set to `false`, disables authentication support in this realm, so that it only supports user lookups. (See the <> and <> features). Defaults to `true`. `follow_referrals`:: If set to `true`, {es} follows referrals returned by the LDAP server. Referrals are URLs returned by the server that are to be used to continue the LDAP operation (such as `search`). Defaults to `true`. [[ref-pki-settings]] [float] ===== PKI realm settings The `type` setting must be set to `pki`. In addition to the <>, you can specify the following settings: `username_pattern`:: The regular expression pattern used to extract the username from the certificate DN. The first match group is the used as the username. Defaults to `CN=(.*?)(?:,\\|$)`. `certificate_authorities`:: List of paths to the PEM certificate files that should be used to authenticate a user's certificate as trusted. Defaults to the trusted certificates configured for SSL. This setting cannot be used with `truststore.path`. `truststore.algorithm`:: Algorithm for the truststore. Defaults to `SunX509`. `truststore.password`:: The password for the truststore. Must be provided if `truststore.path` is set. `truststore.secure_password` (<>):: The password for the truststore. `truststore.path`:: The path of a truststore to use. Defaults to the trusted certificates configured for SSL. This setting cannot be used with `certificate_authorities`. `files.role_mapping`:: Specifies the <> of the <>. Defaults to `ES_PATH_CONF/role_mapping.yml`. `authorization_realms`:: The names of the realms that should be consulted for delegated authorization. If this setting is used, then the PKI realm does not perform role mapping and instead loads the user from the listed realms. See <>. `cache.ttl`:: Specifies the time-to-live for cached user entries. A user and a hash of its credentials are cached for this period of time. Use the standard {es} <>). Defaults to `20m`. `cache.max_users`:: Specifies the maximum number of user entries that the cache can contain. Defaults to `100000`. `delegation.enabled`:: Generally, in order for the clients to be authenticated by the PKI realm they must connect directly to {es}. That is, they must not pass through proxies which terminate the TLS connection. In order to allow for a *trusted* and *smart* proxy, such as Kibana, to sit before {es} and terminate TLS connections, but still allow clients to be authenticated on {es} by this realm, you need to toggle this to `true`. Defaults to `false`. If delegation is enabled, then either `truststore.path` or `certificate_authorities` setting must be defined. For more details, see <>. [[ref-saml-settings]] [float] ===== SAML realm settings The `type` setting must be set to `saml`. In addition to the <>, you can specify the following settings: `idp.entity_id`:: The Entity ID of the SAML Identity Provider. An Entity ID is a URI with a maximum length of 1024 characters. It can be a URL (https://idp.example.com/) or a URN (`urn:example.com:idp`) and can be found in the configuration or the SAML metadata of the Identity Provider. `idp.metadata.path`:: The path _(recommended)_ or URL to a SAML 2.0 metadata file describing the capabilities and configuration of the Identity Provider. If a path is provided, then it is resolved relative to the {es} config directory. If a URL is provided, then it must be either a `file` URL or a `https` URL. {es} automatically polls this metadata resource and reloads the IdP configuration when changes are detected. File based resources are polled at a frequency determined by the global {es} `resource.reload.interval.high` setting, which defaults to 5 seconds. HTTPS resources are polled at a frequency determined by the realm's `idp.metadata.http.refresh` setting. `idp.metadata.http.refresh`:: Controls the frequency with which `https` metadata is checked for changes. Defaults to `1h` (1 hour). `idp.use_single_logout`:: Indicates whether to utilise the Identity Provider's Single Logout service (if one exists in the IdP metadata file). Defaults to `true`. `sp.entity_id`:: The Entity ID to use for this SAML Service Provider. This should be entered as a URI. We recommend that you use the base URL of your Kibana instance. For example, `https://kibana.example.com/`. `sp.acs`:: The URL of the Assertion Consumer Service within {kib}. Typically this is the ""api/security/v1/saml"" endpoint of your Kibana server. For example, `https://kibana.example.com/api/security/v1/saml`. `sp.logout`:: The URL of the Single Logout service within {kib}. Typically this is the ""logout"" endpoint of your Kibana server. For example, `https://kibana.example.com/logout`. `attributes.principal`:: The Name of the SAML attribute that contains the user's principal (username). `attributes.groups`:: The Name of the SAML attribute that contains the user's groups. `attributes.name`:: The Name of the SAML attribute that contains the user's full name. `attributes.mail`:: The Name of the SAML attribute that contains the user's email address. `attributes.dn`:: The Name of the SAML attribute that contains the user's X.50 _Distinguished Name_. `attribute_patterns.principal`:: A Java regular expression that is matched against the SAML attribute specified by `attributes.pattern` before it is applied to the user's _principal_ property. The attribute value must match the pattern and the value of the first _capturing group_ is used as the principal. For example, `^([^@]+)@example\\\\.com$` matches email addresses from the ""example.com"" domain and uses the local-part as the principal. `attribute_patterns.groups`:: As per `attribute_patterns.principal`, but for the _group_ property. `attribute_patterns.name`:: As per `attribute_patterns.principal`, but for the _name_ property. `attribute_patterns.mail`:: As per `attribute_patterns.principal`, but for the _mail_ property. `attribute_patterns.dn`:: As per `attribute_patterns.principal`, but for the _dn_ property. `nameid_format`:: The NameID format that should be requested when asking the IdP to authenticate the current user. The default is to not include the `nameid_format` attribute. `nameid.allow_create`:: The value of the `AllowCreate` attribute of the `NameIdPolicy` element in an authentication request. The default value is false. `nameid.sp_qualifier`:: The value of the `SPNameQualifier` attribute of the `NameIdPolicy` element in an authentication request. The default is to not include the `SPNameQualifier` attribute. `force_authn`:: Specifies whether to set the `ForceAuthn` attribute when requesting that the IdP authenticate the current user. If set to `true`, the IdP is required to verify the user’s identity, irrespective of any existing sessions they might have. Defaults to `false`. `populate_user_metadata`:: Specifies whether to populate the {es} user's metadata with the values that are provided by the SAML attributes. Defaults to `true`. `authorization_realms`:: The names of the realms that should be consulted for delegated authorization. If this setting is used, then the SAML realm does not perform role mapping and instead loads the user from the listed realms. See <>. `allowed_clock_skew`:: The maximum amount of skew that can be tolerated between the IdP's clock and the {es} node's clock. Defaults to `3m` (3 minutes). `req_authn_context_class_ref`:: A comma separated list of Authentication Context Class Reference values to be included in the Requested Authentication Context when requesting the IdP to authenticate the current user. The Authentication Context of the corresponding authentication response should contain at least one of the requested values. + For more information, see <>. [float] [[ref-saml-signing-settings]] ===== SAML realm signing settings If a signing key is configured (that is, either `signing.key` or `signing.keystore.path` is set), then {es} signs outgoing SAML messages. Signing can be configured using the following settings: `signing.saml_messages`:: A list of SAML message types that should be signed or `*` to sign all messages. Each element in the list should be the local name of a SAML XML Element. Supported element types are `AuthnRequest`, `LogoutRequest` and `LogoutResponse`. Only valid if `signing.key` or `signing.keystore.path` is also specified. Defaults to `*`. `signing.key`:: Specifies the path to the PEM encoded private key to use for SAML message signing. `signing.key` and `signing.keystore.path` cannot be used at the same time. `signing.secure_key_passphrase` (<>):: Specifies the passphrase to decrypt the PEM encoded private key (`signing.key`) if it is encrypted. `signing.certificate`:: Specifies the path to the PEM encoded certificate (or certificate chain) that corresponds to the `signing.key`. This certificate must also be included in the Service Provider metadata or manually configured within the IdP to allow for signature validation. This setting can only be used if `signing.key` is set. `signing.keystore.path`:: The path to the keystore that contains a private key and certificate. Must be either a Java Keystore (jks) or a PKCS#12 file. `signing.key` and `signing.keystore.path` cannot be used at the same time. `signing.keystore.type`:: The type of the keystore in `signing.keystore.path`. Must be either `jks` or `PKCS12`. If the keystore path ends in "".p12"", "".pfx"", or ""pkcs12"", this setting defaults to `PKCS12`. Otherwise, it defaults to `jks`. `signing.keystore.alias`:: Specifies the alias of the key within the keystore that should be used for SAML message signing. If the keystore contains more than one private key, this setting must be specified. `signing.keystore.secure_password` (<>):: The password to the keystore in `signing.keystore.path`. `signing.keystore.secure_key_password` (<>):: The password for the key in the keystore (`signing.keystore.path`). Defaults to the keystore password. [float] [[ref-saml-encryption-settings]] ===== SAML realm encryption settings If an encryption key is configured (that is, either `encryption.key` or `encryption.keystore.path` is set), then {es} publishes an encryption certificate when generating metadata and attempts to decrypt incoming SAML content. Encryption can be configured using the following settings: `encryption.key`:: Specifies the path to the PEM encoded private key to use for SAML message decryption. `encryption.key` and `encryption.keystore.path` cannot be used at the same time. `encryption.secure_key_passphrase` (<>):: Specifies the passphrase to decrypt the PEM encoded private key (`encryption.key`) if it is encrypted. `encryption.certificate`:: Specifies the path to the PEM encoded certificate (or certificate chain) that is associated with the `encryption.key`. This certificate must also be included in the Service Provider metadata or manually configured within the IdP to enable message encryption. This setting can be used only if `encryption.key` is set. `encryption.keystore.path`:: The path to the keystore that contains a private key and certificate. Must be either a Java Keystore (jks) or a PKCS#12 file. `encryption.key` and `encryption.keystore.path` cannot be used at the same time. `encryption.keystore.type`:: The type of the keystore (`encryption.keystore.path`). Must be either `jks` or `PKCS12`. If the keystore path ends in "".p12"", "".pfx"", or ""pkcs12"", this setting defaults to `PKCS12`. Otherwise, it defaults to `jks`. `encryption.keystore.alias`:: Specifies the alias of the key within the keystore (`encryption.keystore.path`) that should be used for SAML message decryption. If not specified, all compatible key pairs from the keystore are considered as candidate keys for decryption. `encryption.keystore.secure_password` (<>):: The password to the keystore (`encryption.keystore.path`). `encryption.keystore.secure_key_password` (<>):: The password for the key in the keystore (`encryption.keystore.path`). Only a single password is supported. If you are using multiple decryption keys, they cannot have individual passwords. [float] [[ref-saml-ssl-settings]] ===== SAML realm SSL settings If you are loading the IdP metadata over SSL/TLS (that is, `idp.metadata.path` is a URL using the `https` protocol), the following settings can be used to configure SSL. NOTE: These settings are not used for any purpose other than loading metadata over https. `ssl.key`:: Specifies the path to the PEM encoded private key to use for http client authentication (if required). `ssl.key` and `ssl.keystore.path` cannot be used at the same time. `ssl.key_passphrase`:: Specifies the passphrase to decrypt the PEM encoded private key (`ssl.key`) if it is encrypted. Cannot be used with `ssl.secure_key_passphrase`. `ssl.secure_key_passphrase` (<>):: Specifies the passphrase to decrypt the PEM encoded private key (`ssl.key`) if it is encrypted. Cannot be used with `ssl.key_passphrase`. `ssl.certificate`:: Specifies the path to the PEM encoded certificate (or certificate chain) that is associated with the key (`ssl.key`). This setting can be used only if `ssl.key` is set. `ssl.certificate_authorities`:: Specifies the paths to the PEM encoded certificate authority certificates that should be trusted. `ssl.certificate_authorities` and `ssl.truststore.path` cannot be used at the same time. `ssl.keystore.path`:: Specifies the path to the keystore that contains a private key and certificate. Must be either a Java Keystore (jks) or a PKCS#12 file. `ssl.key` and `ssl.keystore.path` cannot be used at the same time. `ssl.keystore.type`:: The type of the keystore (`ssl.keystore.path`). Must be either `jks` or `PKCS12`. If the keystore path ends in "".p12"", "".pfx"" or ""pkcs12"", this setting defaults to `PKCS12`. Otherwise, it defaults to `jks`. `ssl.keystore.password`:: The password to the keystore (`ssl.keystore.path`). This setting cannot be used with `ssl.keystore.secure_password`. `ssl.keystore.secure_password` (<>):: The password to the keystore (`ssl.keystore.path`). This setting cannot be used with `ssl.keystore.password`. `ssl.keystore.key_password`:: The password for the key in the keystore (`ssl.keystore.path`). Defaults to the keystore password. This setting cannot be used with `ssl.keystore.secure_key_password`. `ssl.keystore.secure_key_password` (<>):: The password for the key in the keystore (`ssl.keystore.path`). Defaults to the keystore password. This setting cannot be used with `ssl.keystore.key_password`. `ssl.truststore.path`:: The path to the keystore that contains the certificates to trust. Must be either a Java Keystore (jks) or a PKCS#12 file. `ssl.certificate_authorities` and `ssl.truststore.path` cannot be used at the same time. `ssl.truststore.type`:: The type of the truststore (`ssl.truststore.path`). Must be either `jks` or `PKCS12`. If the keystore path ends in "".p12"", "".pfx"" or ""pkcs12"", this setting defaults to `PKCS12`. Otherwise, it defaults to `jks`. `ssl.truststore.password`:: The password to the truststore (`ssl.truststore.path`). This setting cannot be used with `ssl.truststore.secure_password`. `ssl.truststore.secure_password` (<>):: The password to the truststore (`ssl.truststore.path`). This setting cannot be used with `ssl.truststore.password`. `ssl.verification_mode`:: One of `full` (verify the hostname and the certificate path), `certificate` (verify the certificate path, but not the hostname) or `none` (perform no verification). Defaults to `full`. + See <> for a more detailed explanation of these values. `ssl.supported_protocols`:: Specifies the supported protocols for TLS/SSL. Defaults to `TLSv1.3,TLSv1.2,TLSv1.1`. `ssl.cipher_suites`:: Specifies the cipher suites that should be supported. [float] [[ref-kerberos-settings]] ===== Kerberos realm settings For a Kerberos realm, the `type` must be set to `kerberos`. In addition to the <>, you can specify the following settings: `keytab.path`:: Specifies the path to the Kerberos keytab file that contains the service principal used by this {es} node. This must be a location within the {es} configuration directory and the file must have read permissions. Required. `remove_realm_name`:: Set to `true` to remove the realm part of principal names. Principal names in Kerberos have the form `user/instance@REALM`. If this option is `true`, the realm part (`@REALM`) will not be included in the username. Defaults to `false`. `krb.debug`:: Set to `true` to enable debug logs for the Java login module that provides support for Kerberos authentication. Defaults to `false`. `cache.ttl`:: The time-to-live for cached user entries. A user is cached for this period of time. Specify the time period using the standard {es} <>. Defaults to `20m`. `cache.max_users`:: The maximum number of user entries that can live in the cache at any given time. Defaults to 100,000. `authorization_realms`:: The names of the realms that should be consulted for delegated authorization. If this setting is used, then the Kerberos realm does not perform role mapping and instead loads the user from the listed realms. See <>. [[ref-oidc-settings]] [float] ===== OpenID Connect realm settings In addition to the <>, you can specify the following settings: `op.issuer`:: A verifiable Identifier for your OpenID Connect Provider. An Issuer Identifier is usually a case sensitive URL using the https scheme that contains scheme, host, and optionally, port number and path components and no query or fragment components. The value for this setting should be provided by your OpenID Connect Provider. `op.authorization_endpoint`:: The URL for the Authorization Endpoint at the OpenID Connect Provider. The value for this setting should be provided by your OpenID Connect Provider. `op.token_endpoint`:: The URL for the Token Endpoint at the OpenID Connect Provider. The value for this setting should be provided by your OpenID Connect Provider. `op.userinfo_endpoint`:: The URL for the User Info Endpoint at the OpenID Connect Provider. The value for this setting should be provided by your OpenID Connect Provider. `op.endsession_endpoint`:: The URL for the End Session Endpoint at the OpenID Connect Provider. The value for this setting should be provided by your OpenID Connect Provider. `op.jwkset_path`:: The path or URL to a JSON Web Key Set with the key material that the OpenID Connect Provider uses for signing tokens and claims responses. If a path is provided, then it is resolved relative to the {es} config directory. If a URL is provided, then it must be either a `file` URL or a `https` URL. {es} automatically caches the retrieved JWK set to avoid unnecessary HTTP requests but will attempt to refresh the JWK upon signature verification failure, as this might indicate that the OpenID Connect Provider has rotated the signing keys. File based resources are polled at a frequency determined by the global {es} `resource.reload.interval.high` setting, which defaults to 5 seconds. `rp.client_id`:: The OAuth 2.0 Client Identifier that was assigned to {es} during registration at the OpenID Connect Provider `rp.client_secret`(<>):: The OAuth 2.0 Client Secret that was assigned to {es} during registration at the OpenID Connect Provider `rp.redirect_uri`:: The Redirect URI within {kib}. If you want to use the authorization code flow, this is the ""api/security/v1/oidc"" endpoint of your {kib} server. If you want to use the implicit flow, it is the ""api/security/v1/oidc/implicit"" endpoint. For example, `https://kibana.example.com/api/security/v1/oidc`. `rp.response_type`:: OAuth 2.0 Response Type value that determines the authorization processing flow to be used. Can be `code` for authorization code grant flow, or one of `id_token`, `id_token token` for the implicit flow. `rp.signature_algorithm`:: The signature algorithm that will be used by {es} in order to verify the signature of the id tokens it will receive from the OpenID Connect Provider. Defaults to `RSA256` `rp.requested_scopes`:: The scope values that will be requested by the OpenID Connect Provider as part of the Authentication Request. Optional, defaults to `openid` `rp.post_logout_redirect_uri`:: The Redirect URI (usually within {kib}) that the OpenID Connect Provider should redirect the browser to after a successful Single Logout. `claims.principal`:: The name of the OpenID Connect claim that contains the user's principal (username). `claims.groups`:: The name of the OpenID Connect claim that contains the user's groups. `claims.name`:: The name of the OpenID Connect claim that contains the user's full name. `claims.mail`:: The name of the OpenID Connect claim that contains the user's email address. `claims.dn`:: The name of the OpenID Connect claim that contains the user's X.509 _Distinguished Name_. `claim_patterns.principal`:: A Java regular expression that is matched against the OpenID Connect claim specified by `claims.principal` before it is applied to the user's _principal_ property. The attribute value must match the pattern and the value of the first _capturing group_ is used as the principal. For example, `^([^@]+)@example\\\\.com$` matches email addresses from the ""example.com"" domain and uses the local-part as the principal. `claim_patterns.groups`:: As per `claim_patterns.principal`, but for the _group_ property. `claim_patterns.name`:: As per `claim_patterns.principal`, but for the _name_ property. `claim_patterns.mail`:: As per `claim_patterns.principal`, but for the _mail_ property. `claim_patterns.dn`:: As per `claim_patterns.principal`, but for the _dn_ property. `allowed_clock_skew`:: The maximum allowed clock skew to be taken into consideration when validating id tokens with regards to their creation and expiration times. `populate_user_metadata`:: Specifies whether to populate the {es} user's metadata with the values that are provided by the OpenID Connect claims. Defaults to `true`. `http.connect_timeout`:: Controls the behavior of the http client used for back-channel communication to the OpenID Connect Provider endpoints. Specifies the timeout until a connection is established. A value of zero means the timeout is not used. Defaults to `5s` `http.connection_read_timeout`:: Controls the behavior of the http client used for back-channel communication to the OpenID Connect Provider endpoints. Specifies the timeout used when requesting a connection from the connection manager. Defaults to `5s` `http.socket_timeout`:: Controls the behavior of the http client used for back-channel communication to the OpenID Connect Provider endpoints. Specifies the socket timeout (SO_TIMEOUT) in milliseconds, which is the timeout for waiting for data or, put differently, a maximum period inactivity between two consecutive data packets). Defaults to `5s` `http.max_connections`:: Controls the behavior of the http client used for back-channel communication to the OpenID Connect Provider endpoints. Specifies the maximum number of connections allowed across all endpoints. `http.max_endpoint_connections`:: Controls the behavior of the http client used for back-channel communication to the OpenID Connect Provider endpoints. Specifies the maximum number of connections allowed per endpoint. [float] [[ref-oidc-ssl-settings]] ===== OpenID Connect realm SSL settings The following settings can be used to configure SSL for all outgoing http connections to the OpenID Connect Provider endpoints. NOTE: These settings are _only_ used for the back-channel communication between {es} and the OpenID Connect Provider `ssl.key`:: Specifies the path to the PEM encoded private key to use for http client authentication (if required). `ssl.key` and `ssl.keystore.path` cannot be used at the same time. `ssl.key_passphrase`:: Specifies the passphrase to decrypt the PEM encoded private key (`ssl.key`) if it is encrypted. Cannot be used with `ssl.secure_key_passphrase`. `ssl.secure_key_passphrase` (<>):: Specifies the passphrase to decrypt the PEM encoded private key (`ssl.key`) if it is encrypted. Cannot be used with `ssl.key_passphrase`. `ssl.certificate`:: Specifies the path to the PEM encoded certificate (or certificate chain) that is associated with the key (`ssl.key`). This setting can be used only if `ssl.key` is set. `ssl.certificate_authorities`:: Specifies the paths to the PEM encoded certificate authority certificates that should be trusted. `ssl.certificate_authorities` and `ssl.truststore.path` cannot be used at the same time. `ssl.keystore.path`:: Specifies the path to the keystore that contains a private key and certificate. Must be either a Java Keystore (jks) or a PKCS#12 file. `ssl.key` and `ssl.keystore.path` cannot be used at the same time. `ssl.keystore.type`:: The type of the keystore (`ssl.keystore.path`). Must be either `jks` or `PKCS12`. If the keystore path ends in "".p12"", "".pfx"" or ""pkcs12"", this setting defaults to `PKCS12`. Otherwise, it defaults to `jks`. `ssl.keystore.password`:: The password to the keystore (`ssl.keystore.path`). This setting cannot be used with `ssl.keystore.secure_password`. `ssl.keystore.secure_password` (<>):: The password to the keystore (`ssl.keystore.path`). This setting cannot be used with `ssl.keystore.password`. `ssl.keystore.key_password`:: The password for the key in the keystore (`ssl.keystore.path`). Defaults to the keystore password. This setting cannot be used with `ssl.keystore.secure_key_password`. `ssl.keystore.secure_key_password` (<>):: The password for the key in the keystore (`ssl.keystore.path`). Defaults to the keystore password. This setting cannot be used with `ssl.keystore.key_password`. `ssl.truststore.path`:: The path to the keystore that contains the certificates to trust. Must be either a Java Keystore (jks) or a PKCS#12 file. `ssl.certificate_authorities` and `ssl.truststore.path` cannot be used at the same time. `ssl.truststore.type`:: The type of the truststore (`ssl.truststore.path`). Must be either `jks` or `PKCS12`. If the keystore path ends in "".p12"", "".pfx"" or ""pkcs12"", this setting defaults to `PKCS12`. Otherwise, it defaults to `jks`. `ssl.truststore.password`:: The password to the truststore (`ssl.truststore.path`). This setting cannot be used with `ssl.truststore.secure_password`. `ssl.truststore.secure_password` (<>):: The password to the truststore (`ssl.truststore.path`). This setting cannot be used with `ssl.truststore.password`. `ssl.verification_mode`:: One of `full` (verify the hostname and the certificate path), `certificate` (verify the certificate path, but not the hostname) or `none` (perform no verification). Defaults to `full`. + See <> for a more detailed explanation of these values. `ssl.supported_protocols`:: Specifies the supported protocols for TLS/SSL. Defaults to `TLSv1.3,TLSv1.2,TLSv1.1` if the JVM supports TLSv1.3, otherwise `TLSv1.2,TLSv1.1`. `ssl.cipher_suites`:: Specifies the cipher suites that should be supported. [float] [[load-balancing]] ===== Load balancing and failover The `load_balance.type` setting can have the following values: * `failover`: The URLs specified are used in the order that they are specified. The first server that can be connected to will be used for all subsequent connections. If a connection to that server fails then the next server that a connection can be established to will be used for subsequent connections. * `dns_failover`: In this mode of operation, only a single URL may be specified. This URL must contain a DNS name. The system will be queried for all IP addresses that correspond to this DNS name. Connections to the Active Directory or LDAP server will always be tried in the order in which they were retrieved. This differs from `failover` in that there is no reordering of the list and if a server has failed at the beginning of the list, it will still be tried for each subsequent connection. * `round_robin`: Connections will continuously iterate through the list of provided URLs. If a server is unavailable, iterating through the list of URLs will continue until a successful connection is made. * `dns_round_robin`: In this mode of operation, only a single URL may be specified. This URL must contain a DNS name. The system will be queried for all IP addresses that correspond to this DNS name. Connections will continuously iterate through the list of addresses. If a server is unavailable, iterating through the list of URLs will continue until a successful connection is made. [float] [[ssl-tls-settings]] ==== Default values for TLS/SSL settings In general, the values below represent the default values for the various TLS settings. The prefixes for these settings are based on the context in which they are used (e.g. `xpack.security.authc.realms.ldap.corp_ldap.ssl.verification_mode` or `xpack.security.transport.ssl.supported_protocols`). For more information, see <>. `*.ssl.supported_protocols`:: Supported protocols with versions. Valid protocols: `SSLv2Hello`, `SSLv3`, `TLSv1`, `TLSv1.1`, `TLSv1.2`, `TLSv1.3`. Defaults to `TLSv1.3,TLSv1.2,TLSv1.1`. + -- NOTE: If `xpack.security.fips_mode.enabled` is `true`, you cannot use `SSLv2Hello` or `SSLv3`. See <>. -- `*.ssl.client_authentication`:: Controls the server's behavior in regard to requesting a certificate from client connections. Valid values are `required`, `optional`, and `none`. `required` forces a client to present a certificate, while `optional` requests a client certificate but the client is not required to present one. Defaults to `required`, except for HTTP, which defaults to `none`. See <>. `*.ssl.verification_mode`:: Controls the verification of certificates. Valid values are: - `full`, which verifies that the provided certificate is signed by a trusted authority (CA) and also verifies that the server's hostname (or IP address) matches the names identified within the certificate. - `certificate`, which verifies that the provided certificate is signed by a trusted authority (CA), but does not perform any hostname verification. - `none`, which performs _no verification_ of the server's certificate. This mode disables many of the security benefits of SSL/TLS and should only be used after very careful consideration. It is primarily intended as a temporary diagnostic mechanism when attempting to resolve TLS errors, and its use on production clusters is strongly discouraged. + The default value is `full`. `*.ssl.cipher_suites`:: Supported cipher suites can be found in Oracle's https://docs.oracle.com/en/java/javase/11/security/oracle-providers.html#GUID-7093246A-31A3-4304-AC5F-5FB6400405E2[Java Cryptography Architecture documentation]. Defaults to `TLS_AES_256_GCM_SHA384`, `TLS_AES_128_GCM_SHA256`, `TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384`, `TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256`, `TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384`, `TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256`, `TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384`, `TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256`, `TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384`, `TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256`, `TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA`, `TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA`, `TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA`, `TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA`, `TLS_RSA_WITH_AES_256_GCM_SHA384`, `TLS_RSA_WITH_AES_128_GCM_SHA256`, `TLS_RSA_WITH_AES_256_CBC_SHA256`, `TLS_RSA_WITH_AES_128_CBC_SHA256`, `TLS_RSA_WITH_AES_256_CBC_SHA`, `TLS_RSA_WITH_AES_128_CBC_SHA`. [float] [[tls-ssl-key-settings]] ===== TLS/SSL key and trusted certificate settings The following settings are used to specify a private key, certificate, and the trusted certificates that should be used when communicating over an SSL/TLS connection. If no trusted certificates are configured, the default certificates that are trusted by the JVM will be trusted along with the certificate(s) associated with a key in the same context. The key and certificate must be in place for connections that require client authentication or when acting as a SSL enabled server. [[pkcs12-truststore-note]] [NOTE] Storing trusted certificates in a PKCS#12 file, although supported, is uncommon in practice. The <>, as well as Java's `keytool`, are designed to generate PKCS#12 files that can be used both as a keystore and as a truststore, but this may not be the case for container files that are created using other tools. Usually, PKCS#12 files only contain secret and private entries. To confirm that a PKCS#12 container includes trusted certificate (""anchor"") entries look for `2.16.840.1.113894.746875.1.1: ` in the `openssl pkcs12 -info` output, or `trustedCertEntry` in the `keytool -list` output. [[http-tls-ssl-settings]] :ssl-prefix: xpack.security.http :component: HTTP :client-auth-default: none :verifies!: :server: :ssl-context: security-http include::ssl-settings.asciidoc[] [[transport-tls-ssl-settings]] :ssl-prefix: xpack.security.transport :component: Transport :client-auth-default!: :verifies: :server: :ssl-context: security-transport include::ssl-settings.asciidoc[] [[ssl-tls-profile-settings]] [float] ===== Transport profile TLS/SSL settings The same settings that are available for the <> are also available for each transport profile. By default, the settings for a transport profile will be the same as the default transport unless they are specified. As an example, lets look at the key setting. For the default transport this is `xpack.security.transport.ssl.key`. In order to use this setting in a transport profile, use the prefix `transport.profiles.$PROFILE.xpack.security.` and append the portion of the setting after `xpack.security.transport.`. For the key setting, this would be `transport.profiles.$PROFILE.xpack.security.ssl.key`. [float] [[ip-filtering-settings]] ==== IP filtering settings You can configure the following settings for <>. `xpack.security.transport.filter.allow`:: List of IP addresses to allow. `xpack.security.transport.filter.deny`:: List of IP addresses to deny. `xpack.security.http.filter.allow`:: List of IP addresses to allow just for HTTP. `xpack.security.http.filter.deny`:: List of IP addresses to deny just for HTTP. `transport.profiles.$PROFILE.xpack.security.filter.allow`:: List of IP addresses to allow for this profile. `transport.profiles.$PROFILE.xpack.security.filter.deny`:: List of IP addresses to deny for this profile. include::security-hash-settings.asciidoc[] ",16196,True,3225.3874458970354,median "//// This guide is maintained in the main Quarkus repository and pull requests should be submitted there: https://github.com/quarkusio/quarkus/tree/main/docs/src/main/asciidoc //// = Apache Kafka Reference Guide include::./attributes.adoc[] :numbered: :sectnums: :sectnumlevels: 4 :toc: This reference guide demonstrates how your Quarkus application can utilize SmallRye Reactive Messaging to interact with Apache Kafka. == Introduction https://kafka.apache.org[Apache Kafka] is a popular open-source distributed event streaming platform. It is used commonly for high-performance data pipelines, streaming analytics, data integration, and mission-critical applications. Similar to a message queue, or an enterprise messaging platform, it lets you: - *publish* (write) and *subscribe* to (read) streams of events, called _records_. - *store* streams of records durably and reliably inside _topics_. - *process* streams of records as they occur or retrospectively. And all this functionality is provided in a distributed, highly scalable, elastic, fault-tolerant, and secure manner. == Quarkus Extension for Apache Kafka Quarkus provides support for Apache Kafka through https://smallrye.io/smallrye-reactive-messaging/[SmallRye Reactive Messaging] framework. Based on Eclipse MicroProfile Reactive Messaging specification 2.0, it proposes a flexible programming model bridging CDI and event-driven. [NOTE] ==== This guide provides an in-depth look on Apache Kafka and SmallRye Reactive Messaging framework. For a quick start take a look at xref:kafka-reactive-getting-started.adoc[Getting Started to SmallRye Reactive Messaging with Apache Kafka]. ==== You can add the `smallrye-reactive-messaging-kafka` extensions to your project by running the following command in your project base directory: [source,bash] ---- ./mvnw quarkus:add-extension -Dextensions=""smallrye-reactive-messaging-kafka"" ---- This will add the following to your `pom.xml`: [source,xml] ---- io.quarkus quarkus-smallrye-reactive-messaging-kafka ---- == Configuring Smallrye Kafka Connector Because Smallrye Reactive Messaging framework supports different messaging backends like Apache Kafka, AMQP, Apache Camel, JMS, MQTT, etc., it employs a generic vocabulary: - Applications send and receive *messages*. A message wraps a _payload_ and can be extended with some _metadata_. With the Kafka connector, a _message_ corresponds to a Kafka _record_. - Messages transit on *channels*. Application components connect to channels to publish and consume messages. The Kafka connector maps _channels_ to Kafka _topics_. - Channels are connected to message backends using *connectors*. Connectors are configured to map incoming messages to a specific channel (consumed by the application) and collect outgoing messages sent to a specific channel. Each connector is dedicated to a specific messaging technology. For example, the connector dealing with Kafka is named `smallrye-kafka`. A minimal configuration for the Kafka connector with an incoming channel looks like the following: [source, properties] ---- %prod.kafka.bootstrap.servers=kafka:9092 <1> mp.messaging.incoming.prices.connector=smallrye-kafka <2> ---- <1> Configure the broker location for the production profile. You can configure it globally or per channel using `mp.messaging.incoming.$channel.bootstrap.servers` property. In dev mode and when running tests, link:kafka-dev-services[Dev Services for Kafka] automatically starts a Kafka broker. When not provided this property defaults to `localhost:9092`. <2> Configure the connector to manage the prices channel. By default the topic name is same as the channel name. You can configure the topic attribute to override it. NOTE: The `%prod` prefix indicates that the property is only used when the application runs in prod mode (so not in dev or test). Refer to the xref:config-reference.adoc#profiles[Profile documentation] for further details. == Receiving messages from Kafka Continuing from the previous minimal configuration, your Quarkus application can receive message payload directly: [source, java] ---- import org.eclipse.microprofile.reactive.messaging.Incoming; import javax.enterprise.context.ApplicationScoped; @ApplicationScoped public class PriceConsumer { @Incoming(""prices"") public void consume(double price) { // process your price. } } ---- There are several other ways your application can consume incoming messages: .Message [source, java] ---- @Incoming(""prices"") public CompletionStage consume(Message msg) { // access record metadata var metadata = msg.getMetadata(IncomingKafkaRecordMetadata.class).orElseThrow(); // process the message payload. double price = msg.getPayload(); // Acknowledge the incoming message (commit the offset) return msg.ack(); } ---- The `Message` type lets the consuming method access the incoming message metadata and handle the acknowledgment manually. We'll explore different acknowledgment strategies in <>. If you want to access the Kafka record objects directly, use: .ConsumerRecord [source, java] ---- @Incoming(""prices"") public void consume(ConsumerRecord record) { String key = record.key(); // Can be `null` if the incoming record has no key String value = record.value(); // Can be `null` if the incoming record has no value String topic = record.topic(); int partition = record.partition(); // ... } ---- `ConsumerRecord` is provided by the underlying Kafka client and can be injected directly to the consumer method. Another simpler approach consists in using `Record`: .Record [source, java] ---- @Incoming(""prices"") public void consume(Record record) { String key = record.key(); // Can be `null` if the incoming record has no key String value = record.value(); // Can be `null` if the incoming record has no value } ---- `Record` is a simple wrapper around key and payload of the incoming Kafka record. .@Channel Alternatively, your application can inject a `Multi` in your bean and subscribe to its events as the following example: [source, java] ---- import io.smallrye.mutiny.Multi; import io.smallrye.reactive.messaging.annotations.Channel; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.jboss.resteasy.annotations.SseElementType; @Path(""/prices"") public class PriceResource { @Inject @Channel(""prices"") Multi prices; @GET @Path(""/prices"") @Produces(MediaType.SERVER_SENT_EVENTS) @SseElementType(""text/plain"") public Multi stream() { return prices; } } ---- This is a good example of how to integrate a Kafka consumer with another downstream, in this example exposing it as a Server-Sent Events endpoint. [NOTE] ==== When consuming messages with `@Channel`, the application code is responsible for the subscription. In the example above, RESTEasy endpoint handles that for you. ==== Following types can be injected as channels: [source, java] ---- @Inject @Channel(""prices"") Multi streamOfPayloads; @Inject @Channel(""prices"") Multi> streamOfMessages; @Inject @Channel(""prices"") Publisher publisherOfPayloads; @Inject @Channel(""prices"") Publisher> publisherOfMessages; ---- As with the previous `Message` example, if your injected channel receives payloads (`Multi`), it acknowledges the message automatically, and support multiple subscribers. If you injected channel receives Message (`Multi>`), you will be responsible for the acknowledgment and broadcasting. We will explore sending broadcast messages in <>. [IMPORTANT] ==== Injecting `@Channel(""prices"")` or having `@Incoming(""prices"")` does not automatically configure the application to consume messages from Kafka. You need to configure an inbound connector with `mp.messaging.incoming.prices\\...` or have an `@Outgoing(""prices"")` method somewhere in your application (in which case, `prices` will be an in-memory channel). ==== [#blocking-processing] === Blocking processing Reactive Messaging invokes your method on an I/O thread. See the xref:quarkus-reactive-architecture.adoc[Quarkus Reactive Architecture documentation] for further details on this topic. But, you often need to combine Reactive Messaging with blocking processing such as database interactions. For this, you need to use the `@Blocking` annotation indicating that the processing is _blocking_ and should not be run on the caller thread. For example, The following code illustrates how you can store incoming payloads to a database using Hibernate with Panache: [source,java] ---- import io.smallrye.reactive.messaging.annotations.Blocking; import org.eclipse.microprofile.reactive.messaging.Incoming; import javax.enterprise.context.ApplicationScoped; import javax.transaction.Transactional; @ApplicationScoped public class PriceStorage { @Incoming(""prices"") @Blocking @Transactional public void store(int priceInUsd) { Price price = new Price(); price.value = priceInUsd; price.persist(); } } ---- The complete example is available in the `kafka-panache-quickstart` {quickstarts-tree-url}/kafka-panache-quickstart[directory]. [NOTE] ==== There are 2 `@Blocking` annotations: 1. `io.smallrye.reactive.messaging.annotations.Blocking` 2. `io.smallrye.common.annotation.Blocking` They have the same effect. Thus, you can use both. The first one provides more fine-grained tuning such as the worker pool to use and whether it preserves the order. The second one, used also with other reactive features of Quarkus, uses the default worker pool and preserves the order. ==== === Acknowledgment Strategies All messages received by a consumer must be acknowledged. In the absence of acknowledgment, the processing is considered in error. If the consumer method receives a `Record` or a payload, the message will be acked on method return, also known as `Strategy.POST_PROCESSING`. If the consumer method returns another reactive stream or `CompletionStage`, the message will be acked when the downstream message is acked. You can override the default behavior to ack the message on arrival (`Strategy.PRE_PROCESSING`), or do not ack the message at all (`Strategy.NONE`) on the consumer method as in the following example: [source, java] ---- @Incoming(""prices"") @Acknowledgment(Acknowledgment.Strategy.PRE_PROCESSING) public void process(double price) { // process price } ---- If the consumer method receives a `Message`, the acknowledgment strategy is `Strategy.MANUAL` and the consumer method is in charge of ack/nack the message. [source, java] ---- @Incoming(""prices"") public CompletionStage process(Message msg) { // process price return msg.ack(); } ---- As mentioned above, the method can also override the acknowledgment strategy to `PRE_PROCESSING` or `NONE`. [[commit-strategies]] === Commit Strategies When a message produced from a Kafka record is acknowledged, the connector invokes a commit strategy. These strategies decide when the consumer offset for a specific topic/partition is committed. Committing an offset indicates that all previous records have been processed. It is also the position where the application would restart the processing after a crash recovery or a restart. Committing every offset has performance penalties as Kafka offset management can be slow. However, not committing the offset often enough may lead to message duplication if the application crashes between two commits. The Kafka connector supports three strategies: - `throttled` keeps track of received messages and commits an offset of the latest acked message in sequence (meaning, all previous messages were also acked). This strategy guarantees at-least-once delivery even if the channel performs asynchronous processing. The connector tracks the received records and periodically (period specified by `auto.commit.interval.ms`, default: 5000 ms) commits the highest consecutive offset. The connector will be marked as unhealthy if a message associated with a record is not acknowledged in `throttled.unprocessed-record-max-age.ms` (default: 60000 ms). Indeed, this strategy cannot commit the offset as soon as a single record processing fails (see <> to configure what happens on failing processing). If `throttled.unprocessed-record-max-age.ms` is set to less than or equal to `0`, it does not perform any health check verification. Such a setting might lead to running out of memory if there are ""poison pill"" messages (that are never acked). This strategy is the default if `enable.auto.commit` is not explicitly set to true. - `latest` commits the record offset received by the Kafka consumer as soon as the associated message is acknowledged (if the offset is higher than the previously committed offset). This strategy provides at-least-once delivery if the channel processes the message without performing any asynchronous processing. This strategy should not be used in high load environment, as offset commit is expensive. However, it reduces the risk of duplicates. - `ignore` performs no commit. This strategy is the default strategy when the consumer is explicitly configured with `enable.auto.commit` to true. It delegates the offset commit to the underlying Kafka client. This strategy provides at-least-once delivery if the channel processes the message without performing any asynchronous operations and when `enable.auto.commit` is set to true. However, if the processing failed between two commits, messages received after the commit and before the failure will be re-processed. [IMPORTANT] ==== The Kafka connector disables the Kafka auto commit when it is not explicitly enabled. This behavior differs from the traditional Kafka consumer. If high throughput is important for you, and you are not limited by the downstream, we recommend to either: - use the `throttled` policy, - or set `enable.auto.commit` to true and annotate the consuming method with `@Acknowledgment(Acknowledgment.Strategy.NONE)`. ==== [[error-handling]] === Error Handling Strategies If a message produced from a Kafka record is nacked, a failure strategy is applied. The Kafka connector supports three strategies: - `fail`: fail the application, no more records will be processed (default strategy). The offset of the record that has not been processed correctly is not committed. - `ignore`: the failure is logged, but the processing continue. The offset of the record that has not been processed correctly is committed. - `dead-letter-queue`: the offset of the record that has not been processed correctly is committed, but the record is written to a Kafka dead letter topic. The strategy is selected using the `failure-strategy` attribute. In the case of `dead-letter-queue`, you can configure the following attributes: - `dead-letter-queue.topic`: the topic to use to write the records not processed correctly, default is `dead-letter-topic-$channel`, with `$channel` being the name of the channel. - `dead-letter-queue.key.serializer`: the serializer used to write the record key on the dead letter queue. By default, it deduces the serializer from the key deserializer. - `dead-letter-queue.value.serializer`: the serializer used to write the record value on the dead letter queue. By default, it deduces the serializer from the value deserializer. The record written on the dead letter queue contains a set of additional headers about the original record: - *dead-letter-reason*: the reason of the failure - *dead-letter-cause*: the cause of the failure if any - *dead-letter-topic*: the original topic of the record - *dead-letter-partition*: the original partition of the record (integer mapped to String) - *dead-letter-offset*: the original offset of the record (long mapped to String) ==== Retrying processing You can combine Reactive Messaging with https://github.com/smallrye/smallrye-fault-tolerance[SmallRye Fault Tolerance], and retry processing if it failed: [source, java] ---- @Incoming(""kafka"") @Retry(delay = 10, maxRetries = 5) public void consume(String v) { // ... retry if this method throws an exception } ---- You can configure the delay, the number of retries, the jitter, etc. If your method returns a `Uni` or `CompletionStage`, you need to add the `@NonBlocking` annotation: [source,java] ---- @Incoming(""kafka"") @Retry(delay = 10, maxRetries = 5) @NonBlocking public Uni consume(String v) { // ... retry if this method throws an exception or the returned Uni produce a failure } ---- NOTE: The `@NonBlocking` annotation is only required with SmallRye Fault Tolerance 5.1.0 and earlier. Starting with SmallRye Fault Tolerance 5.2.0 (available since Quarkus 2.1.0.Final), it is not necessary. See https://smallrye.io/docs/smallrye-fault-tolerance/5.2.0/usage/extra.html#_non_compatible_mode[SmallRye Fault Tolerance documentation] for more information. The incoming messages are acknowledged only once the processing completes successfully. So, it commits the offset after the successful processing. If the processing still fails, even after all retries, the message is _nacked_ and the failure strategy is applied. === Consumer Groups In Kafka, a consumer group is a set of consumers which cooperate to consume data from a topic. A topic is divided into a set of partitions. The partitions of a topic are assigned among the consumers in the group, effectively allowing to scale consumption throughput. Note that each partition is assigned to a single consumer from a group. However, a consumer can be assigned multiple partitions if the number of partitions is greater than the number of consumer in the group. Let's explore briefly different producer/consumer patterns and how to implement them using Quarkus: . *Single consumer thread inside a consumer group* + This is the default behavior of an application subscribing to a Kafka topic: Each Kafka connector will create a single consumer thread and place it inside a single consumer group. Consumer group id defaults to the application name as set by the `quarkus.application.name` configuration property. It can also be set using the `kafka.group.id` property. + image::kafka-one-app-one-consumer.png[alt=Architecture, width=60%, align=center] . *Multiple consumer threads inside a consumer group* + For a given application instance, the number of consumers inside the consumer group can be configured using `mp.messaging.incoming.$channel.partitions` property. The partitions of the subscribed topic will be divided among the consumer threads. Note that if the `partitions` value exceed the number of partitions of the topic, some consumer threads won't be assigned any partitions. + image::kafka-one-app-two-consumers.png[alt=Architecture, width=60%, align=center] . *Multiple consumer applications inside a consumer group* + Similar to the previous example, multiple instances of an application can subscribe to a single consumer group, configured via `mp.messaging.incoming.$channel.group.id` property, or left default to the application name. This in turn will divide partitions of the topic among application instances. + image::kafka-two-app-one-consumer-group.png[alt=Architecture, width=60% , align=center] . *Pub/Sub: Multiple consumer groups subscribed to a topic* + Lastly different applications can subscribe independently to same topics using different *consumer group ids*. For example, messages published to a topic called _orders_ can be consumed independently on two consumer applications, one with `mp.messaging.incoming.orders.group.id=invoicing` and second with `mp.messaging.incoming.orders.group.id=shipping`. Different consumer groups can thus scale independently according to the message consumption requirements. + image::kafka-two-app-two-consumer-groups.png[alt=Architecture, width=60%, align=center] ==== Consumer Rebalance Listener Inside a consumer group, as new group members arrive and old members leave, the partitions are re-assigned so that each member receives a proportional share of the partitions. This is known as rebalancing the group. To handle offset commit and assigned partitions yourself, you can provide a consumer rebalance listener. To achieve this, implement the `io.smallrye.reactive.messaging.kafka.KafkaConsumerRebalanceListener` interface and expose it as a CDI bean with the `@Idenfier` qualifier. A common use case is to store offset in a separate data store to implement exactly-once semantic, or starting the processing at a specific offset. The listener is invoked every time the consumer topic/partition assignment changes. For example, when the application starts, it invokes the `partitionsAssigned` callback with the initial set of topics/partitions associated with the consumer. If, later, this set changes, it calls the `partitionsRevoked` and `partitionsAssigned` callbacks again, so you can implement custom logic. Note that the rebalance listener methods are called from the Kafka polling thread and **will** block the caller thread until completion. That’s because the rebalance protocol has synchronization barriers, and using asynchronous code in a rebalance listener may be executed after the synchronization barrier. When topics/partitions are assigned or revoked from a consumer, it pauses the message delivery and resumes once the rebalance completes. If the rebalance listener handles offset commit on behalf of the user (using the `NONE` commit strategy), the rebalance listener must commit the offset synchronously in the partitionsRevoked callback. We also recommend applying the same logic when the application stops. Unlike the `ConsumerRebalanceListener` from Apache Kafka, the `io.smallrye.reactive.messaging.kafka.KafkaConsumerRebalanceListener` methods pass the Kafka Consumer and the set of topics/partitions. In the following example we set-up a consumer that always starts on messages from at most 10 minutes ago (or offset 0). First we need to provide a bean that implements `io.smallrye.reactive.messaging.kafka.KafkaConsumerRebalanceListener` and is annotated with `io.smallrye.common.annotation.Identifier`. We then must configure our inbound connector to use this bean. [source, java] ---- package inbound; import io.smallrye.common.annotation.Identifier; import io.smallrye.reactive.messaging.kafka.KafkaConsumerRebalanceListener; import org.apache.kafka.clients.consumer.Consumer; import org.apache.kafka.clients.consumer.OffsetAndTimestamp; import org.apache.kafka.clients.consumer.TopicPartition; import javax.enterprise.context.ApplicationScoped; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; @ApplicationScoped @Identifier(""rebalanced-example.rebalancer"") public class KafkaRebalancedConsumerRebalanceListener implements KafkaConsumerRebalanceListener { private static final Logger LOGGER = Logger.getLogger(KafkaRebalancedConsumerRebalanceListener.class.getName()); /** * When receiving a list of partitions, will search for the earliest offset within 10 minutes * and seek the consumer to it. * * @param consumer underlying consumer * @param partitions set of assigned topic partitions */ @Override public void onPartitionsAssigned(Consumer consumer, Collection partitions) { long now = System.currentTimeMillis(); long shouldStartAt = now - 600_000L; //10 minute ago Map request = new HashMap<>(); for (TopicPartition partition : partitions) { LOGGER.info(""Assigned "" + partition); request.put(partition, shouldStartAt); } Map offsets = consumer.offsetsForTimes(request); for (Map.Entry position : offsets.entrySet()) { long target = position.getValue() == null ? 0L : position.getValue().offset(); LOGGER.info(""Seeking position "" + target + "" for "" + position.getKey()); consumer.seek(position.getKey(), target); } } } ---- [source, java] ---- package inbound; import io.smallrye.reactive.messaging.kafka.IncomingKafkaRecord; import org.eclipse.microprofile.reactive.messaging.Acknowledgment; import org.eclipse.microprofile.reactive.messaging.Incoming; import javax.enterprise.context.ApplicationScoped; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; @ApplicationScoped public class KafkaRebalancedConsumer { @Incoming(""rebalanced-example"") @Acknowledgment(Acknowledgment.Strategy.NONE) public CompletionStage consume(IncomingKafkaRecord message) { // We don't need to ACK messages because in this example, // we set offset during consumer rebalance return CompletableFuture.completedFuture(null); } } ---- To configure the inbound connector to use the provided listener, we either set the consumer rebalance listener’s identifier: `mp.messaging.incoming.rebalanced-example.consumer-rebalance-listener.name=rebalanced-example.rebalancer` Or have the listener’s name be the same as the group id: `mp.messaging.incoming.rebalanced-example.group.id=rebalanced-example.rebalancer` Setting the consumer rebalance listener’s name takes precedence over using the group id. ==== Using unique consumer groups If you want to process all the records from a topic (from its beginning), you need: 1. to set `auto.offset.reset = earliest` 2. assign your consumer to a consumer group not used by any other application. Quarkus generates a UUID that changes between two executions (including in dev mode). So, you are sure no other consumer uses it, and you receive a new unique group id every time your application starts. You can use that generated UUID as the consumer group as follows: [source, properties] ---- mp.messaging.incoming.your-channel.auto.offset.reset=earliest mp.messaging.incoming.your-channel.group.id=${quarkus.uuid} ---- IMPORTANT: If the `group.id` attribute is not set, it defaults the `quarkus.application.name` configuration property. == Sending messages to Kafka Configuration for the Kafka connector outgoing channels is similar to that of incoming: [source, properties] ---- %prod.kafka.bootstrap.servers=kafka:9092 <1> mp.messaging.outgoing.prices-out.connector=smallrye-kafka <2> mp.messaging.outgoing.prices-out.topic=prices <3> ---- <1> Configure the broker location for the production profile. You can configure it globally or per channel using `mp.messaging.outgoing.$channel.bootstrap.servers` property. In dev mode and when running tests, link:kafka-dev-services[Dev Services for Kafka] automatically starts a Kafka broker. When not provided, this property defaults to `localhost:9092`. <2> Configure the connector to manage the `prices-out` channel. <3> By default, the topic name is same as the channel name. You can configure the topic attribute to override it. [IMPORTANT] ==== Inside application configuration, channel names are unique. Therefore, if you'd like to configure an incoming and outgoing channel on the same topic, you will need to name channels differently (like in the examples of this guide, `mp.messaging.incoming.prices` and `mp.messaging.outgoing.prices-out`). ==== Then, your application can generate messages and publish them to the `prices-out` channel. It can use `double` payloads as in the following snippet: [source, java] ---- import io.smallrye.mutiny.Multi; import org.eclipse.microprofile.reactive.messaging.Outgoing; import javax.enterprise.context.ApplicationScoped; import java.time.Duration; import java.util.Random; @ApplicationScoped public class KafkaPriceProducer { private final Random random = new Random(); @Outgoing(""prices-out"") public Multi generate() { // Build an infinite stream of random prices // It emits a price every second return Multi.createFrom().ticks().every(Duration.ofSeconds(1)) .map(x -> random.nextDouble()); } } ---- [IMPORTANT] ==== You should not call methods annotated with `@Incoming` and/or `@Outgoing` directly from your code. They are invoked by the framework. Having user code invoking them would not have the expected outcome. ==== Note that the `generate` method returns a `Multi`, which implements the Reactive Streams `Publisher` interface. This publisher will be used by the framework to generate messages and send them to the configured Kafka topic. Instead of returning a payload, you can return a `io.smallrye.reactive.messaging.kafka.Record` to send key/value pairs: [source, java] ---- @Outgoing(""out"") public Multi> generate() { return Multi.createFrom().ticks().every(Duration.ofSeconds(1)) .map(x -> Record.of(""my-key"", random.nextDouble())); } ---- Payload can be wrapped inside `org.eclipse.microprofile.reactive.messaging.Message` to have more control on the written records: [source, java] ---- @Outgoing(""generated-price"") public Multi> generate() { return Multi.createFrom().ticks().every(Duration.ofSeconds(1)) .map(x -> Message.of(random.nextDouble()) .addMetadata(OutgoingKafkaRecordMetadata.builder() .withKey(""my-key"") .withTopic(""my-key-prices"") .withHeaders(new RecordHeaders().add(""my-header"", ""value"".getBytes())) .build())); } ---- `OutgoingKafkaRecordMetadata` allows to set metadata attributes of the Kafka record, such as `key`, `topic`, `partition` or `timestamp`. One use case is to dynamically select the destination topic of a message. In this case, instead of configuring the topic inside your application configuration file, you need to use the outgoing metadata to set the name of the topic. Other than method signatures returning a Reactive Stream `Publisher` (`Multi` being an implementation of `Publisher`), outgoing method can also return single message. In this case the producer will use this method as generator to create an infinite stream. [source, java] ---- @Outgoing(""prices-out"") T generate(); // T excluding void @Outgoing(""prices-out"") Message generate(); @Outgoing(""prices-out"") Uni generate(); @Outgoing(""prices-out"") Uni> generate(); @Outgoing(""prices-out"") CompletionStage generate(); @Outgoing(""prices-out"") CompletionStage> generate(); ---- === Sending messages with @Emitter Sometimes, you need to have an imperative way of sending messages. For example, if you need to send a message to a stream when receiving a POST request inside a REST endpoint. In this case, you cannot use `@Outgoing` because your method has parameters. For this, you can use an `Emitter`. [source, java] ---- import org.eclipse.microprofile.reactive.messaging.Channel; import org.eclipse.microprofile.reactive.messaging.Emitter; import javax.inject.Inject; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Consumes; import javax.ws.rs.core.MediaType; @Path(""/prices"") public class PriceResource { @Inject @Channel(""price-create"") Emitter priceEmitter; @POST @Consumes(MediaType.TEXT_PLAIN) public void addPrice(Double price) { CompletionStage ack = priceEmitter.send(price); } } ---- Sending a payload returns a `CompletionStage`, completed when the message is acked. If the message transmission fails, the `CompletionStage` is completed exceptionally with the reason of the nack. [NOTE] ==== The `Emitter` configuration is done the same way as the other stream configuration used by `@Incoming` and `@Outgoing`. ==== [IMPORTANT] ==== Using the `Emitter` you are sending messages from your imperative code to reactive messaging. These messages are stored in a queue until they are sent. If the Kafka producer client can't keep up with messages trying to be sent over to Kafka, this queue can become a memory hog and you may even run out of memory. You can use `@OnOverflow` to configure back-pressure strategy. It lets you configure the size of the queue (default is 256) and the strategy to apply when the buffer size is reached. Available strategies are `DROP`, `LATEST`, `FAIL`, `BUFFER`, `UNBOUNDED_BUFFER` and `NONE`. ==== With the `Emitter` API, you can also encapsulate the outgoing payload inside `Message`. As with the previous examples, `Message` lets you handle the ack/nack cases differently. [source,java] ---- import java.util.concurrent.CompletableFuture; import org.eclipse.microprofile.reactive.messaging.Channel; import org.eclipse.microprofile.reactive.messaging.Emitter; import javax.inject.Inject; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Consumes; import javax.ws.rs.core.MediaType; @Path(""/prices"") public class PriceResource { @Inject @Channel(""price-create"") Emitter priceEmitter; @POST @Consumes(MediaType.TEXT_PLAIN) public void addPrice(Double price) { priceEmitter.send(Message.of(price) .withAck(() -> { // Called when the message is acked return CompletableFuture.completedFuture(null); }) .withNack(throwable -> { // Called when the message is nacked return CompletableFuture.completedFuture(null); })); } } ---- If you prefer using Reactive Stream APIs, you can use `MutinyEmitter` that will return `Uni` from the `send` method. You can therefore use Mutiny APIs for handling downstream messages and errors. [source,java] ---- import org.eclipse.microprofile.reactive.messaging.Channel; import javax.inject.Inject; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Consumes; import javax.ws.rs.core.MediaType; import io.smallrye.reactive.messaging.MutinyEmitter; @Path(""/prices"") public class PriceResource { @Inject @Channel(""price-create"") MutinyEmitter priceEmitter; @POST @Consumes(MediaType.TEXT_PLAIN) public Uni addPrice(Double price) { return quoteRequestEmitter.send(price) .map(x -> ""ok"") .onFailure().recoverWithItem(""ko""); } } ---- It is also possible to block on sending the event to the emitter with the `sendAndAwait` method. It will only return from the method when the event is acked or nacked by the receiver. [NOTE] .Deprecation ==== The `io.smallrye.reactive.messaging.annotations.Emitter`, `io.smallrye.reactive.messaging.annotations.Channel` and `io.smallrye.reactive.messaging.annotations.OnOverflow` classes are now deprecated and replaced by: * `org.eclipse.microprofile.reactive.messaging.Emitter` * `org.eclipse.microprofile.reactive.messaging.Channel` * `org.eclipse.microprofile.reactive.messaging.OnOverflow` The new `Emitter.send` method returns a `CompletionStage` completed when the produced message is acknowledged. ==== === Write Acknowledgement When Kafka broker receives a record, its acknowledgement can take time depending on the configuration. Also, it stores in-memory the records that cannot be written. By default, the connector does wait for Kafka to acknowledge the record to continue the processing (acknowledging the received Message). You can disable this by setting the `waitForWriteCompletion` attribute to `false`. Note that the `acks` attribute has a huge impact on the record acknowledgement. If a record cannot be written, the message is nacked. === Backpressure The Kafka outbound connector handles back-pressure, monitoring the number of in-flight messages waiting to be written to the Kafka broker. The number of in-flight messages is configured using the `max-inflight-messages` attribute and defaults to 1024. The connector only sends that amount of messages concurrently. No other messages will be sent until at least one in-flight message gets acknowledged by the broker. Then, the connector writes a new message to Kafka when one of the broker’s in-flight messages get acknowledged. Be sure to configure Kafka’s `batch.size` and `linger.ms` accordingly. You can also remove the limit of in-flight messages by setting `max-inflight-messages` to `0`. However, note that the Kafka producer may block if the number of requests reaches `max.in.flight.requests.per.connection`. === Retrying message dispatch When the Kafka producer receives an error from the server, if it is a transient, recoverable error, the client will retry sending the batch of messages. This behavior is controlled by `retries` and `retry.backoff.ms` parameters. In addition to this, SmallRye Reactive Messaging will retry individual messages on recoverable errors, depending on the `retries` and `delivery.timeout.ms` parameters. Note that while having retries in a reliable system is a best practice, the `max.in.flight.requests.per.connection` parameter defaults to `5`, meaning that the order of the messages is not guaranteed. If the message order is a must for your use case, setting `max.in.flight.requests.per.connection` to `1` will make sure a single batch of messages is sent at a time, in the expense of limiting the throughput of the producer. For applying retry mechanism on processing errors, see the section on <>. === In-memory channels In some use cases, it is convenient to use the messaging patterns to transfer messages inside the same application. When you don't connect a channel to a messaging backend like Kafka, everything happens in-memory, and the streams are created by chaining methods together. Each chain is still a reactive stream and enforces the back-pressure protocol. The framework verifies that the producer/consumer chain is complete, meaning that if the application writes messages into an in-memory channel (using a method with only `@Outgoing`, or an `Emitter`), it must also consume the messages from within the application (using a method with only `@Incoming` or using an unmanaged stream). [[broadcasting-messages-on-multiple-consumers]] === Broadcasting messages on multiple consumers By default, a channel can be linked to a single consumer, using `@Incoming` method or `@Channel` reactive stream. At application startup, channels are verified to form a chain of consumers and producers with single consumer and producer. You can override this behavior by setting `mp.messaging.$channel.broadcast=true` on a channel. In case of in-memory channels, `@Broadcast` annotation can be used on the `@Outgoing` method. For example, [source, java] ---- import java.util.Random; import javax.enterprise.context.ApplicationScoped; import org.eclipse.microprofile.reactive.messaging.Incoming; import org.eclipse.microprofile.reactive.messaging.Outgoing; import io.smallrye.reactive.messaging.annotations.Broadcast; @ApplicationScoped public class MultipleConsumer { private final Random random = new Random(); @Outgoing(""in-memory-channel"") @Broadcast double generate() { return random.nextDouble(); } @Incoming(""in-memory-channel"") void consumeAndLog(double price) { System.out.println(price); } @Incoming(""in-memory-channel"") @Outgoing(""prices2"") double consumeAndSend(double price) { return price; } } ---- [NOTE] ==== Reciprocally, multiple producers on the same channel can be merged by setting `mp.messaging.incoming.$channel.merge=true`. On the `@Incoming` methods, you can control how multiple channels are merged using the `@Merge` annotation. ==== == Processing Messages Applications streaming data often need to consume some events from a topic, process them and publish the result to a different topic. A processor method can be simply implemented using both the `@Incoming` and `@Outgoing` annotations: [source, java] ---- import org.eclipse.microprofile.reactive.messaging.Incoming; import org.eclipse.microprofile.reactive.messaging.Outgoing; import javax.enterprise.context.ApplicationScoped; @ApplicationScoped public class PriceProcessor { private static final double CONVERSION_RATE = 0.88; @Incoming(""price-in"") @Outgoing(""price-out"") public double process(double price) { return price * CONVERSION_RATE; } } ---- The parameter of the `process` method is the incoming message payload, whereas the return value will be used as the outgoing message payload. Previously mentioned signatures for parameter and return types are also supported, such as `Message`, `Record`, etc. You can apply asynchronous stream processing by consuming and returning reactive stream `Multi` type: [source,java] ---- import javax.enterprise.context.ApplicationScoped; import org.eclipse.microprofile.reactive.messaging.Incoming; import org.eclipse.microprofile.reactive.messaging.Outgoing; import io.smallrye.mutiny.Multi; @ApplicationScoped public class PriceProcessor { private static final double CONVERSION_RATE = 0.88; @Incoming(""price-in"") @Outgoing(""price-out"") public Multi process(Multi prices) { return prices.filter(p -> p > 100).map(p -> p * CONVERSION_RATE); } } ---- === Propagating Record Key When processing messages, you can propagate incoming record key to the outgoing record. Enabled with `mp.messaging.outgoing.$channel.propagate-record-key=true` configuration, record key propagation produces the outgoing record with the same _key_ as the incoming record. If the outgoing record already contains a _key_, it *won't be overridden* by the incoming record key. If the incoming record does have a _null_ key, the `mp.messaging.outgoing.$channel.key` property is used. [[kafka-bare-clients]] == Accessing Kafka clients directly In rare cases, you may need to access the underlying Kafka clients. `KafkaClientService` provides thread-safe access to `Producer` and `Consumer`. [source,java] ---- import javax.enterprise.context.ApplicationScoped; import javax.enterprise.event.Observes; import javax.inject.Inject; import org.apache.kafka.clients.producer.ProducerRecord; import io.quarkus.runtime.StartupEvent; import io.smallrye.reactive.messaging.kafka.KafkaClientService; import io.smallrye.reactive.messaging.kafka.KafkaConsumer; import io.smallrye.reactive.messaging.kafka.KafkaProducer; @ApplicationScoped public class PriceSender { @Inject KafkaClientService clientService; void onStartup(@Observes StartupEvent startupEvent) { KafkaProducer producer = clientService.getProducer(""generated-price""); producer.runOnSendingThread(client -> client.send(new ProducerRecord<>(""prices"", 2.4))) .await().indefinitely(); } } ---- [IMPORTANT] ==== The `KafkaClientService` is an experimental API and can change in the future. ==== You can also get the Kafka configuration injected to your application and create Kafka producer, consumer and admin clients directly: [source,java] ---- import io.smallrye.common.annotation.Identifier; import org.apache.kafka.clients.admin.AdminClient; import org.apache.kafka.clients.admin.AdminClientConfig; import org.apache.kafka.clients.admin.KafkaAdminClient; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Produces; import javax.inject.Inject; import java.util.HashMap; import java.util.Map; @ApplicationScoped public class KafkaClients { @Inject @Identifier(""default-kafka-broker"") Map config; @Produces AdminClient getAdmin() { Map copy = new HashMap<>(); for (Map.Entry entry : config.entrySet()) { if (AdminClientConfig.configNames().contains(entry.getKey())) { copy.put(entry.getKey(), entry.getValue()); } } return KafkaAdminClient.create(copy); } } ---- This configuration map will contain all Kafka related properties configured inside `application.properties` file. [[kafka-serialization]] == JSON serialization Quarkus has built-in capabilities to deal with JSON Kafka messages. Imagine we have a `Fruit` data class as follows: [source,java] ---- public class Fruit { public String name; public int price; public Fruit() { } public Fruit(String name, int price) { this.name = name; this.price = price; } } ---- And we want to use it to receive messages from Kafka, make some price transformation, and send messages back to Kafka. [source,java] ---- import io.smallrye.reactive.messaging.annotations.Broadcast; import org.eclipse.microprofile.reactive.messaging.Incoming; import org.eclipse.microprofile.reactive.messaging.Outgoing; import javax.enterprise.context.ApplicationScoped; /** * A bean consuming data from the ""fruit-in"" channel and applying some price conversion. * The result is pushed to the ""fruit-out"" channel. */ @ApplicationScoped public class FruitProcessor { private static final double CONVERSION_RATE = 0.88; @Incoming(""fruit-in"") @Outgoing(""fruit-out"") @Broadcast public Fruit process(Fruit fruit) { fruit.price = fruit.price * CONVERSION_RATE; return fruit; } } ---- To do this, we will need to setup JSON serialization with Jackson or JSON-B. NOTE: With JSON serialization correctly configured, you can also use `Publisher` and `Emitter`. [[jackson-serialization]] === Serializing via Jackson First, you need to include the `quarkus-jackson` extension. [source, xml] ---- io.quarkus quarkus-jackson ---- There is an existing `ObjectMapperSerializer` that can be used to serialize all data objects via Jackson. You may create an empty subclass if you want to use <>. The corresponding deserializer class needs to be subclassed. So, let's create a `FruitDeserializer` that extends the `ObjectMapperDeserializer`. [source,java] ---- package com.acme.fruit.jackson; import io.quarkus.kafka.client.serialization.ObjectMapperDeserializer; public class FruitDeserializer extends ObjectMapperDeserializer { public FruitDeserializer() { super(Fruit.class); } } ---- Finally, configure your channels to use the Jackson serializer and deserializer. [source,properties] ---- # Configure the Kafka source (we read from it) mp.messaging.incoming.fruit-in.connector=smallrye-kafka mp.messaging.incoming.fruit-in.topic=fruit-in mp.messaging.incoming.fruit-in.value.deserializer=com.acme.fruit.jackson.FruitDeserializer # Configure the Kafka sink (we write to it) mp.messaging.outgoing.fruit-out.connector=smallrye-kafka mp.messaging.outgoing.fruit-out.topic=fruit-out mp.messaging.outgoing.fruit-out.value.serializer=io.quarkus.kafka.client.serialization.ObjectMapperSerializer ---- Now, your Kafka messages will contain a Jackson serialized representation of your `Fruit` data object. In this case, the `deserializer` configuration is not necessary as the <> is enabled by default. [[jsonb-serialization]] === Serializing via JSON-B First, you need to include the `quarkus-jsonb` extension. [source, xml] ---- io.quarkus quarkus-jsonb ---- There is an existing `JsonbSerializer` that can be used to serialize all data objects via JSON-B. You may create an empty subclass if you want to use <>. The corresponding deserializer class needs to be subclassed. So, let's create a `FruitDeserializer` that extends the generic `JsonbDeserializer`. [source,java] ---- package com.acme.fruit.jsonb; import io.quarkus.kafka.client.serialization.JsonbDeserializer; public class FruitDeserializer extends JsonbDeserializer { public FruitDeserializer() { super(Fruit.class); } } ---- Finally, configure your channels to use the JSON-B serializer and deserializer. [source,properties] ---- # Configure the Kafka source (we read from it) mp.messaging.incoming.fruit-in.connector=smallrye-kafka mp.messaging.incoming.fruit-in.topic=fruit-in mp.messaging.incoming.fruit-in.value.deserializer=com.acme.fruit.jsonb.FruitDeserializer # Configure the Kafka sink (we write to it) mp.messaging.outgoing.fruit-out.connector=smallrye-kafka mp.messaging.outgoing.fruit-out.topic=fruit-out mp.messaging.outgoing.fruit-out.value.serializer=io.quarkus.kafka.client.serialization.JsonbSerializer ---- Now, your Kafka messages will contain a JSON-B serialized representation of your `Fruit` data object. NOTE: If you don't want to create a deserializer for each data object, you can use the generic `io.vertx.kafka.client.serialization.JsonObjectDeserializer` that will deserialize to a `io.vertx.core.json.JsonObject`. The corresponding serializer can also be used: `io.vertx.kafka.client.serialization.JsonObjectSerializer`. == Avro Serialization This is described in a dedicated guide: link:kafka-schema-registry-avro[Using Apache Kafka with Schema Registry and Avro]. [[serialization-autodetection]] == Serializer/deserializer autodetection When using SmallRye Reactive Messaging with Kafka, Quarkus can often automatically detect the correct serializer and deserializer class. This autodetection is based on declarations of `@Incoming` and `@Outgoing` methods, as well as injected ``@Channel``s. For example, if you declare [source,java] ---- @Outgoing(""generated-price"") public Multi generate() { ... } ---- and your configuration indicates that the `generated-price` channel uses the `smallrye-kafka` connector, then Quarkus will automatically set the `value.serializer` to Kafka's built-in `IntegerSerializer`. Similarly, if you declare [source,java] ---- @Incoming(""my-kafka-records"") public void consume(KafkaRecord record) { ... } ---- and your configuration indicates that the `my-kafka-records` channel uses the `smallrye-kafka` connector, then Quarkus will automatically set the `key.deserializer` to Kafka's built-in `LongDeserializer`, as well as the `value.deserializer` to `ByteArrayDeserializer`. Finally, if you declare [source,java] ---- @Inject @Channel(""price-create"") Emitter priceEmitter; ---- and your configuration indicates that the `price-create` channel uses the `smallrye-kafka` connector, then Quarkus will automatically set the `value.serializer` to Kafka's built-in `DoubleSerializer`. The full set of types supported by the serializer/deserializer autodetection is: * `short` and `java.lang.Short` * `int` and `java.lang.Integer` * `long` and `java.lang.Long` * `float` and `java.lang.Float` * `double` and `java.lang.Double` * `byte[]` * `java.lang.String` * `java.util.UUID` * `java.nio.ByteBuffer` * `org.apache.kafka.common.utils.Bytes` * `io.vertx.core.buffer.Buffer` * `io.vertx.core.json.JsonObject` * `io.vertx.core.json.JsonArray` * classes generated from Avro schemas, as well as Avro `GenericRecord`, if Confluent or Apicurio Registry _serde_ is present ** see link:kafka-schema-registry-avro[Using Apache Kafka with Schema Registry and Avro] for more information about using Confluent or Apicurio Registry libraries * classes for which a subclass of `ObjectMapperSerializer` / `ObjectMapperDeserializer` is present, as described in <> ** it is technically not needed to subclass `ObjectMapperSerializer`, but in such case, autodetection isn't possible * classes for which a subclass of `JsonbSerializer` / `JsonbDeserializer` is present, as described in <> ** it is technically not needed to subclass `JsonbSerializer`, but in such case, autodetection isn't possible If a serializer/deserializer is set by configuration, it won't be replaced by the autodetection. In case you have any issues with serializer autodetection, you can switch it off completely by setting `quarkus.reactive-messaging.kafka.serializer-autodetection.enabled=false`. If you find you need to do this, please file a bug in the link:https://github.com/quarkusio/quarkus/issues[Quarkus issue tracker] so we can fix whatever problem you have. == Using Schema Registry This is described in a dedicated guide: link:kafka-schema-registry-avro[Using Apache Kafka with Schema Registry and Avro]. [[kafka-health-check]] == Health Checks Quarkus provides several health checks for Kafka. These checks are used in combination with the `quarkus-smallrye-health` extension. === Kafka Broker Readiness Check When using the `quarkus-kafka-client` extension, you can enable _readiness_ health check by setting the `quarkus.kafka.health.enabled` property to `true` in your `application.properties`. This check reports the status of the interaction with a _default_ Kafka broker (configured using `kafka.bootstrap.servers`). It requires an _admin connection_ with the Kafka broker, and it is disabled by default. If enabled, when you access the `/q/health/ready` endpoint of your application, you will have information about the connection validation status. === Kafka Reactive Messaging Health Checks When using Reactive Messaging and the Kafka connector, each configured channel (incoming or outgoing) provides _startup_, _liveness_ and _readiness_ checks. - The _startup_ check verifies that the communication with Kafka cluster is established. - The _liveness_ check captures any unrecoverable failure happening during the communication with Kafka. - The _readiness_ check verifies that the Kafka connector is ready to consume/produce messages to the configured Kafka topics. For each channel, you can disable the checks using: [source, properties] ---- # Disable both liveness and readiness checks with `health-enabled=false`: # Incoming channel (receiving records form Kafka) mp.messaging.incoming.your-channel.health-enabled=false # Outgoing channel (writing records to Kafka) mp.messaging.outgoing.your-channel.health-enabled=false # Disable only the readiness check with `health-readiness-enabled=false`: mp.messaging.incoming.your-channel.health-readiness-enabled=false mp.messaging.outgoing.your-channel.health-readiness-enabled=false ---- NOTE: You can configure the `bootstrap.servers` for each channel using `mp.messaging.incoming|outgoing.$channel.bootstrap.servers` property. Default is `kafka.bootstrap.servers`. Reactive Messaging _startup_ and _readiness_ checks offer two strategies. The default strategy verifies that an active connection is established with the broker. This approach is not intrusive as it's based on built-in Kafka client metrics. Using the `health-topic-verification-enabled=true` attribute, _startup_ probe uses an _admin client_ to check for the list of topics. Whereas the _readiness_ probe for an incoming channel checks that at least one partition is assigned for consumption, and for an outgoing channel checks that the topic used by the producer exist in the broker. Note that to achieve this, an _admin connection_ is required. You can adjust the timeout for topic verification calls to the broker using the `health-topic-verification-timeout` configuration. == Kafka Streams This is described in a dedicated guide: link:kafka-streams[Using Apache Kafka Streams]. == Using Snappy for message compression On _outgoing_ channels, you can enable Snappy compression by setting the `compression.type` attribute to `snappy`: [source, properties] ---- mp.messaging.outgoing.fruit-out.compression.type=snappy ---- In JVM mode, it will work out of the box. However, to compile your application to a native executable, you need to: 1. Uses GraalVM 21.+ 2. Add `quarkus.kafka.snappy.enabled=true` to your `application.properties` In native mode, Snappy is disabled by default as the use of Snappy requires embedding a native library and unpacking it when the application starts. == Authentication with OAuth If your Kafka broker uses OAuth as authentication mechanism, you need to configure the Kafka consumer to enable this authentication process. First, add the following dependency to your application: [source, xml] ---- io.strimzi kafka-oauth-client ---- This dependency provides the callback handler required to handle the OAuth workflow. Then, in the `application.properties`, add: [source, properties] ---- mp.messaging.connector.smallrye-kafka.security.protocol=SASL_PLAINTEXT mp.messaging.connector.smallrye-kafka.sasl.mechanism=OAUTHBEARER mp.messaging.connector.smallrye-kafka.sasl.jaas.config=org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required \\ oauth.client.id=""team-a-client"" \\ oauth.client.secret=""team-a-client-secret"" \\ oauth.token.endpoint.uri=""http://keycloak:8080/auth/realms/kafka-authz/protocol/openid-connect/token"" ; mp.messaging.connector.smallrye-kafka.sasl.login.callback.handler.class=io.strimzi.kafka.oauth.client.JaasClientOauthLoginCallbackHandler quarkus.ssl.native=true ---- Update the `oauth.client.id`, `oauth.client.secret` and `oauth.token.endpoint.uri` values. OAuth authentication works for both JVM and native modes. Since SSL in not enabled by default in native mode, `quarkus.ssl.native=true` must be added to support JaasClientOauthLoginCallbackHandler, which uses SSL. (See the xref:native-and-ssl.adoc[Using SSL with Native Executables] guide for more details.) == Testing a Kafka application === Testing without a broker It can be useful to test the application without having to start a Kafka broker. To achieve this, you can _switch_ the channels managed by the Kafka connector to _in-memory_. IMPORTANT: This approach only works for JVM tests. It cannot be used for native tests (because they do not support injection). First, add the following dependency to your application: [source, xml] ---- io.smallrye.reactive smallrye-reactive-messaging-in-memory test ---- Then, create a Quarkus Test Resource as follows: [source, java] ---- public class KafkaTestResourceLifecycleManager implements QuarkusTestResourceLifecycleManager { @Override public Map start() { Map env = new HashMap<>(); Map props1 = InMemoryConnector.switchIncomingChannelsToInMemory(""orders""); // <1> Map props2 = InMemoryConnector.switchOutgoingChannelsToInMemory(""queue""); // <2> env.putAll(props1); env.putAll(props2); return env; // <3> } @Override public void stop() { InMemoryConnector.clear(); // <4> } } ---- <1> Switch the incoming channel ""orders"" (expecting messages from Kafka) to in-memory. <2> Switch the outgoing channel ""queue"" (writing messages to Kafka) to in-memory. <3> Builds and returns a `Map` containing all the properties required to configure the application to use in-memory channels. <4> When the test stops, clear the `InMemoryConnector` (discard all the received and sent messages) Create a Quarkus Test using the test resource created above: [source, java] ---- @QuarkusTest @QuarkusTestResource(KafkaTestResourceLifecycleManager.class) class BaristaTest { @Inject InMemoryConnector connector; // <1> @Test void testProcessOrder() { InMemorySource orders = connector.source(""orders""); // <2> InMemorySink queue = connector.sink(""queue""); // <3> Order order = new Order(); order.setProduct(""coffee""); order.setName(""Coffee lover""); order.setOrderId(""1234""); orders.send(order); // <4> await().>>until(queue::received, t -> t.size() == 1); // <5> Beverage queuedBeverage = queue.received().get(0).getPayload(); Assertions.assertEquals(Beverage.State.READY, queuedBeverage.getPreparationState()); Assertions.assertEquals(""coffee"", queuedBeverage.getBeverage()); Assertions.assertEquals(""Coffee lover"", queuedBeverage.getCustomer()); Assertions.assertEquals(""1234"", queuedBeverage.getOrderId()); } } ---- <1> Inject the in-memory connector in your test class. <2> Retrieve the incoming channel (`orders`) - the channel must have been switched to in-memory in the test resource. <3> Retrieve the outgoing channel (`queue`) - the channel must have been switched to in-memory in the test resource. <4> Use the `send` method to send a message to the `orders` channel. So, the application will process this message. <5> Use the `received` method to check the messages produced by the application. === Starting Kafka in a test resource Alternatively, you can start a Kafka broker in a test resource. The following snippet shows a test resource starting a Kafka broker using https://www.testcontainers.org/modules/kafka/[Testcontainers]: [source, java] ---- public class KafkaResource implements QuarkusTestResourceLifecycleManager { private final KafkaContainer kafka = new KafkaContainer(); @Override public Map start() { kafka.start(); return Collections.singletonMap(""kafka.bootstrap.servers"", kafka.getBootstrapServers()); // <1> } @Override public void stop() { kafka.close(); } } ---- <1> Configure the Kafka bootstrap location, so the application connects to this broker. [[kafka-dev-services]] include::kafka-dev-services.adoc[leveloffset=+1] == Kubernetes Service Bindings Quarkus Kafka extension supports link:deploying-to-kubernetes[Service Binding Specification for Kubernetes]. You can enable this by adding the `quarkus-kubernetes-service-binding` extension to your application. When running in appropriately configured Kubernetes clusters, Kafka extension will pull its Kafka broker connection configuration from the service binding available inside the cluster, without the need for user configuration. == Execution model Reactive Messaging invokes user's methods on an I/O thread. Thus, by default, the methods must not block. As described in <>, you need to add the `@Blocking` annotation on the method if this method will block the caller thread. See the xref:quarkus-reactive-architecture.adoc[Quarkus Reactive Architecture documentation] for further details on this topic. [[kafka-configuration]] == Configuration Reference More details about the SmallRye Reactive Messaging configuration can be found in the https://smallrye.io/smallrye-reactive-messaging/smallrye-reactive-messaging/3.6/kafka/kafka.html[SmallRye Reactive Messaging - Kafka Connector Documentation]. The most important attributes are listed in the tables below: === Incoming channel configuration (polling from Kafka) The following attributes are configured using: [source, properties] ---- mp.messaging.incoming.your-channel-name.attribute=value ---- Some properties have aliases which can be configured globally: [source, properties] ---- kafka.bootstrap.servers=... ---- include::smallrye-kafka-incoming.adoc[] === Outgoing channel configuration (writing to Kafka) The following attributes are configured using: [source, properties] ---- mp.messaging.outgoing.your-channel-name.attribute=value ---- Some properties have aliases which can be configured globally: [source, properties] ---- kafka.bootstrap.servers=... ---- include::smallrye-kafka-outgoing.adoc[] == Integrating with Kafka - Common patterns === Writing to Kafka from an HTTP endpoint To send messages to Kafka from an HTTP endpoint, inject an `Emitter` (or a `MutinyEmitter`) in your endpoint: [source, java] ---- package org.acme; import java.util.concurrent.CompletionStage; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.eclipse.microprofile.reactive.messaging.Channel; import org.eclipse.microprofile.reactive.messaging.Emitter; @Path(""/"") public class ResourceSendingToKafka { @Channel(""kafka"") Emitter emitter; // <1> @POST @Produces(MediaType.TEXT_PLAIN) public CompletionStage send(String payload) { // <2> return emitter.send(payload); // <3> } } ---- <1> Inject an `Emitter` <2> The HTTP method receives the payload and returns a `CompletionStage` completed when the message is written to Kafka <3> Send the message to Kafka, the `send` method returns a `CompletionStage` The endpoint sends the passed payload (from a `POST` HTTP request) to the emitter. The emitter's channel is mapped to a Kafka topic in the `application.properties` file: [source, properties] ---- mp.messaging.outgoing.kafka.connector=smallrye-kafka mp.messaging.outgoing.kafka.topic=my-topic ---- The endpoint returns a `CompletionStage` indicating the asynchronous nature of the method. The `emitter.send` method returns a `CompletionStage` . The returned future is completed when the message has been written to Kafka. If the writing fails, the returned `CompletionStage` is completed exceptionally. If the endpoint does not return a `CompletionStage`, the HTTP response may be written before the message is sent to Kafka, and so failures won't be reported to the user. If you need to send a Kafka record, use: [source, java] ---- package org.acme; import java.util.concurrent.CompletionStage; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.eclipse.microprofile.reactive.messaging.Channel; import org.eclipse.microprofile.reactive.messaging.Emitter; import io.smallrye.reactive.messaging.kafka.Record; @Path(""/"") public class ResourceSendingToKafka { @Channel(""kafka"") Emitter> emitter; // <1> @POST @Produces(MediaType.TEXT_PLAIN) public CompletionStage send(String payload) { return emitter.send(Record.of(""my-key"", payload)); // <2> } } ---- <1> Note the usage of an `Emitter>` <2> Create the record using `Record.of(k, v)` === Persisting Kafka messages with Hibernate with Panache To persist objects received from Kafka into a database, you can use Hibernate with Panache. NOTE: If you use Hibernate Reactive, look at <>. Let's imagine you receive `Fruit` objects. For simplicity purposes, our `Fruit` class is pretty simple: [source, java] ---- package org.acme; import javax.persistence.Entity; import io.quarkus.hibernate.orm.panache.PanacheEntity; @Entity public class Fruit extends PanacheEntity { public String name; } ---- To consume `Fruit` instances stored on a Kafka topic, and persist them into a database, you can use the following approach: [source, java] ---- package org.acme; import javax.enterprise.context.ApplicationScoped; import javax.transaction.Transactional; import org.eclipse.microprofile.reactive.messaging.Incoming; import io.smallrye.common.annotation.Blocking; @ApplicationScoped public class FruitConsumer { @Incoming(""fruits"") // <1> @Transactional // <2> @Blocking // <3> public void persistFruits(Fruit fruit) { // <4> fruit.persist(); // <5> } } ---- <1> Configuring the incoming channel. This channel reads from Kafka. <2> As we are writing in a database, we must be in a transaction. This annotation starts a new transaction and commits it when the method returns. <3> Writing to a database using classic Hibernate is blocking. So, you must tell to Quarkus that the method must be called on a worker thread you can block (and not an I/O thread). <4> The method receives each Fruit. Note that you would need a deserializer to reconstruct the Fruit instances from the Kafka records. <5> Persist the received `fruit` object. As mentioned in <4>, you need a deserializer that can create a `Fruit` from the record. This can be done using a Jackson deserializer: [source, java] ---- package org.acme; import io.quarkus.kafka.client.serialization.ObjectMapperDeserializer; public class FruitDeserializer extends ObjectMapperDeserializer { public FruitDeserializer() { super(Fruit.class); } } ---- The associated configuration would be: [source, properties] ---- mp.messaging.incoming.fruits.connector=smallrye-kafka mp.messaging.incoming.fruits.value.deserializer=org.acme.FruitDeserializer ---- Check <> for more detail about the usage of Jackson with Kafka. You can also use Avro. [#persisting-kafka-messages-with-hibernate-reactive] === Persisting Kafka messages with Hibernate Reactive To persist objects received from Kafka into a database, you can use Hibernate Reactive with Panache. Let's imagine you receive `Fruit` objects. For simplicity purposes, our `Fruit` class is pretty simple: [source, java] ---- package org.acme; import javax.persistence.Entity; import io.quarkus.hibernate.reactive.panache.PanacheEntity; // <1> @Entity public class Fruit extends PanacheEntity { public String name; } ---- <1> Make sure to use the reactive variant To consume `Fruit` instances stored on a Kafka topic, and persist them into a database, you can use the following approach: [source, java] ---- package org.acme; import javax.enterprise.context.ApplicationScoped; import org.eclipse.microprofile.reactive.messaging.Incoming; import io.quarkus.hibernate.reactive.panache.Panache; import io.smallrye.mutiny.Uni; @ApplicationScoped public class FruitStore { @Incoming(""fruits"") public Uni persist(Fruit fruit) { return Panache.withTransaction(() -> // <1> fruit.persist() // <2> .map(persisted -> null) // <3> ); } } ---- <1> Instruct Panache to run the given (asynchronous) action in a transaction. The transaction completes when the action completes. <2> Persist the entity. It returns a `Uni`. <3> Switch back to a `Uni`. Unlike with _classic_ Hibernate, you can't use `@Transactional`. Instead, we use `Panache.withTransaction` and persist our entity. The `map` is used to return a `Uni` and not a `Uni`. You need a deserializer that can create a `Fruit` from the record. This can be done using a Jackson deserializer: [source, java] ---- package org.acme; import io.quarkus.kafka.client.serialization.ObjectMapperDeserializer; public class FruitDeserializer extends ObjectMapperDeserializer { public FruitDeserializer() { super(Fruit.class); } } ---- The associated configuration would be: [source, properties] ---- mp.messaging.incoming.fruits.connector=smallrye-kafka mp.messaging.incoming.fruits.value.deserializer=org.acme.FruitDeserializer ---- Check <> for more detail about the usage of Jackson with Kafka. You can also use Avro. === Writing entities managed by Hibernate to Kafka Let's imagine the following process: 1. You receive an HTTP request with a payload, 2. You create an Hibernate entity instance from this payload, 3. You persist that entity into a database, 4. You send the entity to a Kafka topic NOTE: If you use Hibernate Reactive, look at <>. Because we write to a database, we must run this method in a transaction. Yet, sending the entity to Kafka happens asynchronously. The operation returns a `CompletionStage` (or a `Uni` if you use a `MutinyEmitter`) reporting when the operation completes. We must be sure that the transaction is still running until the object is written. Otherwise, you may access the object outside the transaction, which is not allowed. To implement this process, you need the following approach: [source, java] ---- package org.acme; import java.util.concurrent.CompletionStage; import javax.transaction.Transactional; import javax.ws.rs.POST; import javax.ws.rs.Path; import org.eclipse.microprofile.reactive.messaging.Channel; import org.eclipse.microprofile.reactive.messaging.Emitter; @Path(""/"") public class ResourceSendingToKafka { @Channel(""kafka"") Emitter emitter; @POST @Path(""/fruits"") @Transactional // <1> public CompletionStage storeAndSendToKafka(Fruit fruit) { // <2> fruit.persist(); return emitter.send(fruit); // <3> } } ---- <1> As we are writing to the database, make sure we run inside a transaction <2> The method receives the fruit instance to persist. It returns a `CompletionStage` which is used for the transaction demarcation. The transaction is committed when the return `CompletionStage` completes. In our case, it's when the message is written to Kafka. <3> Send the managed instance to Kafka. Make sure we wait for the message to complete before closing the transaction. [#writing-entities-managed-by-hibernate-reactive-to-kafka] === Writing entities managed by Hibernate Reactive to Kafka To send to Kafka entities managed by Hibernate Reactive, we recommend using: * RESTEasy Reactive to serve HTTP requests * A `MutinyEmitter` to send message to a channel, so it can be easily integrated with the Mutiny API exposed by Hibernate Reactive or Hibernate Reactive with Panache. The following example demonstrates how to receive a payload, store it in the database using Hibernate Reactive with Panache, and send the persisted entity to Kafka: [source, java] ---- package org.acme; import javax.ws.rs.POST; import javax.ws.rs.Path; import org.eclipse.microprofile.reactive.messaging.Channel; import io.quarkus.hibernate.reactive.panache.Panache; import io.smallrye.mutiny.Uni; import io.smallrye.reactive.messaging.MutinyEmitter; @Path(""/"") public class ReactiveGreetingResource { @Channel(""kafka"") MutinyEmitter emitter; // <1> @POST @Path(""/fruits"") public Uni sendToKafka(Fruit fruit) { // <2> return Panache.withTransaction(() -> // <3> fruit.persist() ) .chain(f -> emitter.send(f)); // <4> } } ---- <1> Inject a `MutinyEmitter` which exposes a Mutiny API. It simplifies the integration with the Mutiny API exposed by Hibernate Reactive with Panache. <2> The HTTP method receiving the payload returns a `Uni`. The HTTP response is written when the operation completes (the entity is persisted and written to Kafka). <3> We need to write the entity into the database in a transaction. <4> Once the persist operation completes, we send the entity to Kafka. The `send` method returns a `Uni`. === Streaming Kafka topics as server-sent events Streaming a Kafka topic as server-sent events (SSE) is straightforward: 1. You inject the channel representing the Kafka topic in your HTTP endpoint 2. You return that channel as a `Publisher` or a `Multi` from the HTTP method The following code provides an example: [source, java] ---- @Channel(""fruits"") Multi fruits; @GET @Produces(MediaType.SERVER_SENT_EVENTS) public Multi stream() { return fruits; } ---- Some environment cuts the SSE connection when there is not enough activity. The workaround consists of sending _ping_ messages (or empty objects) periodically. [source, java] ---- @Channel(""fruits"") Multi fruits; @Inject ObjectMapper mapper; @GET @Produces(MediaType.SERVER_SENT_EVENTS) public Multi stream() { return Multi.createBy().merging() .streams( fruits.map(this::toJson), getPingStream() ); } Multi emitAPeriodicPing() { return Multi.createFrom().ticks().every(Duration.ofSeconds(10)) .onItem().transform(x -> ""{}""); } private String toJson(Fruit f) { try { return mapper.writeValueAsString(f); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } ---- The workaround is a bit more complex as besides sending the fruits coming from Kafka, we need to send pings periodically. To achieve this we merge the stream coming from Kafka and a periodic stream emitting `{}` every 10 seconds. == Going further This guide has shown how you can interact with Kafka using Quarkus. It utilizes SmallRye Reactive Messaging to build data streaming applications. If you want to go further, check the documentation of https://smallrye.io/smallrye-reactive-messaging[SmallRye Reactive Messaging], the implementation used in Quarkus. ",16352,True,2903.8890902360763,median "class zcl_abap_behv_test_trans_bufr2 definition public final create private. public section. interfaces zif_abap_behv_test_trans_bufr. class-methods: ""!

Get the transactional buffer instance

get_instance returning value(double_transactional_buffer) type ref to zif_abap_behv_test_trans_bufr. protected section. private section. ""Structure to hold bdef load attributes types: begin of t_bdef_load, head type cl_abap_behv_load=>t_head, entities type cl_abap_behv_load=>tt_entity, features type cl_abap_behv_load=>tt_feature, actions type cl_abap_behv_load=>tt_action, relations type cl_abap_behv_load=>tt_relat, associations type cl_abap_behv_load=>tt_assoc, end of t_bdef_load . types: begin of ty_double_transactional_buffer, entity_root type abp_root_entity_name, entity_name type abp_entity_name, entity_alias type abp_entity_name, entity_instances type ref to data, reported type ref to data, failed type ref to data, end of ty_double_transactional_buffer. class-data: ""!

Transactional buffer double singleton instance

double_transactional_buffer type ref to zif_abap_behv_test_trans_bufr. data: ""!

Transactional buffer double

dbl_transactional_buffer_table type standard table of ty_double_transactional_buffer with key entity_name. "" TODO : should we have a sorted table on entity name for binary search, or provide hashing to improve the search constants: c_message_class type symsgid value 'ZBO_MOCKING_MESSAGE'. methods: check_instance_equal importing instance_1 type any instance_2 type any entity_fields type ddfields returning value(equal) type abap_bool, check_instance_exists importing instance_to_check type any entity_instances type any table entity_fields type ddfields returning value(exists) type abap_bool, get_entity_fields importing entity_name type abp_entity_name returning value(entity_fields) type ddfields, deep_clone importing data_to_be_cloned type any exporting reference_to_cloned_data type ref to data, format_res_as_per_cntrl_flds importing control_fields type any entity_fields type ddfields changing entity_instance type any, fill_read_reported_and_failed importing i_entity_fields type ddfields alias_name type abp_entity_name message_number type symsgno retrieval type abp_behv_retrievals changing c_failed type data c_reported type data cs_retrieval_instance type any, fill_modify_reported_n_failed importing i_entity_fields type ddfields alias_name type abp_entity_name message_number type symsgno change type abp_behv_changes changing c_failed type data c_reported type data cs_change_instance type any, fill_modify_mapped importing i_entity_fields type ddfields alias_name type abp_entity_name message_number type symsgno change type abp_behv_changes changing c_mapped type data cs_change_instance type any, _create importing change type abp_behv_changes bdef_load type t_bdef_load changing failed type data mapped type data reported type data, _delete importing change type abp_behv_changes bdef_load type t_bdef_load changing failed type data mapped type data reported type data, cascade_delete importing instance type any associations type cl_abap_behv_load=>tt_assoc entity type abp_entity_name, _update importing change type abp_behv_changes bdef_load type t_bdef_load changing failed type data mapped type data reported type data, _create_by_assoc importing change type abp_behv_changes bdef_load type t_bdef_load changing failed type data mapped type data reported type data, _read importing retrieval type abp_behv_retrievals bdef_load type t_bdef_load changing failed type data reported type data, _read_by_assoc importing retrieval type abp_behv_retrievals bdef_load type t_bdef_load changing failed type data reported type data, find_reported_if_configured importing entities type cl_abap_behv_load=>tt_entity instance_to_check type any changing buffer_4_entity type ty_double_transactional_buffer c_reported type data. endclass. class zcl_abap_behv_test_trans_bufr2 implementation. method get_instance. if zcl_abap_behv_test_trans_bufr2=>double_transactional_buffer is initial. zcl_abap_behv_test_trans_bufr2=>double_transactional_buffer = new zcl_abap_behv_test_trans_bufr2( ). endif. double_transactional_buffer = zcl_abap_behv_test_trans_bufr2=>double_transactional_buffer. endmethod. method zif_abap_behv_test_trans_bufr~read. data bdef_load type t_bdef_load. field-symbols type abp_behv_retrievals. cl_abap_behv_load=>get_load( exporting entity = root_name all = abap_true importing head = bdef_load-head entities = bdef_load-entities features = bdef_load-features actions = bdef_load-actions relations = bdef_load-relations associations = bdef_load-associations ). loop at retrievals assigning . case -op. when if_abap_behv=>op-r-read. _read( exporting retrieval = bdef_load = bdef_load changing failed = failed reported = reported ). when if_abap_behv=>op-r-read_ba. _read_by_assoc( exporting retrieval = bdef_load = bdef_load changing failed = failed reported = reported ). endcase. endloop. endmethod. method zif_abap_behv_test_trans_bufr~modify. "" steps "" loop through each entity in the changes "" check whether a buffer entry is present in the transactional buffer or not for the entity "" if buffer entry is not present, first create a new buffer entry for the entity "" If operation is CREATE "" loop through instances of entity to be created from the change "" for each instance to create, check whether the buffer entry for the entity already has an entry with same keys "" if entry is already present fill the failed and reported structure "" if instance is not present add the instance to the buffer entry and fill the mapped structure "" if operation is UPDATE "" check whether the buffer contains an entry with the same primary keys, if present update the instance and fill mapped "" if not available, fill failed and reported "" if operation is DELETE "" check whether the buffer contains an entry with the same primary keys, if present delete the instance "" if not available, fill failed and reported data bdef_load type t_bdef_load. cl_abap_behv_load=>get_load( exporting entity = root_name all = abap_true importing head = bdef_load-head entities = bdef_load-entities features = bdef_load-features actions = bdef_load-actions relations = bdef_load-relations associations = bdef_load-associations ). loop at changes assigning field-symbol(). case -op. when if_abap_behv=>op-m-create. _create( exporting change = bdef_load = bdef_load changing failed = failed mapped = mapped reported = reported ). when if_abap_behv=>op-m-update. _update( exporting change = bdef_load = bdef_load changing failed = failed mapped = mapped reported = reported ). when if_abap_behv=>op-m-delete. _delete( exporting change = bdef_load = bdef_load changing failed = failed mapped = mapped reported = reported ). when if_abap_behv=>op-m-create_ba. _create_by_assoc( exporting change = bdef_load = bdef_load changing failed = failed mapped = mapped reported = reported ). endcase. endloop. endmethod. method check_instance_equal. data entity_field type dfies. field-symbols type any. field-symbols type any. loop at entity_fields into entity_field where keyflag = abap_true. assign component entity_field-fieldname of structure instance_1 to . assign component entity_field-fieldname of structure instance_2 to . if <> . "" entity does not match equal = abap_false. return. endif. endloop. equal = abap_true. return. endmethod. method check_instance_exists. field-symbols type any. loop at entity_instances assigning . data(equal) = check_instance_equal( instance_1 = instance_to_check instance_2 = entity_fields = entity_fields ). if equal = abap_true. exists = abap_true. return. endif. endloop. exists = abap_false. endmethod. method get_entity_fields. data struct_descr type ref to cl_abap_structdescr. struct_descr ?= cl_abap_typedescr=>describe_by_name( entity_name ). entity_fields = struct_descr->get_ddic_field_list( ). endmethod. method deep_clone. field-symbols type any. create data reference_to_cloned_data like data_to_be_cloned. assign reference_to_cloned_data->* to . = data_to_be_cloned. endmethod. method format_res_as_per_cntrl_flds. data entity_field type dfies. field-symbols type any. field-symbols type any. loop at entity_fields into entity_field where fieldname <> '.NODE1' and keyflag = abap_false. assign component entity_field-fieldname of structure control_fields to . if = if_abap_behv=>mk-off. "" clear data assign component entity_field-fieldname of structure entity_instance to . clear . endif. endloop. endmethod. method fill_read_reported_and_failed. field-symbols type standard table. field-symbols type standard table. assign component alias_name of structure c_failed to . data entry_failed type ref to data. create data entry_failed like line of . assign entry_failed->* to field-symbol(). ""Assign key fields loop at i_entity_fields into data(entity_field) where keyflag = abap_true. assign component entity_field-fieldname of structure cs_retrieval_instance to field-symbol(). assign component entity_field-fieldname of structure to field-symbol(). = . endloop. ""Assign fail reason assign component cl_abap_behv=>co_techfield_name-fail of structure to field-symbol(). assign component 'CAUSE' of structure to field-symbol(). = if_abap_behv=>cause-not_found. ""Assign Association if read by association operation. if retrieval-op eq if_abap_behv=>op-r-read_ba. assign component cl_abap_behv=>co_techfield_name-assoc of structure to field-symbol(). assign component retrieval-sub_name of structure to field-symbol(). = '01'. endif. append to . ""Fill reported assign component alias_name of structure c_reported to . data entry_reported type ref to data. create data entry_reported like line of . assign entry_reported->* to field-symbol(). ""Assign key fields loop at i_entity_fields into entity_field where keyflag = abap_true. assign component entity_field-fieldname of structure cs_retrieval_instance to . assign component entity_field-fieldname of structure to . = . endloop. ""Assign exception message instance data(lo_message) = new lcl_exception_handler( )->new_message( id = c_message_class number = message_number severity = if_abap_behv_message=>severity-error ). field-symbols: type ref to if_abap_behv_message. field-symbols: type ref to if_abap_behv_message. assign component cl_abap_behv=>co_techfield_name-msg of structure to . assign lo_message to . = . append to . endmethod. method fill_modify_reported_n_failed. field-symbols type standard table. field-symbols type standard table. assign component alias_name of structure c_failed to . data entry_failed type ref to data. create data entry_failed like line of . assign entry_failed->* to field-symbol(). ""Assign key fields loop at i_entity_fields into data(entity_field) where keyflag = abap_true. assign component entity_field-fieldname of structure cs_change_instance to field-symbol(). assign component entity_field-fieldname of structure to field-symbol(). = . endloop. ""Assign fail reason assign component cl_abap_behv=>co_techfield_name-fail of structure to field-symbol(). assign component 'CAUSE' of structure to field-symbol(). "" Make operation specific additions to failed case change-op. when if_abap_behv=>op-m-create. = if_abap_behv=>cause-unspecific. assign component cl_abap_behv=>co_techfield_name-create of structure to field-symbol(). = '01'. when if_abap_behv=>op-m-create_ba. = if_abap_behv=>cause-unspecific. assign component cl_abap_behv=>co_techfield_name-create of structure to . = '01'. when if_abap_behv=>op-m-update. = if_abap_behv=>cause-not_found. assign component cl_abap_behv=>co_techfield_name-update of structure to field-symbol(). = '01'. when if_abap_behv=>op-m-delete. = if_abap_behv=>cause-not_found. assign component cl_abap_behv=>co_techfield_name-delete of structure to field-symbol(). = '01'. endcase. append to . ""Fill reported assign component alias_name of structure c_reported to . data entry_reported type ref to data. create data entry_reported like line of . assign entry_reported->* to field-symbol(). ""Assign key fields loop at i_entity_fields into entity_field where keyflag = abap_true. assign component entity_field-fieldname of structure cs_change_instance to . assign component entity_field-fieldname of structure to . = . endloop. ""Assign exception message instance data(lo_message) = new lcl_exception_handler( )->new_message( id = c_message_class number = message_number severity = if_abap_behv_message=>severity-error ). field-symbols: type ref to if_abap_behv_message. field-symbols: type ref to if_abap_behv_message. assign component cl_abap_behv=>co_techfield_name-msg of structure to . assign lo_message to . = . append to . endmethod. method fill_modify_mapped. field-symbols type standard table. assign component alias_name of structure c_mapped to . data entry_mapped type ref to data. create data entry_mapped like line of . assign entry_mapped->* to field-symbol(). ""Assign key fields loop at i_entity_fields into data(entity_field) where keyflag = abap_true. assign component entity_field-fieldname of structure cs_change_instance to field-symbol(). assign component entity_field-fieldname of structure to field-symbol(). = . endloop. append to . endmethod. method cascade_delete. data buffer_4_assoc_entity type ty_double_transactional_buffer. data buffer_4_entity type ty_double_transactional_buffer. data entity_buffer_instance type ref to data. data(entity_fields) = get_entity_fields( entity ). read table associations into data(association) with key source_entity = entity. if sy-subrc eq 0. data(associated_entity) = association-target_entity. endif. if associated_entity is not initial. if line_exists( dbl_transactional_buffer_table[ entity_name = associated_entity ] ). buffer_4_assoc_entity = dbl_transactional_buffer_table[ entity_name = associated_entity ]. endif. if buffer_4_assoc_entity is not initial. field-symbols type standard table. assign buffer_4_assoc_entity-entity_instances->* to . if is assigned. loop at assigning field-symbol(). ""check if the instance is associated with the input entity instance data(equal) = check_instance_equal( exporting instance_1 = instance_2 = instance entity_fields = entity_fields "" here we are passing the entity fields of parent entity and not associated entity because "" the read happens only based on the key value of parent and not associated entity ). if equal eq abap_true. cascade_delete( associations = associations entity = associated_entity instance = ). endif. endloop. endif. endif. endif. ""delete the instance if line_exists( dbl_transactional_buffer_table[ entity_name = entity ] ). buffer_4_entity = dbl_transactional_buffer_table[ entity_name = entity ]. if buffer_4_entity is not initial. field-symbols type standard table. assign buffer_4_entity-entity_instances->* to . "" TODO: Check if an assignment check is required. loop at assigning field-symbol(). ""look for a matching instance to be deleted equal = check_instance_equal( exporting instance_1 = instance_2 = instance entity_fields = entity_fields ). if equal eq abap_true. delete . exit. endif. endloop. endif. endif. endmethod. method _create_by_assoc. data buffer_4_entity type ty_double_transactional_buffer. data entity_buffer_instance type ref to data. data struct_descr_4_entity type ref to cl_abap_structdescr. data entity_fields type ddfields. field-symbols type standard table. field-symbols type standard table. field-symbols type any. field-symbols type any. if line_exists( dbl_transactional_buffer_table[ entity_name = change-entity_name ] ). buffer_4_entity = dbl_transactional_buffer_table[ entity_name = change-entity_name ]. endif. if buffer_4_entity is initial. "" no buffer entry present for the entity buffer_4_entity-entity_name = change-entity_name. buffer_4_entity-entity_instances = cl_abap_behvdescr=>create_data( p_name = change-entity_name p_op = if_abap_behv=>op-r-read ""TODO : Should it be modify/read? p_kind = if_abap_behv=>typekind-result ). append buffer_4_entity to dbl_transactional_buffer_table. endif. struct_descr_4_entity ?= cl_abap_typedescr=>describe_by_name( change-entity_name ). entity_fields = struct_descr_4_entity->get_ddic_field_list( ). data(entity_details) = bdef_load-entities[ name = change-entity_name ]. data(alias) = entity_details-alias. alias = to_upper( alias ). if alias is not initial. buffer_4_entity-entity_alias = alias. else. buffer_4_entity-entity_alias = change-entity_name. endif. ""Won't be filled in all the use cases. assign buffer_4_entity-entity_instances->* to . assign change-instances->* to . loop at assigning . ""check whether the entity instance is already present in the buffer data(instance_exists_in_buffer) = check_instance_exists( exporting instance_to_check = entity_instances = entity_fields = entity_fields ). data buffer_4_assoc_entity type ty_double_transactional_buffer. data struct_descr_assoc_entity type ref to cl_abap_structdescr. data entity_fields_of_assoc_entity type ddfields. field-symbols type standard table. field-symbols type any. data(association) = bdef_load-associations[ source_entity = change-entity_name ]. data(associated_entity) = association-target_entity. struct_descr_assoc_entity ?= cl_abap_typedescr=>describe_by_name( associated_entity ). entity_fields_of_assoc_entity = struct_descr_assoc_entity->get_ddic_field_list( ). assign component cl_abap_behv=>co_techfield_name-target of structure to . loop at assigning . "" make sure the foreign key values are filled in the associated entity instance loop at bdef_load-relations[ source_entity = associated_entity ]-foreignkeys into data(key). assign component key-local_name of structure to field-symbol(). assign component key-local_name of structure to field-symbol(). = . endloop. "" Check if buffer entry exists for the associated entity if line_exists( dbl_transactional_buffer_table[ entity_name = associated_entity ] ). buffer_4_assoc_entity = dbl_transactional_buffer_table[ entity_name = associated_entity ]. endif. if buffer_4_assoc_entity is initial. "" no buffer entry present for the associated entity buffer_4_assoc_entity-entity_name = associated_entity. buffer_4_assoc_entity-entity_instances = cl_abap_behvdescr=>create_data( p_name = associated_entity p_op = if_abap_behv=>op-r-read p_kind = if_abap_behv=>typekind-result ). append buffer_4_assoc_entity to dbl_transactional_buffer_table. endif. "" evaluate the alias name for associated entity data(assoc_entity_details) = bdef_load-entities[ name = associated_entity ]. data(assoc_entity_alias) = assoc_entity_details-alias. assoc_entity_alias = to_upper( assoc_entity_alias ). if assoc_entity_alias is not initial. buffer_4_assoc_entity-entity_alias = assoc_entity_alias. else. assoc_entity_alias = associated_entity. buffer_4_assoc_entity-entity_alias = associated_entity. endif. ""Won't be filled in all the use cases. "" if the parent entity instance itself doesn't exist "" fill mapped and reported. No further processing required if instance_exists_in_buffer = abap_false. "" fill failed and reported fill_modify_reported_n_failed( exporting i_entity_fields = entity_fields_of_assoc_entity alias_name = assoc_entity_alias message_number = 001 change = change changing c_failed = failed c_reported = reported cs_change_instance = ). continue. endif. field-symbols type standard table. assign buffer_4_assoc_entity-entity_instances->* to . ""check whether the associated entity instance is already present in the buffer data(assoc_instance_exists_in_buff) = check_instance_exists( exporting instance_to_check = entity_instances = entity_fields = entity_fields_of_assoc_entity ). if assoc_instance_exists_in_buff = abap_true. "" fill failed and reported fill_modify_reported_n_failed( exporting i_entity_fields = entity_fields_of_assoc_entity alias_name = assoc_entity_alias message_number = 001 change = change changing c_failed = failed c_reported = reported cs_change_instance = ). else. data assoc_entity_buffer_instance type ref to data. field-symbols type any. create data assoc_entity_buffer_instance like line of . assign assoc_entity_buffer_instance->* to . = corresponding #( ). append to . "" Fill mapped table fill_modify_mapped( exporting alias_name = assoc_entity_alias i_entity_fields = entity_fields_of_assoc_entity message_number = '001' change = change changing c_mapped = mapped cs_change_instance = ). endif. endloop. endloop. endmethod. method _create. data buffer_4_entity type ty_double_transactional_buffer. data entity_buffer_instance type ref to data. data struct_descr_4_entity type ref to cl_abap_structdescr. data entity_fields type ddfields. field-symbols type standard table. field-symbols type standard table. field-symbols type any. field-symbols type any. if line_exists( dbl_transactional_buffer_table[ entity_name = change-entity_name ] ). buffer_4_entity = dbl_transactional_buffer_table[ entity_name = change-entity_name ]. endif. if buffer_4_entity is initial. "" no buffer entry present for the entity buffer_4_entity-entity_name = change-entity_name. buffer_4_entity-entity_instances = cl_abap_behvdescr=>create_data( p_name = change-entity_name p_op = if_abap_behv=>op-r-read ""TODO : Should it be modify/read? p_kind = if_abap_behv=>typekind-result ). append buffer_4_entity to dbl_transactional_buffer_table. endif. struct_descr_4_entity ?= cl_abap_typedescr=>describe_by_name( change-entity_name ). entity_fields = struct_descr_4_entity->get_ddic_field_list( ). data(entity_details) = bdef_load-entities[ name = change-entity_name ]. data(alias) = entity_details-alias. alias = to_upper( alias ). if alias is not initial. buffer_4_entity-entity_alias = alias. else. buffer_4_entity-entity_alias = change-entity_name. endif. ""Won't be filled in all the use cases. assign buffer_4_entity-entity_instances->* to . assign change-instances->* to . loop at assigning . ""check whether the entity instance is already present in the buffer data(instance_exists_in_buffer) = check_instance_exists( exporting instance_to_check = entity_instances = entity_fields = entity_fields ). if instance_exists_in_buffer = abap_true. "" fill failed and reported fill_modify_reported_n_failed( exporting i_entity_fields = entity_fields alias_name = alias message_number = 001 change = change changing c_failed = failed c_reported = reported cs_change_instance = ). data: found_reported_inst type ref to data. field-symbols: type any. assign buffer_4_entity to . find_reported_if_configured( exporting entities = bdef_load-entities instance_to_check = changing buffer_4_entity = c_reported = reported ). else. "" Create instance create data entity_buffer_instance like line of . assign entity_buffer_instance->* to . = corresponding #( ). append to . "" Fill mapped table fill_modify_mapped( exporting alias_name = alias i_entity_fields = entity_fields message_number = '001' change = change changing c_mapped = mapped cs_change_instance = ). endif. endloop. endmethod. method _delete. data buffer_4_entity type ty_double_transactional_buffer. data entity_buffer_instance type ref to data. data struct_descr_4_entity type ref to cl_abap_structdescr. data entity_fields type ddfields. field-symbols type standard table. field-symbols type standard table. field-symbols type any. field-symbols type any. if line_exists( dbl_transactional_buffer_table[ entity_name = change-entity_name ] ). buffer_4_entity = dbl_transactional_buffer_table[ entity_name = change-entity_name ]. endif. if buffer_4_entity is initial. "" no buffer entry present for the entity buffer_4_entity-entity_name = change-entity_name. buffer_4_entity-entity_instances = cl_abap_behvdescr=>create_data( p_name = change-entity_name p_op = if_abap_behv=>op-r-read ""TODO : Should it be modify/read? p_kind = if_abap_behv=>typekind-result ). append buffer_4_entity to dbl_transactional_buffer_table. endif. struct_descr_4_entity ?= cl_abap_typedescr=>describe_by_name( change-entity_name ). entity_fields = struct_descr_4_entity->get_ddic_field_list( ). data(entity_details) = bdef_load-entities[ name = change-entity_name ]. data(alias) = entity_details-alias. alias = to_upper( alias ). if alias is not initial. buffer_4_entity-entity_alias = alias. else. buffer_4_entity-entity_alias = change-entity_name. endif. ""Won't be filled in all the use cases. assign buffer_4_entity-entity_instances->* to . assign change-instances->* to . loop at assigning . ""check whether the entity instance is already present in the buffer data(instance_exists_in_buffer) = check_instance_exists( exporting instance_to_check = entity_instances = entity_fields = entity_fields ). if instance_exists_in_buffer = abap_false. "" fill failed and reported fill_modify_reported_n_failed( exporting i_entity_fields = entity_fields alias_name = alias message_number = 001 change = change changing c_failed = failed c_reported = reported cs_change_instance = ). else. ""delete the instance, along with all the associated instances cascade_delete( associations = bdef_load-associations entity = change-entity_name instance = ). ""no mapped in this case. endif. endloop. endmethod. method _update. data buffer_4_entity type ty_double_transactional_buffer. data entity_buffer_instance type ref to data. data struct_descr_4_entity type ref to cl_abap_structdescr. data entity_fields type ddfields. field-symbols type standard table. field-symbols type standard table. field-symbols type any. field-symbols type any. if line_exists( dbl_transactional_buffer_table[ entity_name = change-entity_name ] ). buffer_4_entity = dbl_transactional_buffer_table[ entity_name = change-entity_name ]. endif. if buffer_4_entity is initial. "" no buffer entry present for the entity buffer_4_entity-entity_name = change-entity_name. buffer_4_entity-entity_instances = cl_abap_behvdescr=>create_data( p_name = change-entity_name p_op = if_abap_behv=>op-r-read ""TODO : Should it be modify/read? p_kind = if_abap_behv=>typekind-result ). append buffer_4_entity to dbl_transactional_buffer_table. endif. struct_descr_4_entity ?= cl_abap_typedescr=>describe_by_name( change-entity_name ). entity_fields = struct_descr_4_entity->get_ddic_field_list( ). data(entity_details) = bdef_load-entities[ name = change-entity_name ]. data(alias) = entity_details-alias. alias = to_upper( alias ). if alias is not initial. buffer_4_entity-entity_alias = alias. else. buffer_4_entity-entity_alias = change-entity_name. endif. ""Won't be filled in all the use cases. assign buffer_4_entity-entity_instances->* to . assign change-instances->* to . loop at assigning . ""check whether the entity instance is already present in the buffer data(instance_exists_in_buffer) = check_instance_exists( exporting instance_to_check = entity_instances = entity_fields = entity_fields ). if instance_exists_in_buffer = abap_false. "" fill failed and reported fill_modify_reported_n_failed( exporting i_entity_fields = entity_fields alias_name = alias message_number = 001 change = change changing c_failed = failed c_reported = reported cs_change_instance = ). else. "" update the instance create data entity_buffer_instance like line of . assign entity_buffer_instance->* to . = corresponding #( ). modify table from . "" fill mapped fill_modify_mapped( exporting alias_name = alias i_entity_fields = entity_fields message_number = '001' change = change changing c_mapped = mapped cs_change_instance = ). endif. endloop. endmethod. method _read. data entity_fields type ddfields. data buffer_entry_for_entity type ty_double_transactional_buffer. data entity_buffer_instance_copy type ref to data. field-symbols type standard table. field-symbols type any. field-symbols type any. field-symbols type standard table. field-symbols type any. field-symbols type any. field-symbols type standard table. "" retrieve the buffer entry for the entity if line_exists( dbl_transactional_buffer_table[ entity_name = retrieval-entity_name ] ). buffer_entry_for_entity = dbl_transactional_buffer_table[ entity_name = retrieval-entity_name ]. loop at bdef_load-entities into data(entity) where name = retrieval-entity_name. buffer_entry_for_entity-entity_alias = entity-alias. exit. endloop. endif. "" retrieve fields of the entity entity_fields = get_entity_fields( retrieval-entity_name ). "" get the reference to the entity instances requested assign retrieval-instances->* to . "" get the reference to the output result assign retrieval-results->* to . "" get the reference to the entity instances in buffer assign buffer_entry_for_entity-entity_instances->* to . "" TODO: Fill failed structure when the entry does not exist in the transactional buffer if buffer_entry_for_entity is initial. ""TODO: Throw exception that entity doesn't exist. data(entity_details) = retrieval-entity_name. loop at bdef_load-entities into entity where name = retrieval-entity_name. buffer_entry_for_entity-entity_alias = entity-alias. exit. endloop. data(alias) = buffer_entry_for_entity-entity_alias. alias = to_upper( alias ). loop at assigning . fill_read_reported_and_failed( exporting i_entity_fields = entity_fields alias_name = alias message_number = 001 retrieval = retrieval changing c_failed = failed c_reported = reported cs_retrieval_instance = ). endloop. exit. endif. "" TODO: Probably we can get rid of key fields calculation from the structure. Because the retrieval instance entry already "" has all the key fields. So probably loop through the components and filter out the key fields. *---- read the buffer entries corresponding to the entries in the retrieval table loop at assigning . "" check whether the retrieval entry is present in the buffer loop at assigning . data(equal) = check_instance_equal( exporting instance_1 = instance_2 = entity_fields = entity_fields ). if equal = abap_true. "" create a copy of buffer instance entry deep_clone( exporting data_to_be_cloned = importing reference_to_cloned_data = entity_buffer_instance_copy ). assign entity_buffer_instance_copy->* to . "" format data as per the control structures provided assign component '%control' of structure to . format_res_as_per_cntrl_flds( exporting control_fields = entity_fields = entity_fields changing entity_instance = ). append to . exit. endif. endloop. ""Instance doesn't exist in buffer if equal eq abap_false. entity_details = retrieval-entity_name. alias = buffer_entry_for_entity-entity_alias. alias = to_upper( alias ). fill_read_reported_and_failed( exporting i_entity_fields = entity_fields alias_name = alias message_number = 001 retrieval = retrieval changing c_failed = failed c_reported = reported cs_retrieval_instance = ). endif. assign buffer_entry_for_entity to field-symbol(). find_reported_if_configured( exporting entities = bdef_load-entities instance_to_check = changing buffer_4_entity = c_reported = reported ). endloop. endmethod. method _read_by_assoc. data entity_fields type ddfields. data buffer_entry_for_entity type ty_double_transactional_buffer. data entity_buffer_instance_copy type ref to data. field-symbols type standard table. field-symbols type any. field-symbols type any. field-symbols type standard table. field-symbols type any. field-symbols type any. field-symbols type standard table. "" retrieve the buffer entry for the entity if line_exists( dbl_transactional_buffer_table[ entity_name = retrieval-entity_name ] ). buffer_entry_for_entity = dbl_transactional_buffer_table[ entity_name = retrieval-entity_name ]. loop at bdef_load-entities into data(entity) where name = retrieval-entity_name. buffer_entry_for_entity-entity_alias = entity-alias. exit. endloop. endif. "" retrieve fields of the entity entity_fields = get_entity_fields( retrieval-entity_name ). "" get the reference to the entity instances requested assign retrieval-instances->* to . "" get the reference to the output result assign retrieval-results->* to . "" get the reference to the entity instances in buffer assign buffer_entry_for_entity-entity_instances->* to . "" TODO: Fill failed structure when the entry does not exist in the transactional buffer if buffer_entry_for_entity is initial. ""TODO: Throw exception that entity doesn't exist. data(entity_details) = retrieval-entity_name. loop at bdef_load-entities into entity where name = retrieval-entity_name. buffer_entry_for_entity-entity_alias = entity-alias. exit. endloop. data(alias) = buffer_entry_for_entity-entity_alias. alias = to_upper( alias ). loop at assigning . fill_read_reported_and_failed( exporting i_entity_fields = entity_fields alias_name = alias message_number = 001 retrieval = retrieval changing c_failed = failed c_reported = reported cs_retrieval_instance = ). endloop. exit. endif. "" TODO: Probably we can get rid of key fields calculation from the structure. Because the retrieval instance entry already "" has all the key fields. So probably loop through the components and filter out the key fields. *---- read the associated entity buffer entries corresponding to the entries in the retrieval table data(association) = bdef_load-associations[ name = retrieval-sub_name ]. data(associated_entity) = association-target_entity. data buffer_entry_for_assoc_entity type ty_double_transactional_buffer. "" retrieve fields of the associated entity data(assoc_entity_fields) = get_entity_fields( associated_entity ). loop at assigning . "" check whether the retrieval entry is present in the buffer loop at assigning . data(parent_equal) = check_instance_equal( exporting instance_1 = instance_2 = entity_fields = entity_fields ). if parent_equal = abap_true. "" retrieve the buffer entry for the associated entity if line_exists( dbl_transactional_buffer_table[ entity_name = associated_entity ] ). buffer_entry_for_assoc_entity = dbl_transactional_buffer_table[ entity_name = associated_entity ]. loop at bdef_load-entities into entity where name = associated_entity. buffer_entry_for_assoc_entity-entity_alias = entity-alias. exit. endloop. endif. field-symbols type standard table. assign buffer_entry_for_assoc_entity-entity_instances->* to . "" check whether the retrieval entry is present in the buffer if is assigned. loop at assigning field-symbol(). data(equal) = check_instance_equal( exporting instance_1 = instance_2 = entity_fields = entity_fields "" here we are passing the entity fields of parent entity and not associated entity because "" the read happens only based on the key value of parent and not associated entity ). if equal = abap_true. "" create a copy of buffer instance entry deep_clone( exporting data_to_be_cloned = importing reference_to_cloned_data = entity_buffer_instance_copy ). assign entity_buffer_instance_copy->* to . "" format data as per the control structures provided assign component '%control' of structure to . format_res_as_per_cntrl_flds( exporting control_fields = entity_fields = assoc_entity_fields changing entity_instance = ). append to . "" exit. endif. endloop. endif. continue. endif. endloop. "" If the parent entity itself does not exist if parent_equal eq abap_false. "" fill failed and reported alias = buffer_entry_for_entity-entity_alias. alias = to_upper( alias ). fill_read_reported_and_failed( exporting i_entity_fields = entity_fields alias_name = alias message_number = 001 retrieval = retrieval changing c_failed = failed c_reported = reported cs_retrieval_instance = ). endif. endloop. endmethod. method zif_abap_behv_test_trans_bufr~config_error_response_4_modify. data bdef_load type t_bdef_load. field-symbols: type ty_double_transactional_buffer, type standard table, type any, type standard table. cl_abap_behv_load=>get_load( exporting entity = root_name all = abap_true importing head = bdef_load-head entities = bdef_load-entities features = bdef_load-features actions = bdef_load-actions relations = bdef_load-relations associations = bdef_load-associations ). ""Fill reported. if reported is not initial. loop at bdef_load-entities into data(entity). if entity-alias is initial. assign component to_upper( entity-name ) of structure reported to . if is assigned. break-point. endif. else. assign component to_upper( entity-alias ) of structure reported to . if is assigned and is not initial. ""Check if double transactional buffer contains the entity and entity instance. loop at assigning field-symbol(). if line_exists( dbl_transactional_buffer_table[ entity_name = entity-name ] ). "" = dbl_transactional_buffer_table[ entity_name = entity-name ]. assign dbl_transactional_buffer_table[ entity_name = entity-name ] to . assign -entity_instances->* to . data(entity_fields) = get_entity_fields( entity-name ). loop at assigning . data(equal) = check_instance_equal( exporting instance_1 = instance_2 = entity_fields = entity_fields ). if equal = abap_true. if -reported is initial. create data -reported like reported. endif. field-symbols: type any, type standard table. assign -reported->* to . assign component to_upper( entity-alias ) of structure to . append to . endif. endloop. else. ""TODO: Throw exception with a reason that ""no buffer exists for the entity"" endif. endloop. else. ""TODO: Throw exception with a reason that ""reported can't be empty"" endif. endif. endloop. else. ""TODO: Throw exception with a reason that ""reported can't be empty"" endif. endmethod. method zif_abap_behv_test_trans_bufr~config_error_response_4_read. data bdef_load type t_bdef_load. field-symbols: type ty_double_transactional_buffer, type standard table, type any, type standard table. cl_abap_behv_load=>get_load( exporting entity = root_name all = abap_true importing head = bdef_load-head entities = bdef_load-entities features = bdef_load-features actions = bdef_load-actions relations = bdef_load-relations associations = bdef_load-associations ). ""Fill reported. if reported is not initial. loop at bdef_load-entities into data(entity). if entity-alias is initial. assign component to_upper( entity-name ) of structure reported to . if is assigned. break-point. endif. else. assign component to_upper( entity-alias ) of structure reported to . if is assigned and is not initial. ""Check if double transactional buffer contains the entity and entity instance. loop at assigning field-symbol(). if line_exists( dbl_transactional_buffer_table[ entity_name = entity-name ] ). "" = dbl_transactional_buffer_table[ entity_name = entity-name ]. assign dbl_transactional_buffer_table[ entity_name = entity-name ] to . assign -entity_instances->* to . data(entity_fields) = get_entity_fields( entity-name ). loop at assigning . data(equal) = check_instance_equal( exporting instance_1 = instance_2 = entity_fields = entity_fields ). if equal = abap_true. if -reported is initial. create data -reported like reported. endif. field-symbols: type any, type standard table. assign -reported->* to . assign component to_upper( entity-alias ) of structure to . append to . endif. endloop. else. ""TODO: Throw exception with a reason that ""no buffer exists for the entity"" endif. endloop. else. ""TODO: Throw exception with a reason that ""reported can't be empty"" endif. endif. endloop. else. ""TODO: Throw exception with a reason that ""reported can't be empty"" endif. endmethod. method find_reported_if_configured. field-symbols: type standard table. field-symbols: type any. assign buffer_4_entity-reported->* to . if buffer_4_entity-reported is not initial. loop at entities into data(entity). data(entity_fields) = get_entity_fields( entity-name ). if entity-alias is initial. assign component to_upper( entity-name ) of structure buffer_4_entity-reported to . if is assigned. break-point. endif. else. assign component to_upper( entity-alias ) of structure to . if is assigned and is not initial. ""Check if double transactional buffer contains the entity and entity instance. loop at assigning field-symbol(). data(equal) = check_instance_equal( exporting instance_1 = instance_to_check instance_2 = entity_fields = entity_fields ). if equal = abap_true. field-symbols type standard table. assign component to_upper( entity-alias ) of structure c_reported to . append to . endif. endloop. endif. endif. endloop. endif. endmethod. endclass. ",12751,True,2951.163493391252,median "*&---------------------------------------------------------------------* *& Local class definition - General for Transaction Processing *&---------------------------------------------------------------------* CLASS lcl_tools DEFINITION. PUBLIC SECTION. CONSTANTS: BEGIN OF cs_condition, true TYPE sy-binpt VALUE 'T', false TYPE sy-binpt VALUE 'F', END OF cs_condition. CLASS-METHODS are_structures_different IMPORTING ir_data1 TYPE REF TO data ir_data2 TYPE REF TO data RETURNING VALUE(rv_result) TYPE sy-binpt RAISING cx_udm_message. CLASS-METHODS get_postal_address IMPORTING iv_node_id TYPE /scmtms/bo_node_id EXPORTING et_postal_address TYPE /bofu/t_addr_postal_addressk RAISING cx_udm_message. CLASS-METHODS get_field_of_structure IMPORTING ir_struct_data TYPE REF TO data iv_field_name TYPE clike RETURNING VALUE(rv_value) TYPE char50 RAISING cx_udm_message. CLASS-METHODS get_errors_log IMPORTING io_umd_message TYPE REF TO cx_udm_message iv_appsys TYPE c EXPORTING es_bapiret TYPE bapiret2. CLASS-METHODS get_local_timestamp IMPORTING iv_date TYPE any DEFAULT sy-datum iv_time TYPE any DEFAULT sy-uzeit RETURNING VALUE(rv_timestamp) TYPE /saptrx/event_exp_datetime. CLASS-METHODS get_pretty_value IMPORTING iv_value TYPE any RETURNING VALUE(rv_pretty) TYPE /saptrx/paramval200. CLASS-METHODS get_system_time_zone RETURNING VALUE(rv_tzone) TYPE timezone RAISING cx_udm_message. CLASS-METHODS get_system_date_time RETURNING VALUE(rv_datetime) TYPE string RAISING cx_udm_message. CLASS-METHODS is_number IMPORTING iv_value TYPE any RETURNING VALUE(rv_result) TYPE abap_bool. CLASS-METHODS is_table IMPORTING iv_value TYPE any RETURNING VALUE(rv_result) TYPE abap_bool. CLASS-METHODS throw_exception IMPORTING iv_textid TYPE sotr_conc DEFAULT '' RAISING cx_udm_message. CLASS-METHODS get_stop_points IMPORTING iv_root_id TYPE /scmtms/tor_id it_stop TYPE /scmtms/t_em_bo_tor_stop EXPORTING et_stop_points TYPE lif_ef_types=>tt_stop_points. CLASS-METHODS is_odd IMPORTING iv_value TYPE n RETURNING VALUE(rv_is_odd) TYPE abap_bool. CLASS-METHODS get_capa_match_key IMPORTING iv_assgn_stop_key TYPE /scmtms/tor_stop_key it_capa_stop TYPE /scmtms/t_em_bo_tor_stop it_capa_root TYPE /scmtms/t_em_bo_tor_root RETURNING VALUE(rv_capa_matchkey) TYPE /saptrx/loc_id_2. CLASS-METHODS check_is_fo_deleted IMPORTING is_root_new TYPE /scmtms/s_em_bo_tor_root is_root_old TYPE /scmtms/s_em_bo_tor_root RETURNING VALUE(rv_result) TYPE lif_ef_types=>tv_condition RAISING cx_udm_message. CLASS-METHODS get_fo_tracked_item_obj IMPORTING is_app_object TYPE trxas_appobj_ctab_wa is_root TYPE /scmtms/s_em_bo_tor_root it_item TYPE /scmtms/t_em_bo_tor_item iv_appsys TYPE /saptrx/applsystem iv_old_data TYPE abap_bool DEFAULT abap_false CHANGING ct_track_id_data TYPE lif_ef_types=>tt_enh_track_id_data RAISING cx_udm_message. CLASS-METHODS get_track_obj_changes IMPORTING is_app_object TYPE trxas_appobj_ctab_wa iv_appsys TYPE /saptrx/applsystem it_track_id_data_new TYPE lif_ef_types=>tt_enh_track_id_data it_track_id_data_old TYPE lif_ef_types=>tt_enh_track_id_data CHANGING ct_track_id_data TYPE lif_ef_types=>tt_track_id_data RAISING cx_udm_message. ENDCLASS. CLASS lcl_tools IMPLEMENTATION. METHOD get_track_obj_changes. CONSTANTS: cs_mtr_truck TYPE string VALUE '31', cs_trxcod_resource TYPE string VALUE 'RESOURCE'. DATA(lt_track_id_data_new) = it_track_id_data_new. DATA(lt_track_id_data_old) = it_track_id_data_old. LOOP AT lt_track_id_data_new ASSIGNING FIELD-SYMBOL() WHERE trxcod = cs_trxcod_resource. READ TABLE lt_track_id_data_old WITH KEY key = -key ASSIGNING FIELD-SYMBOL(). IF sy-subrc = 0. DATA(lt_fields) = CAST cl_abap_structdescr( cl_abap_typedescr=>describe_by_data( p_data = ) )->get_included_view( ). DATA(lv_result) = abap_false. LOOP AT lt_fields ASSIGNING FIELD-SYMBOL(). ASSIGN COMPONENT -name OF STRUCTURE TO FIELD-SYMBOL(). ASSIGN COMPONENT -name OF STRUCTURE TO FIELD-SYMBOL(). IF IS ASSIGNED AND IS ASSIGNED. IF <> . lv_result = abap_true. EXIT. ENDIF. ENDIF. ENDLOOP. IF lv_result = abap_true. APPEND VALUE #( appsys = iv_appsys appobjtype = is_app_object-appobjtype appobjid = is_app_object-appobjid trxcod = -trxcod trxid = -trxid start_date = lcl_tools=>get_system_date_time( ) end_date = lif_ef_constants=>cv_max_end_date timzon = lcl_tools=>get_system_time_zone( ) msrid = space ) TO ct_track_id_data. APPEND VALUE #( appsys = iv_appsys appobjtype = is_app_object-appobjtype appobjid = is_app_object-appobjid trxcod = -trxcod trxid = -trxid start_date = lcl_tools=>get_system_date_time( ) end_date = lif_ef_constants=>cv_max_end_date timzon = lcl_tools=>get_system_time_zone( ) msrid = space action = /scmtms/cl_scem_int_c=>sc_param_action-delete ) TO ct_track_id_data. ENDIF. DELETE lt_track_id_data_old WHERE key = -key. ELSE. APPEND VALUE #( appsys = iv_appsys appobjtype = is_app_object-appobjtype appobjid = is_app_object-appobjid trxcod = -trxcod trxid = -trxid start_date = lcl_tools=>get_system_date_time( ) end_date = lif_ef_constants=>cv_max_end_date timzon = lcl_tools=>get_system_time_zone( ) msrid = space ) TO ct_track_id_data. ENDIF. ENDLOOP. ""Deleted resources LOOP AT lt_track_id_data_old ASSIGNING FIELD-SYMBOL(). APPEND VALUE #( appsys = iv_appsys appobjtype = is_app_object-appobjtype appobjid = is_app_object-appobjid trxcod = -trxcod trxid = -trxid start_date = lcl_tools=>get_system_date_time( ) end_date = lif_ef_constants=>cv_max_end_date timzon = lcl_tools=>get_system_time_zone( ) msrid = space action = /scmtms/cl_scem_int_c=>sc_param_action-delete ) TO ct_track_id_data. ENDLOOP. ENDMETHOD. METHOD get_fo_tracked_item_obj. CONSTANTS: cs_mtr_truck TYPE string VALUE '31', cs_trxcod_resource TYPE string VALUE 'RESOURCE'. LOOP AT it_item ASSIGNING FIELD-SYMBOL(). IF -platenumber IS ASSIGNED AND -res_id IS ASSIGNED AND -node_id IS ASSIGNED AND -item_cat IS ASSIGNED AND -item_cat = /scmtms/if_tor_const=>sc_tor_item_category-av_item. IF is_root-tor_id IS NOT INITIAL AND -res_id IS NOT INITIAL. APPEND VALUE #( key = -node_id appsys = iv_appsys appobjtype = is_app_object-appobjtype appobjid = is_app_object-appobjid trxcod = cs_trxcod_resource trxid = |{ is_root-tor_id }{ -res_id }| start_date = lcl_tools=>get_system_date_time( ) end_date = lif_ef_constants=>cv_max_end_date timzon = lcl_tools=>get_system_time_zone( ) msrid = space ) TO ct_track_id_data. ENDIF. DATA(lv_mtr) = is_root-mtr. SELECT SINGLE motscode FROM /sapapo/trtype INTO lv_mtr WHERE ttype = lv_mtr. SHIFT lv_mtr LEFT DELETING LEADING '0'. IF is_root-tor_id IS NOT INITIAL AND -platenumber IS NOT INITIAL AND lv_mtr = cs_mtr_truck. APPEND VALUE #( key = |{ -node_id }P| appsys = iv_appsys appobjtype = is_app_object-appobjtype appobjid = is_app_object-appobjid trxcod = cs_trxcod_resource trxid = |{ is_root-tor_id }{ -platenumber }| start_date = lcl_tools=>get_system_date_time( ) end_date = lif_ef_constants=>cv_max_end_date timzon = lcl_tools=>get_system_time_zone( ) msrid = space ) TO ct_track_id_data. ENDIF. ENDIF. ENDLOOP. ENDMETHOD. METHOD check_is_fo_deleted. rv_result = lif_ef_constants=>cs_condition-false. DATA(lv_carrier_removed) = xsdbool( is_root_old-tsp IS INITIAL AND is_root_new-tsp IS NOT INITIAL ). DATA(lv_execution_status_changed) = xsdbool( ( is_root_old-execution <> /scmtms/if_tor_status_c=>sc_root-execution-v_in_execution AND is_root_old-execution <> /scmtms/if_tor_status_c=>sc_root-execution-v_ready_for_execution AND is_root_old-execution <> /scmtms/if_tor_status_c=>sc_root-execution-v_executed ) AND ( is_root_new-execution = /scmtms/if_tor_status_c=>sc_root-execution-v_in_execution OR is_root_new-execution = /scmtms/if_tor_status_c=>sc_root-execution-v_ready_for_execution OR is_root_new-execution = /scmtms/if_tor_status_c=>sc_root-execution-v_executed ) ). DATA(lv_lifecycle_status_changed) = xsdbool( ( is_root_old-lifecycle <> /scmtms/if_tor_status_c=>sc_root-lifecycle-v_in_process AND is_root_old-lifecycle <> /scmtms/if_tor_status_c=>sc_root-lifecycle-v_completed ) AND ( is_root_new-lifecycle = /scmtms/if_tor_status_c=>sc_root-lifecycle-v_in_process OR is_root_new-lifecycle = /scmtms/if_tor_status_c=>sc_root-lifecycle-v_completed ) ). IF lv_carrier_removed = abap_true OR lv_execution_status_changed = abap_true OR lv_lifecycle_status_changed = abap_true . rv_result = lif_ef_constants=>cs_condition-true. ENDIF. ENDMETHOD. METHOD get_capa_match_key. DATA lt_stop TYPE /scmtms/t_em_bo_tor_stop. ASSIGN it_capa_stop[ node_id = iv_assgn_stop_key ] TO FIELD-SYMBOL(). IF sy-subrc <> 0. RETURN. ENDIF. ASSIGN it_capa_root[ node_id = -parent_node_id ]-tor_id TO FIELD-SYMBOL(). IF sy-subrc <> 0. RETURN. ENDIF. /scmtms/cl_tor_helper_stop=>get_stop_sequence( EXPORTING it_root_key = VALUE #( ( key = -parent_node_id ) ) iv_before_image = abap_false IMPORTING et_stop_seq_d = DATA(lt_stop_seq) ). ASSIGN lt_stop_seq[ root_key = -parent_node_id ] TO FIELD-SYMBOL(). IF sy-subrc <> 0. RETURN. ENDIF. lt_stop = CORRESPONDING /scmtms/t_em_bo_tor_stop( -stop_seq ). ASSIGN -stop_map[ stop_key = -node_id ]-tabix TO FIELD-SYMBOL(). IF sy-subrc <> 0. RETURN. ENDIF. lcl_tools=>get_stop_points( EXPORTING iv_root_id = it_stop = lt_stop IMPORTING et_stop_points = DATA(lt_stop_points) ). ASSIGN lt_stop_points[ seq_num = log_locid = -log_locid ] TO FIELD-SYMBOL(). IF sy-subrc = 0. rv_capa_matchkey = -stop_id. SHIFT rv_capa_matchkey LEFT DELETING LEADING '0'. ENDIF. ENDMETHOD. METHOD is_odd. DATA lv_reminder TYPE n. lv_reminder = iv_value MOD 2. IF lv_reminder <> 0. rv_is_odd = abap_true. ELSE. rv_is_odd = abap_false. ENDIF. ENDMETHOD. METHOD are_structures_different. DATA: lt_fields TYPE cl_abap_structdescr=>component_table, lv_dummy TYPE char100. FIELD-SYMBOLS: TYPE any, TYPE any, TYPE any, TYPE any. ASSIGN ir_data1->* TO . ASSIGN ir_data2->* TO . IF IS ASSIGNED AND IS ASSIGNED. lt_fields = CAST cl_abap_structdescr( cl_abap_typedescr=>describe_by_data( p_data = ) )->get_components( ). rv_result = cs_condition-false. LOOP AT lt_fields ASSIGNING FIELD-SYMBOL(). ASSIGN COMPONENT -name OF STRUCTURE TO . ASSIGN COMPONENT -name OF STRUCTURE TO . IF IS ASSIGNED AND IS ASSIGNED. IF <> . rv_result = cs_condition-true. EXIT. ENDIF. ELSE. MESSAGE e001(zsst_gtt) WITH -name INTO lv_dummy. lcl_tools=>throw_exception( ). ENDIF. ENDLOOP. ELSE. MESSAGE e002(zsst_gtt) INTO lv_dummy. lcl_tools=>throw_exception( ). ENDIF. ENDMETHOD. METHOD get_field_of_structure. DATA lv_dummy TYPE char100. FIELD-SYMBOLS: TYPE any, TYPE any. ASSIGN ir_struct_data->* TO . IF IS ASSIGNED. ASSIGN COMPONENT iv_field_name OF STRUCTURE TO . IF IS ASSIGNED. rv_value = . ELSE. MESSAGE e001(zst_gtt) WITH iv_field_name INTO lv_dummy. lcl_tools=>throw_exception( ). ENDIF. ELSE. MESSAGE e002(zsst_gtt) INTO lv_dummy. lcl_tools=>throw_exception( ). ENDIF. ENDMETHOD. METHOD get_errors_log. es_bapiret-id = io_umd_message->m_msgid. es_bapiret-number = io_umd_message->m_msgno. es_bapiret-type = io_umd_message->m_msgty. es_bapiret-message_v1 = io_umd_message->m_msgv1. es_bapiret-message_v2 = io_umd_message->m_msgv2. es_bapiret-message_v3 = io_umd_message->m_msgv3. es_bapiret-message_v4 = io_umd_message->m_msgv4. es_bapiret-system = iv_appsys. ENDMETHOD. METHOD get_local_timestamp. rv_timestamp = COND #( WHEN iv_date IS NOT INITIAL THEN |0{ iv_date }{ iv_time }| ). ENDMETHOD. METHOD get_pretty_value. rv_pretty = COND #( WHEN lcl_tools=>is_number( iv_value = iv_value ) = abap_true THEN |{ iv_value }| ELSE iv_value ). ENDMETHOD. METHOD get_system_time_zone. CALL FUNCTION 'GET_SYSTEM_TIMEZONE' IMPORTING timezone = rv_tzone EXCEPTIONS customizing_missing = 1 OTHERS = 2. IF sy-subrc <> 0. MESSAGE e003(zpof_gtt) INTO DATA(lv_dummy). lcl_tools=>throw_exception( ). ENDIF. ENDMETHOD. METHOD get_system_date_time. rv_datetime = |0{ sy-datum }{ sy-uzeit }|. ENDMETHOD. METHOD is_number. DATA(lo_type) = cl_abap_typedescr=>describe_by_data( p_data = iv_value ). rv_result = SWITCH #( lo_type->type_kind WHEN cl_abap_typedescr=>typekind_decfloat OR cl_abap_typedescr=>typekind_decfloat16 OR cl_abap_typedescr=>typekind_decfloat34 OR cl_abap_typedescr=>typekind_float OR cl_abap_typedescr=>typekind_int OR cl_abap_typedescr=>typekind_int1 OR cl_abap_typedescr=>typekind_int2 OR cl_abap_typedescr=>typekind_int8 OR cl_abap_typedescr=>typekind_num OR cl_abap_typedescr=>typekind_numeric OR cl_abap_typedescr=>typekind_packed THEN abap_true ELSE abap_false ). ENDMETHOD. METHOD is_table. DATA(lo_type) = cl_abap_typedescr=>describe_by_data( p_data = iv_value ). rv_result = boolc( lo_type->type_kind = cl_abap_typedescr=>typekind_table ). ENDMETHOD. METHOD throw_exception. RAISE EXCEPTION TYPE cx_udm_message EXPORTING textid = iv_textid m_msgid = sy-msgid m_msgty = sy-msgty m_msgno = sy-msgno m_msgv1 = sy-msgv1 m_msgv2 = sy-msgv2 m_msgv3 = sy-msgv3 m_msgv4 = sy-msgv4. ENDMETHOD. METHOD get_stop_points. DATA: lv_last_loc_uuid TYPE /scmtms/locuuid, lv_ord_no_counter(4) TYPE n. DATA(lv_stops) = lines( it_stop ). LOOP AT it_stop USING KEY parent_seqnum ASSIGNING FIELD-SYMBOL(). ""n_2217177 CASE sy-tabix. WHEN 1. ADD 1 TO lv_ord_no_counter. APPEND VALUE #( stop_id = |{ iv_root_id }{ lv_ord_no_counter }| log_locid = -log_locid seq_num = -seq_num ) TO et_stop_points. WHEN lv_stops. ADD 1 TO lv_ord_no_counter. APPEND VALUE #( stop_id = |{ iv_root_id }{ lv_ord_no_counter }| log_locid = -log_locid seq_num = -seq_num ) TO et_stop_points. WHEN OTHERS. * new intermediate location only if the loc_uuid is different form the last intermediate location IF lv_last_loc_uuid <> -log_loc_uuid AND -log_loc_uuid <> /scmtms/if_common_c=>c_empty_key. ADD 1 TO lv_ord_no_counter. ENDIF. APPEND VALUE #( stop_id = |{ iv_root_id }{ lv_ord_no_counter }| log_locid = -log_locid seq_num = -seq_num ) TO et_stop_points. ENDCASE. lv_last_loc_uuid = -log_loc_uuid. ENDLOOP. ENDMETHOD. METHOD get_postal_address. DATA(lo_tor_srv_mgr) = /bobf/cl_tra_serv_mgr_factory=>get_service_manager( iv_bo_key = /scmtms/if_tor_c=>sc_bo_key ). DATA(lo_loc_srv_mgr) = /bobf/cl_tra_serv_mgr_factory=>get_service_manager( iv_bo_key = /scmtms/if_location_c=>sc_bo_key ). lo_tor_srv_mgr->retrieve_by_association( EXPORTING iv_node_key = /scmtms/if_tor_c=>sc_node-root it_key = VALUE #( ( key = iv_node_id ) ) iv_association = /scmtms/if_tor_c=>sc_association-root-stop IMPORTING et_target_key = DATA(lt_stop_target_key) ). IF lt_stop_target_key IS NOT INITIAL. lo_tor_srv_mgr->retrieve_by_association( EXPORTING iv_node_key = /scmtms/if_tor_c=>sc_node-stop it_key = CORRESPONDING #( lt_stop_target_key ) iv_association = /scmtms/if_tor_c=>sc_association-stop-bo_loc_log IMPORTING et_key_link = DATA(lt_loc_log_key_link) ). IF lt_loc_log_key_link IS NOT INITIAL. lo_loc_srv_mgr->retrieve_by_association( EXPORTING iv_node_key = /scmtms/if_location_c=>sc_node-root it_key = CORRESPONDING #( lt_loc_log_key_link MAPPING key = target_key ) iv_association = /scmtms/if_location_c=>sc_association-root-address IMPORTING et_key_link = DATA(lt_address_key_link) ). IF lt_address_key_link IS NOT INITIAL. TRY. DATA(lr_bo_conf) = /bobf/cl_frw_factory=>get_configuration( iv_bo_key = /scmtms/if_location_c=>sc_bo_key ). CATCH /bobf/cx_frw. MESSAGE e011(zsst_gtt) INTO DATA(lv_dummy). lcl_tools=>throw_exception( ). ENDTRY. DATA(lv_postal_ass_key) = lr_bo_conf->get_content_key_mapping( iv_content_cat = /bobf/if_conf_c=>sc_content_ass iv_do_content_key = /bofu/if_addr_constants=>sc_association-root-postal_address iv_do_root_node_key = /scmtms/if_location_c=>sc_node-/bofu/address ). lo_loc_srv_mgr->retrieve_by_association( EXPORTING iv_node_key = /scmtms/if_location_c=>sc_node-/bofu/address it_key = CORRESPONDING #( lt_address_key_link MAPPING key = target_key ) iv_association = lv_postal_ass_key iv_fill_data = abap_true IMPORTING et_data = et_postal_address ). ENDIF. ENDIF. ENDIF. ENDMETHOD. ENDCLASS. CLASS lcl_ef_performer DEFINITION. PUBLIC SECTION. TYPES: BEGIN OF ts_definition, maintab TYPE /saptrx/strucdatadef, mastertab TYPE /saptrx/strucdatadef, END OF ts_definition. CLASS-METHODS check_relevance IMPORTING is_definition TYPE ts_definition io_bo_factory TYPE REF TO lif_factory iv_appsys TYPE /saptrx/applsystem is_app_obj_types TYPE /saptrx/aotypes it_all_appl_tables TYPE trxas_tabcontainer it_app_type_cntl_tabs TYPE trxas_apptype_tabs OPTIONAL it_app_objects TYPE trxas_appobj_ctabs RETURNING VALUE(rv_result) TYPE sy-binpt RAISING cx_udm_message. CLASS-METHODS get_control_data IMPORTING is_definition TYPE lif_ef_types=>ts_definition io_bo_factory TYPE REF TO lif_factory iv_appsys TYPE /saptrx/applsystem is_app_obj_types TYPE /saptrx/aotypes it_all_appl_tables TYPE trxas_tabcontainer it_app_type_cntl_tabs TYPE trxas_apptype_tabs it_app_objects TYPE trxas_appobj_ctabs CHANGING ct_control_data TYPE lif_ef_types=>tt_control_data RAISING cx_udm_message. CLASS-METHODS get_planned_events IMPORTING is_definition TYPE lif_ef_types=>ts_definition io_factory TYPE REF TO lif_factory iv_appsys TYPE /saptrx/applsystem is_app_obj_types TYPE /saptrx/aotypes it_all_appl_tables TYPE trxas_tabcontainer it_app_type_cntl_tabs TYPE trxas_apptype_tabs it_app_objects TYPE trxas_appobj_ctabs CHANGING ct_expeventdata TYPE lif_ef_types=>tt_expeventdata ct_measrmntdata TYPE lif_ef_types=>tt_measrmntdata ct_infodata TYPE lif_ef_types=>tt_infodata RAISING cx_udm_message. CLASS-METHODS get_track_id_data IMPORTING is_definition TYPE lif_ef_types=>ts_definition io_bo_factory TYPE REF TO lif_factory iv_appsys TYPE /saptrx/applsystem is_app_obj_types TYPE /saptrx/aotypes it_all_appl_tables TYPE trxas_tabcontainer it_app_type_cntl_tabs TYPE trxas_apptype_tabs it_app_objects TYPE trxas_appobj_ctabs EXPORTING et_track_id_data TYPE lif_ef_types=>tt_track_id_data RAISING cx_udm_message. ENDCLASS. CLASS lcl_ef_performer IMPLEMENTATION. METHOD check_relevance. DATA lo_ef_processor TYPE REF TO lif_ef_processor. lo_ef_processor = io_bo_factory->get_ef_processor( is_definition = is_definition io_bo_factory = io_bo_factory iv_appsys = iv_appsys is_app_obj_types = is_app_obj_types it_all_appl_tables = it_all_appl_tables it_app_type_cntl_tabs = it_app_type_cntl_tabs it_app_objects = it_app_objects ). lo_ef_processor->check_app_objects( ). rv_result = lo_ef_processor->check_relevance( io_bo_factory ). ENDMETHOD. METHOD get_control_data. DATA(lo_ef_processor) = io_bo_factory->get_ef_processor( is_definition = is_definition io_bo_factory = io_bo_factory iv_appsys = iv_appsys is_app_obj_types = is_app_obj_types it_all_appl_tables = it_all_appl_tables it_app_type_cntl_tabs = it_app_type_cntl_tabs it_app_objects = it_app_objects ). lo_ef_processor->check_app_objects( ). lo_ef_processor->get_control_data( EXPORTING io_bo_factory = io_bo_factory CHANGING ct_control_data = ct_control_data[] ). ENDMETHOD. METHOD get_planned_events. DATA lo_ef_processor TYPE REF TO lif_ef_processor. lo_ef_processor = io_factory->get_ef_processor( is_definition = is_definition io_bo_factory = io_factory iv_appsys = iv_appsys is_app_obj_types = is_app_obj_types it_all_appl_tables = it_all_appl_tables it_app_type_cntl_tabs = it_app_type_cntl_tabs it_app_objects = it_app_objects ). lo_ef_processor->check_app_objects( ). lo_ef_processor->get_planned_events( EXPORTING io_factory = io_factory CHANGING ct_expeventdata = ct_expeventdata ct_measrmntdata = ct_measrmntdata ct_infodata = ct_infodata ). ENDMETHOD. METHOD get_track_id_data. DATA: lo_ef_processor TYPE REF TO lif_ef_processor. CLEAR: et_track_id_data[]. lo_ef_processor = io_bo_factory->get_ef_processor( is_definition = is_definition io_bo_factory = io_bo_factory iv_appsys = iv_appsys is_app_obj_types = is_app_obj_types it_all_appl_tables = it_all_appl_tables it_app_type_cntl_tabs = it_app_type_cntl_tabs it_app_objects = it_app_objects ). lo_ef_processor->check_app_objects( ). lo_ef_processor->get_track_id_data( EXPORTING io_bo_factory = io_bo_factory IMPORTING et_track_id_data = et_track_id_data ). ENDMETHOD. ENDCLASS. CLASS lcl_ef_processor DEFINITION. PUBLIC SECTION. INTERFACES lif_ef_processor. METHODS constructor IMPORTING io_ef_parameters TYPE REF TO lif_ef_parameters io_bo_reader TYPE REF TO lif_bo_reader io_pe_filler TYPE REF TO lif_pe_filler is_definition TYPE lif_ef_types=>ts_definition. PRIVATE SECTION. DATA: mo_ef_parameters TYPE REF TO lif_ef_parameters, mo_bo_reader TYPE REF TO lif_bo_reader, mo_pe_filler TYPE REF TO lif_pe_filler, ms_definition TYPE lif_ef_types=>ts_definition. METHODS add_struct_to_control_data IMPORTING ir_bo_data TYPE REF TO data iv_appobjid TYPE /saptrx/aoid CHANGING ct_control_data TYPE lif_ef_types=>tt_control_data RAISING cx_udm_message. METHODS add_sys_attr_to_control_data IMPORTING iv_appobjid TYPE /saptrx/aoid CHANGING ct_control_data TYPE lif_ef_types=>tt_control_data RAISING cx_udm_message. ENDCLASS. CLASS lcl_ef_processor IMPLEMENTATION. METHOD add_struct_to_control_data. DATA: lt_fields TYPE cl_abap_structdescr=>component_table, ls_control_data TYPE lif_ef_types=>ts_control_data, lr_mapping TYPE REF TO data, lv_dummy TYPE char100. FIELD-SYMBOLS: TYPE any, TYPE any, TYPE ANY TABLE, TYPE any, TYPE any. ASSIGN ir_bo_data->* TO . IF IS ASSIGNED. "" get fields list of the structure, which provided by reader class lt_fields = CAST cl_abap_structdescr( cl_abap_typedescr=>describe_by_data( p_data = ) )->get_components( ). "" assign mapping table to use it in converting of field names into external format lr_mapping = mo_bo_reader->get_mapping_structure( ). ASSIGN lr_mapping->* TO . IF IS ASSIGNED. "" fill generic parameters ls_control_data-appsys = mo_ef_parameters->get_appsys( ). ls_control_data-appobjtype = mo_ef_parameters->get_app_obj_types( )-aotype. ls_control_data-language = sy-langu. ls_control_data-appobjid = iv_appobjid. "" walk around fields list and copy values one by one LOOP AT lt_fields ASSIGNING FIELD-SYMBOL(). ASSIGN COMPONENT -name OF STRUCTURE TO . ASSIGN COMPONENT -name OF STRUCTURE TO . CLEAR: ls_control_data-paramindex, ls_control_data-value. IF IS ASSIGNED AND IS ASSIGNED. ls_control_data-paramname = . "" simple copy for usual values IF lcl_tools=>is_table( iv_value = ) = abap_false. IF IS NOT INITIAL. ls_control_data-value = lcl_tools=>get_pretty_value( iv_value = ). ENDIF. APPEND ls_control_data TO ct_control_data. "" cycled copy for table values ELSE. ASSIGN TO . LOOP AT ASSIGNING . ADD 1 TO ls_control_data-paramindex. IF IS NOT INITIAL. ls_control_data-value = lcl_tools=>get_pretty_value( iv_value = ). ENDIF. APPEND ls_control_data TO ct_control_data. CLEAR: ls_control_data-value. ENDLOOP. ENDIF. ELSEIF IS NOT ASSIGNED. MESSAGE e010(zsst_gtt) INTO lv_dummy. lcl_tools=>throw_exception( ). ELSE. MESSAGE e010(zsst_gtt) INTO lv_dummy. lcl_tools=>throw_exception( ). ENDIF. ENDLOOP. ELSE. MESSAGE e010(zsst_gtt) INTO lv_dummy. lcl_tools=>throw_exception( ). ENDIF. ELSE. MESSAGE e010(zsst_gtt) INTO lv_dummy. lcl_tools=>throw_exception( ). ENDIF. ENDMETHOD. METHOD add_sys_attr_to_control_data. DATA: ls_control_data TYPE lif_ef_types=>ts_control_data, lv_tzone TYPE timezone. ls_control_data-appsys = mo_ef_parameters->get_appsys( ). ls_control_data-appobjtype = mo_ef_parameters->get_app_obj_types( )-aotype. ls_control_data-language = sy-langu. ls_control_data-appobjid = iv_appobjid. ls_control_data-paramname = lif_ef_constants=>cs_system_fields-actual_bisiness_timezone. ls_control_data-value = lcl_tools=>get_system_time_zone( ). APPEND ls_control_data TO ct_control_data. ls_control_data-paramname = lif_ef_constants=>cs_system_fields-actual_bisiness_datetime. ls_control_data-value = lcl_tools=>get_system_date_time( ). APPEND ls_control_data TO ct_control_data. ls_control_data-paramname = lif_ef_constants=>cs_system_fields-actual_technical_timezone. ls_control_data-value = lcl_tools=>get_system_time_zone( ). APPEND ls_control_data TO ct_control_data. ls_control_data-paramname = lif_ef_constants=>cs_system_fields-actual_technical_datetime. ls_control_data-value = lcl_tools=>get_system_date_time( ). APPEND ls_control_data TO ct_control_data. ENDMETHOD. METHOD constructor. mo_ef_parameters = io_ef_parameters. mo_bo_reader = io_bo_reader. mo_pe_filler = io_pe_filler. ms_definition = is_definition. ENDMETHOD. METHOD lif_ef_processor~check_app_objects. DATA: lr_app_objects TYPE REF TO data, lv_dummy TYPE char100. FIELD-SYMBOLS: TYPE trxas_appobj_ctabs. lr_app_objects = mo_ef_parameters->get_app_objects( ). ASSIGN lr_app_objects->* TO . LOOP AT ASSIGNING FIELD-SYMBOL(). IF -maintabdef <> ms_definition-maintab. MESSAGE e087(/saptrx/asc) WITH -maintabdef mo_ef_parameters->get_app_obj_types( )-controldatafunc lif_ef_constants=>cv_aot mo_ef_parameters->get_appsys( ) INTO lv_dummy. lcl_tools=>throw_exception( iv_textid = lif_ef_constants=>cs_errors-table_determination ). ELSEIF ms_definition-mastertab IS NOT INITIAL AND -mastertabdef <> ms_definition-mastertab. MESSAGE e088(/saptrx/asc) WITH -maintabdef mo_ef_parameters->get_app_obj_types( )-controldatafunc lif_ef_constants=>cv_aot mo_ef_parameters->get_appsys( ) INTO lv_dummy. lcl_tools=>throw_exception( iv_textid = lif_ef_constants=>cs_errors-table_determination ). ENDIF. ENDLOOP. ENDMETHOD. METHOD lif_ef_processor~check_relevance. FIELD-SYMBOLS TYPE trxas_appobj_ctabs. DATA(lr_app_objects) = mo_ef_parameters->get_app_objects( ). ASSIGN lr_app_objects->* TO . rv_result = lif_ef_constants=>cs_condition-false. LOOP AT ASSIGNING FIELD-SYMBOL(). TRY. mo_bo_reader = io_bo_factory->get_bo_reader( is_appl_object = io_ef_parameters = mo_ef_parameters ). CATCH cx_udm_message. CONTINUE. ENDTRY. rv_result = mo_bo_reader->check_relevance( is_app_object = ). IF rv_result = abap_true. EXIT. ENDIF. ENDLOOP. ENDMETHOD. METHOD lif_ef_processor~get_control_data. DATA: lr_app_objects TYPE REF TO data, lr_bo_data TYPE REF TO data. FIELD-SYMBOLS: TYPE trxas_appobj_ctabs, TYPE trxas_appobj_ctab_wa. lr_app_objects = mo_ef_parameters->get_app_objects( ). ASSIGN lr_app_objects->* TO . LOOP AT ASSIGNING WHERE maintabdef = ms_definition-maintab. mo_bo_reader = io_bo_factory->get_bo_reader( is_appl_object = io_ef_parameters = mo_ef_parameters ). lr_bo_data = mo_bo_reader->get_data( EXPORTING is_app_object = ). add_struct_to_control_data( EXPORTING ir_bo_data = lr_bo_data iv_appobjid = -appobjid CHANGING ct_control_data = ct_control_data ). add_sys_attr_to_control_data( EXPORTING iv_appobjid = -appobjid CHANGING ct_control_data = ct_control_data ). ENDLOOP. ENDMETHOD. METHOD lif_ef_processor~get_planned_events. DATA: lt_expeventdata TYPE lif_ef_types=>tt_expeventdata, lt_measrmntdata TYPE lif_ef_types=>tt_measrmntdata, lt_infodata TYPE lif_ef_types=>tt_infodata, lr_app_objects TYPE REF TO data. FIELD-SYMBOLS TYPE trxas_appobj_ctabs. lr_app_objects = mo_ef_parameters->get_app_objects( ). ASSIGN lr_app_objects->* TO . LOOP AT ASSIGNING FIELD-SYMBOL() WHERE maintabdef = ms_definition-maintab. mo_pe_filler = io_factory->get_pe_filler( is_appl_object = io_ef_parameters = mo_ef_parameters ). mo_pe_filler->get_planed_events( EXPORTING is_app_objects = CHANGING ct_expeventdata = lt_expeventdata ct_measrmntdata = lt_measrmntdata ct_infodata = lt_infodata ). ENDLOOP. "" Add all the changes to result tables in the end of the method, "" so that in case of exceptions there will be no inconsistent data in them IF lt_expeventdata[] IS NOT INITIAL. ct_expeventdata[] = VALUE #( BASE ct_expeventdata ( LINES OF lt_expeventdata ) ). ENDIF. IF lt_measrmntdata[] IS NOT INITIAL. ct_measrmntdata[] = VALUE #( BASE ct_measrmntdata ( LINES OF lt_measrmntdata ) ). ENDIF. IF lt_expeventdata[] IS NOT INITIAL. lt_infodata[] = VALUE #( BASE ct_infodata ( LINES OF lt_infodata ) ). ENDIF. ENDMETHOD. METHOD lif_ef_processor~get_track_id_data. DATA: lr_app_objects TYPE REF TO data, lt_track_id_data TYPE lif_ef_types=>tt_track_id_data, lr_bo_data TYPE REF TO data. FIELD-SYMBOLS: TYPE trxas_appobj_ctabs. CLEAR: et_track_id_data[]. lr_app_objects = mo_ef_parameters->get_app_objects( ). ASSIGN lr_app_objects->* TO . LOOP AT ASSIGNING FIELD-SYMBOL() WHERE maintabdef = ms_definition-maintab. mo_bo_reader = io_bo_factory->get_bo_reader( is_appl_object = io_ef_parameters = mo_ef_parameters ). mo_bo_reader->get_track_id_data( EXPORTING is_app_object = IMPORTING et_track_id_data = lt_track_id_data ). et_track_id_data = VALUE #( BASE et_track_id_data ( LINES OF lt_track_id_data ) ). ENDLOOP. ENDMETHOD. ENDCLASS. CLASS lcl_ef_parameters DEFINITION. PUBLIC SECTION. INTERFACES lif_ef_parameters. METHODS constructor IMPORTING iv_appsys TYPE /saptrx/applsystem is_app_obj_types TYPE /saptrx/aotypes it_all_appl_tables TYPE trxas_tabcontainer it_app_type_cntl_tabs TYPE trxas_apptype_tabs OPTIONAL it_app_objects TYPE trxas_appobj_ctabs. PRIVATE SECTION. DATA: mv_appsys TYPE /saptrx/applsystem, ms_app_obj_types TYPE /saptrx/aotypes, mr_all_appl_tables TYPE REF TO data, mr_app_type_cntl_tabs TYPE REF TO data, mr_app_objects TYPE REF TO data. ENDCLASS. CLASS lcl_ef_parameters IMPLEMENTATION. METHOD constructor. mv_appsys = iv_appsys. ms_app_obj_types = is_app_obj_types. mr_all_appl_tables = REF #( it_all_appl_tables ). IF it_app_type_cntl_tabs IS SUPPLIED. mr_app_type_cntl_tabs = REF #( it_app_type_cntl_tabs ). ENDIF. mr_app_objects = REF #( it_app_objects ). ENDMETHOD. METHOD lif_ef_parameters~get_appl_table. TRY. FIELD-SYMBOLS: TYPE trxas_tabcontainer. ASSIGN mr_all_appl_tables->* TO . rr_data = [ tabledef = iv_tabledef ]-tableref. CATCH cx_sy_itab_line_not_found. MESSAGE e008(/saptrx/asc) WITH iv_tabledef ms_app_obj_types-aotype INTO DATA(lv_dummy). lcl_tools=>throw_exception( iv_textid = lif_ef_constants=>cs_errors-stop_processing ). ENDTRY. ENDMETHOD. METHOD lif_ef_parameters~get_app_obj_types. rs_app_obj_types = ms_app_obj_types. ENDMETHOD. METHOD lif_ef_parameters~get_app_objects. rr_data = mr_app_objects. ENDMETHOD. METHOD lif_ef_parameters~get_appsys. rv_appsys = mv_appsys. ENDMETHOD. ENDCLASS. CLASS lcl_factory DEFINITION ABSTRACT. PUBLIC SECTION. INTERFACES lif_factory ABSTRACT METHODS get_bo_reader get_pe_filler. ENDCLASS. CLASS lcl_factory IMPLEMENTATION. METHOD lif_factory~get_ef_parameters. ro_ef_parameters = NEW lcl_ef_parameters( iv_appsys = iv_appsys is_app_obj_types = is_app_obj_types it_all_appl_tables = it_all_appl_tables it_app_type_cntl_tabs = it_app_type_cntl_tabs it_app_objects = it_app_objects ). ENDMETHOD. METHOD lif_factory~get_ef_processor. DATA: lo_ef_parameters TYPE REF TO lif_ef_parameters, lo_bo_reader TYPE REF TO lif_bo_reader, lo_pe_filler TYPE REF TO lif_pe_filler. lo_ef_parameters = lif_factory~get_ef_parameters( iv_appsys = iv_appsys is_app_obj_types = is_app_obj_types it_all_appl_tables = it_all_appl_tables it_app_type_cntl_tabs = it_app_type_cntl_tabs it_app_objects = it_app_objects ). ro_ef_processor = NEW lcl_ef_processor( io_ef_parameters = lo_ef_parameters io_bo_reader = lo_bo_reader io_pe_filler = lo_pe_filler is_definition = is_definition ). ENDMETHOD. ENDCLASS. ",10694,False,1899.2092515279476,median "* Copyright 2019,2020 IBM Corp. 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. class ZCL_IBMC_SERVICE_EXT definition public inheriting from ZCL_IBMC_SERVICE create public . public section. types: ty_instance_id(32) type c . types: ty_servicename(30) type c . types: ty_image_format(3) type c . types TY_IMAGE_CLASS type STRING . types: begin of ts_oauth_prop, url type ts_url, username type string, password type string, apikey type string, end of ts_oauth_prop . constants C_FIELD_NONE type FIELDNAME value '###' ##NO_TEXT. constants C_FORMAT_JPG type TY_IMAGE_FORMAT value 'jpg' ##NO_TEXT. constants C_FORMAT_PNG type TY_IMAGE_FORMAT value 'png' ##NO_TEXT. constants C_FORMAT_GIF type TY_IMAGE_FORMAT value 'gif' ##NO_TEXT. constants C_FORMAT_TIF type TY_IMAGE_FORMAT value 'tif' ##NO_TEXT. constants C_FORMAT_ZIP type TY_IMAGE_FORMAT value 'zip' ##NO_TEXT. constants C_FORMAT_ALL type TY_IMAGE_FORMAT value '*' ##NO_TEXT. constants C_FORMAT_UNKNOWN type TY_IMAGE_FORMAT value '###' ##NO_TEXT. constants C_TOKEN_GENERATION_NEVER type CHAR value 'N' ##NO_TEXT. constants C_TOKEN_GENERATION_ALWAYS type CHAR value 'A' ##NO_TEXT. constants C_TOKEN_GENERATION_AUTO type CHAR value SPACE ##NO_TEXT. constants C_IAM_TOKEN_HOST type STRING value 'iam.cloud.ibm.com' ##NO_TEXT. constants C_IAM_TOKEN_PATH type STRING value '/identity/token' ##NO_TEXT. constants C_ICP4D_TOKEN_PATH type STRING value '/v1/preauth/validateAuth' ##NO_TEXT. data P_INSTANCE_ID type TY_INSTANCE_ID . data P_SERVICENAME type TY_SERVICENAME . ""!

Returns the bearer token, if available.

""! ""! @parameter E_BEARER_TOKEN | Access token. ""! methods GET_BEARER_TOKEN returning value(E_BEARER_TOKEN) type STRING . ""!

Returns the SDK built date.

""! ""! @parameter E_SDK_VERSION_DATE | Built data in format YYYYMMDD. ""! methods GET_SDK_VERSION_DATE returning value(E_SDK_VERSION_DATE) type STRING . ""!

Method for internal use.

""! methods SET_BEARER_TOKEN importing !I_BEARER_TOKEN type STRING . ""!

Retrieves a value of a configuration parameter

from table ZIBMC_CONFIG. ""! ""! @parameter I_DEFAULT | Default value, if configuration parameter is not found. ""! @parameter I_PARAM | Configuration parameter name. ""! methods GET_CONFIG_VALUE importing !I_DEFAULT type ZIBMC_CONFIG-VALUE optional !I_PARAM type ZIBMC_CONFIG-PARAM returning value(E_VALUE) type ZIBMC_CONFIG-VALUE raising ZCX_IBMC_SERVICE_EXCEPTION . ""!

Factory method to instantiate a service specific wrapper class.

""! ""! @parameter I_INSTANCE_ID | ""! Value of field INSTANCE_UID in table ZIBMC_CONFIG. ""! Service credentials are read from table ZIBMC_CONFIG with key SERVICE = Name of service wrapper class without prefix ZCL_IBMC_ and INSTANCE_UID. ""! @parameter I_URL | URL of the service. ""! @parameter I_HOST | Host of the service. I_URL and I_HOST can be used synonymously. ""! @parameter I_USERNAME | User password to authenticate on service. ""! @parameter I_PASSWORD | User password to authenticate on service. ""! @parameter I_PROXY_HOST | Proxy server, not applicable on SAP Cloud Platform. ""! @parameter I_PROXY_PORT | Proxy server port, not applicable on SAP Cloud Platform. ""! @parameter I_APIKEY | API key password to authenticate on service. ""! @parameter I_AUTH_METHOD | Authentication method. Possible values are ""IAM"", ""ICP4D"", ""basicAuth"", ""NONE"". ""! @parameter I_OAUTH_PROP | Credentials to generate token for OAuth authentication. ""! @parameter I_TOKEN_GENERATION | Method for access token refresh:
""! C_TOKEN_GENERATION_NEVER - Access token is not refreshed. ""! C_TOKEN_GENERATION_ALWAYS - Access to token is refreshed for each service call. ""! C_TOKEN_GENERATION_AUTO - Access to token is refreshed just before it expires. ""! @parameter I_REQUEST_HEADERS | List of headers sent with every request, format 'Header1=Value1;Header2=Value2'. ""! @parameter I_VERSION | Value of query parameter VERSION. ""! class-methods GET_INSTANCE importing !I_INSTANCE_ID type TY_INSTANCE_ID optional !I_URL type STRING optional !I_HOST type STRING optional !I_USERNAME type STRING optional !I_PASSWORD type STRING optional !I_PROXY_HOST type STRING optional !I_PROXY_PORT type STRING optional !I_APIKEY type STRING optional !I_AUTH_METHOD type STRING default C_DEFAULT !I_OAUTH_PROP type TS_OAUTH_PROP optional !I_ACCESS_TOKEN type TS_ACCESS_TOKEN optional !I_TOKEN_GENERATION type CHAR default C_TOKEN_GENERATION_AUTO !I_REQUEST_HEADERS type STRING optional !I_VERSION type STRING optional exporting value(EO_INSTANCE) type ANY . ""!

Compresses multiple images from an internal table

to a one or more xstrings in ZIP format. ""! ""! @parameter IT_EXAMPLES | Internal table of images. ""! @parameter IV_FIELD_CLASS | ""! Field in IT_EXAMPLES that contains the file class. ""! All records in IT_EXAMPLES with same class will be compress into one ZIP xstring. ""! @parameter IV_FIELD_FILENAME | Field in IT_EXAMPLES that contains the filename for the image. ""! @parameter IV_FIELD_IMAGE | Field in IT_EXAMPLES that contains the image. ""! @parameter IV_IMAGE_FORMAT | Format of the image. Possible values are ""! C_FORMAT_JPG, C_FORMAT_PNG, C_FORMAT_GIF, C_FORMAT_TIF, C_FORMAT_ALL. ""! @parameter IV_IMAGE_NAME | Name of the image. ""! @parameter ET_ZIPDATA | Internal table containing a compressed ZIP xstring for each image class. ""! @raising ZCX_IBMC_SERVICE_EXCEPTION | Exception being raised in case of an error. ""! class-methods GET_ZIPDATA importing !IT_EXAMPLES type ANY TABLE !IV_FIELD_CLASS type FIELDNAME default C_FIELD_NONE !IV_FIELD_FILENAME type FIELDNAME optional !IV_FIELD_IMAGE type FIELDNAME optional !IV_IMAGE_FORMAT type TY_IMAGE_FORMAT optional !IV_IMAGE_NAME type STRING optional exporting !ET_ZIPDATA type TT_MAP_FILE raising ZCX_IBMC_SERVICE_EXCEPTION . methods GET_ACCESS_TOKEN redefinition . methods GET_REQUEST_PROP redefinition . protected section. private section. data P_OAUTH_PROP type TS_OAUTH_PROP . data P_TOKEN_GENERATION type CHAR . ""!

Method for internal use.

""! class-methods ADD_CONFIG_PROP importing !I_SERVICENAME type TY_SERVICENAME !I_INSTANCE_ID type TY_INSTANCE_ID optional changing !C_REQUEST_PROP type ANY . ""!

Method for internal use.

""! class-methods ADD_IMAGE_TO_ZIP importing !IS_TABLELINE type ANY !IO_ZIP type ref to CL_ABAP_ZIP !IV_BASE64 type BOOLEAN !IV_FILENAME type STRING optional !IV_FIELD_IMAGE type FIELDNAME !IV_FIELD_FILENAME type FIELDNAME optional raising ZCX_IBMC_SERVICE_EXCEPTION . ""!

Method for internal use.

""! class-methods GET_FIELD_DATA importing !IS_TABLELINE type ANY !IV_FIELD_CLASS type FIELDNAME optional !IV_FIELD_FILENAME type FIELDNAME optional !IV_FIELD_IMAGE type FIELDNAME optional exporting !EV_FIELD_CLASS type FIELDNAME !EV_FIELD_FILENAME type FIELDNAME !EV_FIELD_IMAGE type FIELDNAME !EV_FIELD_IMAGE_BASE64 type FIELDNAME raising ZCX_IBMC_SERVICE_EXCEPTION . ENDCLASS. CLASS ZCL_IBMC_SERVICE_EXT IMPLEMENTATION. method add_config_prop. data: lt_compname type tt_string, lv_type type char, ls_config type zibmc_config, lt_config type standard table of zibmc_config, lt_ref type standard table of ref to data, lr_data type ref to data, lv_index type i value 0, ls_url type ts_url value is initial. field-symbols: type any, type any, type string, type any. "" read config table if not i_instance_id is initial. select * from zibmc_config where service = @i_servicename and instance_uid = @i_instance_id into table @lt_config. else. select * from zibmc_config where service = @i_servicename and instance_uid = @space into table @lt_config. endif. "" quit, if no relevant entry in config table exists check sy-subrc = 0. "" change config parameter ""URL"" to ""HOST"" ls_config-param = 'HOST'. modify lt_config from ls_config transporting param where param = 'URL'. "" perform breadth-first search on c_request_prop to allow setting values on deeper levels, "" e.g. HOST -> c_request_prop-url-host lr_data = ref #( c_request_prop ). append lr_data to lt_ref. do. lv_index = lv_index + 1. read table lt_ref into lr_data index lv_index. if sy-subrc <> 0. exit. endif. assign lr_data->* to . get_components( exporting i_structure = importing e_components = lt_compname ). loop at lt_compname assigning . assign component of structure to . check sy-subrc = 0. get_field_type( exporting i_field = importing e_technical_type = lv_type ). if lv_type eq zif_ibmc_service_arch~c_datatype-struct or lv_type eq zif_ibmc_service_arch~c_datatype-struct_deep. lr_data = ref #( ). append lr_data to lt_ref. else. if is initial. read table lt_config into ls_config with key param = ##WARN_OK. if sy-subrc = 0. condense ls_config-value. = ls_config-value. endif. endif. endif. endloop. enddo. endmethod. method add_image_to_zip. data: lx_image type xstring, lv_filename type string. field-symbols: type any, type any. if not iv_filename is initial. lv_filename = iv_filename. else. assign component iv_field_filename of structure is_tableline to . lv_filename = conv #( ). "" type conversion if lv_filename is initial. raise_exception( i_msgno = '056' ). endif. endif. assign component iv_field_image of structure is_tableline to . if iv_base64 eq c_boolean_true. lx_image = base64_decode( i_base64 = ). io_zip->add( name = lv_filename content = lx_image ). else. io_zip->add( name = lv_filename content = ). endif. endmethod. method get_access_token. data: lo_response type to_rest_response, lv_grand_urlencoded type string, lv_key_urlencoded type string, lv_json type string, lv_seconds type i, lv_timestamp type timestamp, ls_token type zibmc_token value is initial, ls_timestamp type timestamp, begin of ls_token_classic, token type string, end of ls_token_classic. if not i_request_prop-access_token-access_token is initial. ls_token-access_token = p_request_prop_default-access_token-access_token. ls_token-token_type = p_request_prop_default-access_token-token_type. ls_token-expires_ts = p_request_prop_default-access_token-expires_ts. else. select single * from zibmc_token where service = @p_servicename and instance_uid = @p_instance_id into @ls_token. endif. "" check if access token has expired get time stamp field ls_timestamp. if ls_timestamp >= ls_token-expires_ts. clear ls_token. endif. "" (re)new token unless it is still valid if ls_token-access_token is initial and p_token_generation ne c_token_generation_never. data: ls_token_request_prop type ts_request_prop. ls_token_request_prop-url = p_oauth_prop-url. "" set to tribool_false to distinguish between false and inital ls_token_request_prop-auth_basic = c_tribool_false. ls_token_request_prop-auth_oauth = c_tribool_false. ls_token_request_prop-auth_apikey = c_tribool_false. ls_token_request_prop-header_accept = zcl_ibmc_service=>zif_ibmc_service_arch~c_mediatype-appl_json. if i_request_prop-auth_name eq 'IAM' ##NO_TEXT. "" write urlencoded parameters if not ls_token-refresh_token is initial. lv_grand_urlencoded = escape( val = 'refresh_token' format = cl_abap_format=>e_uri_full ) ##NO_TEXT. lv_key_urlencoded = escape( val = ls_token-refresh_token format = cl_abap_format=>e_uri_full ). ls_token_request_prop-body = `grant_type=` && lv_grand_urlencoded && `&refresh_token=` && lv_key_urlencoded ##NO_TEXT. else. if not p_oauth_prop-apikey is initial. lv_grand_urlencoded = escape( val = 'urn:ibm:params:oauth:grant-type:apikey' format = cl_abap_format=>e_uri_full ) ##NO_TEXT. lv_key_urlencoded = escape( val = p_oauth_prop-apikey format = cl_abap_format=>e_uri_full ). ls_token_request_prop-body = `grant_type=` && lv_grand_urlencoded && `&apikey=` && lv_key_urlencoded ##NO_TEXT. elseif not p_oauth_prop-password is initial. lv_grand_urlencoded = escape( val = 'urn:ibm:params:oauth:grant-type:password' format = cl_abap_format=>e_uri_full ) ##NO_TEXT. lv_key_urlencoded = escape( val = p_oauth_prop-password format = cl_abap_format=>e_uri_full ). ls_token_request_prop-body = `grant_type=` && lv_grand_urlencoded && `&username=` && p_oauth_prop-username && `&password=` && p_oauth_prop-password ##NO_TEXT. else. ls_token_request_prop-username = p_oauth_prop-username. ls_token_request_prop-password = p_oauth_prop-password. ls_token_request_prop-apikey = p_oauth_prop-apikey. endif. endif. ls_token_request_prop-header_content_type = zcl_ibmc_service=>zif_ibmc_service_arch~c_mediatype-appl_www_form_urlencoded. "" execute HTTP POST request lo_response = http_post( i_request_prop = ls_token_request_prop ). "" receive response json lv_json = get_response_string( lo_response ). "" call json parser (ignore properties that do not exist in abap structure) parse_json( exporting i_json = lv_json changing c_abap = ls_token ). else. if i_request_prop-auth_body eq c_boolean_true. "" POST request having username/password in body (e.g. for Db2 Warehouse) ls_token_request_prop-body = `{ ""userid"": ""` && p_oauth_prop-username && `"", ""password"": ""` && p_oauth_prop-password && `"" }` ##NO_TEXT. ls_token_request_prop-header_content_type = zcl_ibmc_service=>zif_ibmc_service_arch~c_mediatype-appl_json. "" execute HTTP POST request lo_response = http_post( i_request_prop = ls_token_request_prop ). else. ls_token_request_prop-username = p_oauth_prop-username. ls_token_request_prop-password = p_oauth_prop-password. ls_token_request_prop-apikey = p_oauth_prop-apikey. ls_token_request_prop-url = p_oauth_prop-url. ls_token_request_prop-auth_basic = c_boolean_true. "" execute HTTP GET request lo_response = http_get( i_request_prop = ls_token_request_prop ). "" receive response json lv_json = get_response_string( lo_response ). if i_request_prop-auth_name eq 'ICP4D' ##NO_TEXT. "" parse expected response: "" { ""username"": ""joe"", ""role"": ""User"", ""uid"": ""1003"", "" ""accessToken"": ""eyJhbGc…1AjT_w"", "" ""messageCode"": ""success"", ""message"": ""success"" } data: begin of ls_access_token_icp4d, accesstoken type string, end of ls_access_token_icp4d. parse_json( exporting i_json = lv_json changing c_abap = ls_access_token_icp4d ). ls_token-access_token = ls_access_token_icp4d-accesstoken. ls_token-expires_in = 12 * 3600. else. "" call json parser parse_json( exporting i_json = lv_json changing c_abap = ls_token_classic ). ls_token-access_token = ls_token_classic-token. ls_token-expires_in = 3600. endif. ls_token-token_type = 'Bearer' ##NO_TEXT. endif. endif. "" calculate expiration time if ls_token-expires_in > 0. get time stamp field lv_timestamp. lv_seconds = ls_token-expires_in - 300. "" subtract 5 minutes to be save ls_token-expires_ts = cl_abap_tstmp=>add( tstmp = lv_timestamp secs = lv_seconds ). endif. ls_token-service = p_servicename. ls_token-instance_uid = p_instance_id. if p_token_generation eq c_token_generation_auto. modify zibmc_token from @ls_token. commit work. endif. endif. "" fill returning parameter move-corresponding ls_token to e_access_token ##ENH_OK. endmethod. method get_bearer_token. data: ls_access_token type ts_access_token. try. ls_access_token = get_access_token( ). catch zcx_ibmc_service_exception. clear ls_access_token. endtry. if ls_access_token-token_type eq 'Bearer'. e_bearer_token = ls_access_token-access_token. else. clear e_bearer_token. endif. endmethod. method get_config_value. select single value from zibmc_config where param = @i_param and service = @p_servicename and instance_uid = @p_instance_id into @e_value. if sy-subrc <> 0. select single value from zibmc_config where param = @i_param and service = @p_servicename and instance_uid = @space into @e_value. if sy-subrc <> 0. if i_default is supplied. e_value = i_default. else. raise exception type zcx_ibmc_service_exception. endif. endif. endif. endmethod. method get_field_data. data: begin of ls_comp, name type string, type type char, length type i, end of ls_comp, lt_comp like standard table of ls_comp, lt_compname type tt_string, lv_msg1 type string. field-symbols: type any. get_components( exporting i_structure = is_tableline importing e_components = lt_compname ). loop at lt_compname into ls_comp-name. assign component ls_comp-name of structure is_tableline to . get_field_type( exporting i_field = importing e_technical_type = ls_comp-type e_length = ls_comp-length ). append ls_comp to lt_comp. endloop. clear: ev_field_class, ev_field_filename, ev_field_image, ev_field_image_base64. if ev_field_class is requested. if not iv_field_class is initial. "" field that contains class name is explicit specified ev_field_class = iv_field_class. else. "" field CLASS read table lt_comp with key name = 'CLASS' into ls_comp. if sy-subrc = 0 and ( ls_comp-type eq 'C' or ls_comp-type eq 'g' or ls_comp-type eq 'N' ). "" character type ev_field_class = ls_comp-name. else. "" first field of character type and length 6 or more contains class name loop at lt_comp into ls_comp where ( type eq 'C' or type eq 'N' ) and length >= 6 and name ne 'FILENAME' and name ne 'IMAGE' and name ne 'IMAGE_BASE64'. ev_field_class = ls_comp-name. exit. endloop. endif. if ev_field_class is initial. "" first field of type string contains class name loop at lt_comp into ls_comp where type eq 'g' and name ne 'FILENAME' and name ne 'IMAGE' and name ne 'IMAGE_BASE64'. ev_field_class = ls_comp-name. exit. endloop. endif. endif. endif. if ev_field_filename is requested. if not iv_field_filename is initial. "" field that contains image name is explicit specified ev_field_filename = iv_field_filename. else. read table lt_comp with key name = 'FILENAME' into ls_comp. if sy-subrc = 0 and ( ls_comp-type eq 'C' or ls_comp-type eq 'g' or ls_comp-type eq 'N' ). ev_field_filename = ls_comp-name. else. "" first field of character type and length 12 or more contains image name loop at lt_comp into ls_comp where ( type eq 'C' or type eq 'N' ) and length >= 12 and name ne ev_field_class and name ne 'IMAGE' and name ne 'IMAGE_BASE64'. ev_field_filename = ls_comp-name. exit. endloop. endif. if ev_field_filename is initial. "" first field of type string contains image name loop at lt_comp into ls_comp where type eq 'g' and name ne ev_field_class. ev_field_filename = ls_comp-name. exit. endloop. endif. endif. endif. if ev_field_image is requested. if not iv_field_image is initial. "" field that contains image data is explicit specified "" check image field data type to determine encoding read table lt_comp into ls_comp with key name = iv_field_image. if sy-subrc <> 0. lv_msg1 = conv #( ev_field_image ). "" type conversion raise_exception( i_msgno = '054' "" Field &1 is missing or has incompatible type. i_msgv1 = lv_msg1 ). endif. if ls_comp-type eq 'g'. "" image is base64 encoded ev_field_image_base64 = iv_field_image. else. "" image in binary data ev_field_image = iv_field_image. endif. else. read table lt_comp with key name = 'IMAGE' into ls_comp. if sy-subrc <> 0. read table lt_comp with key name = 'IMAGE_BASE64' into ls_comp. endif. if sy-subrc = 0 and ( ls_comp-type eq 'y' or ls_comp-type eq 'g' ). "" xstring or string if ls_comp-type eq 'g'. ev_field_image_base64 = ls_comp-name. else. ev_field_image = ls_comp-name. endif. else. "" first field of type xstring contains image data (binary) loop at lt_comp into ls_comp where type eq 'y' and name ne ev_field_class and name ne ev_field_filename. ev_field_image = ls_comp-name. exit. endloop. endif. if ev_field_image is initial. "" first field of type string contains image data (base64 encoded) loop at lt_comp into ls_comp where type eq 'g' and name ne ev_field_class and name ne ev_field_filename. ev_field_image_base64 = ls_comp-name. exit. endloop. endif. endif. endif. endmethod. method get_instance. data: lv_classname type string, ls_request_prop type ts_request_prop, lo_instance type ref to zcl_ibmc_service_ext, lt_headerstr type tt_string, lv_headerstr type string, ls_header type ts_header. "" instantiate object of type of exporting parameter get_field_type( exporting i_field = eo_instance importing e_relative_type = lv_classname ). create object eo_instance type (lv_classname) exporting i_url = i_url i_host = i_host i_proxy_host = i_proxy_host i_proxy_port = i_proxy_port i_username = i_username i_password = i_password i_apikey = i_apikey. lo_instance ?= eo_instance. "" Set service name (= class name without namespace and prefix 'CL_') if lv_classname cp 'Z*'. find first occurrence of regex 'ZCL_[^_]*_([^\\/]*)$' in lv_classname submatches lo_instance->p_servicename. else. find first occurrence of regex 'CL_([^\\/]*)$' in lv_classname submatches lo_instance->p_servicename. endif. if lo_instance->p_servicename is initial. find first occurrence of regex '([^\\/]*)$' in lv_classname submatches lo_instance->p_servicename. if lo_instance->p_servicename is initial. lo_instance->p_servicename = lv_classname. endif. endif. "" Set default request headers split i_request_headers at ';' into table lt_headerstr. if sy-subrc = 0. loop at lt_headerstr into lv_headerstr. split lv_headerstr at '=' into ls_header-name ls_header-value. if sy-subrc = 0. append ls_header to lo_instance->p_request_prop_default-headers. endif. endloop. endif. "" Set instance ID if not i_instance_id is initial. lo_instance->p_instance_id = i_instance_id. else. lo_instance->p_instance_id = get_progname( ). endif. "" Merge properties from config table for this service and instance add_config_prop( exporting i_servicename = lo_instance->p_servicename i_instance_id = lo_instance->p_instance_id changing c_request_prop = lo_instance->p_request_prop_default ). normalize_url( changing c_url = lo_instance->p_request_prop_default-url ). "" Merge properties from config table for this service type add_config_prop( exporting i_servicename = lo_instance->p_servicename changing c_request_prop = lo_instance->p_request_prop_default ). normalize_url( changing c_url = lo_instance->p_request_prop_default-url ). "" Get service default properties ls_request_prop = lo_instance->get_request_prop( i_auth_method = i_auth_method ). merge_structure( exporting i_alternative = ls_request_prop changing c_base = lo_instance->p_request_prop_default ). "" Ensure that OAuth is set in case IAM is used. if lo_instance->p_request_prop_default-auth_name eq 'IAM'. lo_instance->p_request_prop_default-auth_oauth = c_boolean_true. endif. "" Set OAuth properties lo_instance->p_oauth_prop = i_oauth_prop. normalize_url( changing c_url = lo_instance->p_oauth_prop-url ). if ls_request_prop-auth_name eq 'IAM' or ls_request_prop-auth_name eq 'ICP4D' ##NO_TEXT. if lo_instance->p_oauth_prop-url-host is initial. lo_instance->p_oauth_prop-url-protocol = 'https' ##NO_TEXT. if ls_request_prop-auth_name eq 'IAM'. lo_instance->p_oauth_prop-url-host = c_iam_token_host. else. lo_instance->p_oauth_prop-url-host = lo_instance->p_request_prop_default-url-host. endif. endif. if lo_instance->p_oauth_prop-url-path_base is initial and lo_instance->p_oauth_prop-url-path is initial. "" Set path_base (not path), otherwise the default service path_base would be added, which is not correct if ls_request_prop-auth_name eq 'IAM'. lo_instance->p_oauth_prop-url-path_base = c_iam_token_path. else. lo_instance->p_oauth_prop-url-path_base = c_icp4d_token_path. endif. endif. if lo_instance->p_oauth_prop-password is initial and lo_instance->p_oauth_prop-apikey is initial. lo_instance->p_oauth_prop-username = lo_instance->p_request_prop_default-username. lo_instance->p_oauth_prop-password = lo_instance->p_request_prop_default-password. lo_instance->p_oauth_prop-apikey = lo_instance->p_request_prop_default-apikey. endif. endif. if not i_access_token-access_token is initial. lo_instance->p_token_generation = c_token_generation_never. lo_instance->set_access_token( i_access_token = i_access_token ). else. lo_instance->p_token_generation = i_token_generation. endif. lo_instance->p_version = i_version. endmethod. method get_request_prop. data: lv_auth_method type string. e_request_prop = super->get_request_prop( i_auth_method = i_auth_method ). lv_auth_method = i_auth_method. if lv_auth_method eq c_default. lv_auth_method = 'IAM'. endif. if lv_auth_method is initial. e_request_prop-auth_basic = c_boolean_false. e_request_prop-auth_oauth = c_boolean_false. e_request_prop-auth_apikey = c_boolean_false. elseif lv_auth_method eq 'IAM'. e_request_prop-auth_name = 'IAM'. e_request_prop-auth_type = 'apiKey'. e_request_prop-auth_headername = 'Authorization'. e_request_prop-auth_header = c_boolean_true. elseif lv_auth_method eq 'ICP4D'. e_request_prop-auth_name = 'ICP4D'. e_request_prop-auth_type = 'apiKey'. e_request_prop-auth_headername = 'Authorization'. e_request_prop-auth_header = c_boolean_true. elseif lv_auth_method eq 'basicAuth'. e_request_prop-auth_name = 'basicAuth'. e_request_prop-auth_type = 'http'. e_request_prop-auth_basic = c_boolean_true. endif. endmethod. method get_sdk_version_date. e_sdk_version_date = ''. endmethod. method get_zipdata. constants: c_class_all type string value '#ALL#'. data: lv_field_class type fieldname, lv_field_filename type fieldname, lv_field_image type fieldname, lv_field_image_base64 type fieldname, lv_field_image_act type fieldname, lv_base64 type boolean, lr_data type ref to data, ls_zipdata type ts_map_file, lv_image_count type i, lv_class type ty_image_class, lt_classes type standard table of ty_image_class, lv_filename type string, lv_filename_suffix(4) type n value 0, lo_zip type ref to cl_abap_zip value is initial, lv_image_name type string, lv_image_format type ty_image_format. field-symbols: type any, type any, type any, type any. create data lr_data like line of it_examples. assign lr_data->* to . "" determine field with filename if iv_field_filename is initial or iv_field_filename eq c_field_none. if not iv_image_name is initial. lv_field_filename = c_field_none. lv_image_name = iv_image_name. endif. else. lv_field_filename = iv_field_filename. clear: lv_image_name, lv_image_format. endif. "" get field names get_field_data( exporting is_tableline = iv_field_class = iv_field_class iv_field_filename = lv_field_filename iv_field_image = iv_field_image importing ev_field_class = lv_field_class ev_field_filename = lv_field_filename ev_field_image = lv_field_image ev_field_image_base64 = lv_field_image_base64 ). "" reset field name for filename if explicitly set to 'none'. if lv_field_filename eq c_field_none. clear lv_field_filename. endif. if iv_field_class eq c_field_none. "" do not separate into different classes append c_class_all to lt_classes. else. "" compile list of different classes loop at it_examples assigning . assign component lv_field_class of structure to . append to lt_classes. endloop. sort lt_classes. delete adjacent duplicates from lt_classes. endif. "" determine default image format if iv_image_format is initial or iv_image_format eq c_format_all or iv_image_format eq c_format_unknown. lv_image_format = c_format_jpg. else. lv_image_format = iv_image_format. endif. translate lv_image_format to lower case. "" generate a zip data xstring per class loop at lt_classes into lv_class. check not lv_class is initial. create object lo_zip. lv_image_count = 0. loop at it_examples assigning . if lv_class ne c_class_all. assign component lv_field_class of structure to . check eq lv_class. endif. "" determine filename clear lv_filename. if not lv_field_filename is initial. assign component lv_field_filename of structure to . if sy-subrc = 0. "" remove path from filename find regex '([^/\\\\]*)$' in submatches lv_filename. endif. endif. "" if valid filename was not found, use the default if lv_filename np '*+.+++'. if lv_filename is initial. if lv_image_name is initial. lv_filename = lv_class && lv_filename_suffix && `.` && lv_image_format. else. lv_filename = lv_image_name && lv_filename_suffix && `.` && lv_image_format. endif. else. lv_filename = lv_filename && `.` && lv_image_format. endif. lv_filename_suffix = lv_filename_suffix + 1. endif. "" determine image encoding if lv_field_image is initial. lv_field_image_act = lv_field_image_base64. lv_base64 = c_boolean_true. elseif lv_field_image_base64 is initial. lv_field_image_act = lv_field_image. lv_base64 = c_boolean_false. else. assign component lv_field_image of structure to . if not is initial. lv_field_image_act = lv_field_image. lv_base64 = c_boolean_false. else. lv_field_image_act = lv_field_image_base64. lv_base64 = c_boolean_true. endif. endif. "" add image to zip data add_image_to_zip( exporting io_zip = lo_zip is_tableline = iv_filename = lv_filename iv_field_image = lv_field_image_act iv_base64 = lv_base64 ). lv_image_count = lv_image_count + 1. endloop. if lv_image_count > 0. ls_zipdata-key = lv_class. ls_zipdata-data = lo_zip->save( ). append ls_zipdata to et_zipdata. endif. endloop. endmethod. method set_bearer_token. data: ls_access_token type ts_access_token. ls_access_token-token_type = 'Bearer' ##NO_TEXT. ls_access_token-access_token = i_bearer_token. try. set_access_token( i_access_token = ls_access_token ). catch zcx_ibmc_service_exception ##NO_HANDLER. endtry. endmethod. ENDCLASS. ",8620,False,1629.5297748526907,median "-- Generated by Snowball 2.2.0 - https://snowballstem.org/ package body Stemmer.Portuguese is pragma Style_Checks (""-mr""); pragma Warnings (Off, ""*variable*is never read and never assigned*""); pragma Warnings (Off, ""*mode could be*instead of*""); pragma Warnings (Off, ""*formal parameter.*is not modified*""); pragma Warnings (Off, ""*this line is too long*""); pragma Warnings (Off, ""*is not referenced*""); procedure R_Residual_form (Z : in out Context_Type; Result : out Boolean); procedure R_Residual_suffix (Z : in out Context_Type; Result : out Boolean); procedure R_Verb_suffix (Z : in out Context_Type; Result : out Boolean); procedure R_Standard_suffix (Z : in out Context_Type; Result : out Boolean); procedure R_R2 (Z : in out Context_Type; Result : out Boolean); procedure R_R1 (Z : in out Context_Type; Result : out Boolean); procedure R_RV (Z : in out Context_Type; Result : out Boolean); procedure R_Mark_regions (Z : in out Context_Type; Result : out Boolean); procedure R_Postlude (Z : in out Context_Type; Result : out Boolean); procedure R_Prelude (Z : in out Context_Type; Result : out Boolean); G_V : constant Grouping_Array (0 .. 159) := ( True, False, False, False, True, False, False, False, True, False, False, False, False, False, True, False, False, False, False, False, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, True, True, False, False, False, False, False, False, True, True, False, False, True, False, False, False, False, False, True, True, False, False, False, False, False, True, False, False, False, False, False, False ); Among_String : constant String := """" & ""ã"" & ""õ"" & """" & ""a~"" & ""o~"" & ""ic"" & ""ad"" & ""os"" & ""iv"" & ""ante"" & ""avel"" & ""ível"" & ""ic"" & ""abil"" & ""iv"" & ""ica"" & ""ância"" & ""ência"" & ""logia"" & ""ira"" & ""adora"" & ""osa"" & ""ista"" & ""iva"" & ""eza"" & ""idade"" & ""ante"" & ""mente"" & ""amente"" & ""ável"" & ""ível"" & ""ico"" & ""ismo"" & ""oso"" & ""amento"" & ""imento"" & ""ivo"" & ""aça~o"" & ""uça~o"" & ""ador"" & ""icas"" & ""ências"" & ""logias"" & ""iras"" & ""adoras"" & ""osas"" & ""istas"" & ""ivas"" & ""ezas"" & ""idades"" & ""adores"" & ""antes"" & ""aço~es"" & ""uço~es"" & ""icos"" & ""ismos"" & ""osos"" & ""amentos"" & ""imentos"" & ""ivos"" & ""ada"" & ""ida"" & ""ia"" & ""aria"" & ""eria"" & ""iria"" & ""ara"" & ""era"" & ""ira"" & ""ava"" & ""asse"" & ""esse"" & ""isse"" & ""aste"" & ""este"" & ""iste"" & ""ei"" & ""arei"" & ""erei"" & ""irei"" & ""am"" & ""iam"" & ""ariam"" & ""eriam"" & ""iriam"" & ""aram"" & ""eram"" & ""iram"" & ""avam"" & ""em"" & ""arem"" & ""erem"" & ""irem"" & ""assem"" & ""essem"" & ""issem"" & ""ado"" & ""ido"" & ""ando"" & ""endo"" & ""indo"" & ""ara~o"" & ""era~o"" & ""ira~o"" & ""ar"" & ""er"" & ""ir"" & ""as"" & ""adas"" & ""idas"" & ""ias"" & ""arias"" & ""erias"" & ""irias"" & ""aras"" & ""eras"" & ""iras"" & ""avas"" & ""es"" & ""ardes"" & ""erdes"" & ""irdes"" & ""ares"" & ""eres"" & ""ires"" & ""asses"" & ""esses"" & ""isses"" & ""astes"" & ""estes"" & ""istes"" & ""is"" & ""ais"" & ""eis"" & ""areis"" & ""ereis"" & ""ireis"" & ""áreis"" & ""éreis"" & ""íreis"" & ""ásseis"" & ""ésseis"" & ""ísseis"" & ""áveis"" & ""íeis"" & ""aríeis"" & ""eríeis"" & ""iríeis"" & ""ados"" & ""idos"" & ""amos"" & ""áramos"" & ""éramos"" & ""íramos"" & ""ávamos"" & ""íamos"" & ""aríamos"" & ""eríamos"" & ""iríamos"" & ""emos"" & ""aremos"" & ""eremos"" & ""iremos"" & ""ássemos"" & ""êssemos"" & ""íssemos"" & ""imos"" & ""armos"" & ""ermos"" & ""irmos"" & ""ámos"" & ""arás"" & ""erás"" & ""irás"" & ""eu"" & ""iu"" & ""ou"" & ""ará"" & ""erá"" & ""irá"" & ""a"" & ""i"" & ""o"" & ""os"" & ""á"" & ""í"" & ""ó"" & ""e"" & ""ç"" & ""é"" & ""ê""; A_0 : constant Among_Array_Type (0 .. 2) := ( (1, 0, -1, 3, 0), (1, 2, 0, 1, 0), (3, 4, 0, 2, 0)); A_1 : constant Among_Array_Type (0 .. 2) := ( (5, 4, -1, 3, 0), (5, 6, 0, 1, 0), (7, 8, 0, 2, 0)); A_2 : constant Among_Array_Type (0 .. 3) := ( (9, 10, -1, -1, 0), (11, 12, -1, -1, 0), (13, 14, -1, -1, 0), (15, 16, -1, 1, 0)); A_3 : constant Among_Array_Type (0 .. 2) := ( (17, 20, -1, 1, 0), (21, 24, -1, 1, 0), (25, 29, -1, 1, 0)); A_4 : constant Among_Array_Type (0 .. 2) := ( (30, 31, -1, 1, 0), (32, 35, -1, 1, 0), (36, 37, -1, 1, 0)); A_5 : constant Among_Array_Type (0 .. 44) := ( (38, 40, -1, 1, 0), (41, 46, -1, 1, 0), (47, 52, -1, 4, 0), (53, 57, -1, 2, 0), (58, 60, -1, 9, 0), (61, 65, -1, 1, 0), (66, 68, -1, 1, 0), (69, 72, -1, 1, 0), (73, 75, -1, 8, 0), (76, 78, -1, 1, 0), (79, 83, -1, 7, 0), (84, 87, -1, 1, 0), (88, 92, -1, 6, 0), (93, 98, 12, 5, 0), (99, 103, -1, 1, 0), (104, 108, -1, 1, 0), (109, 111, -1, 1, 0), (112, 115, -1, 1, 0), (116, 118, -1, 1, 0), (119, 124, -1, 1, 0), (125, 130, -1, 1, 0), (131, 133, -1, 8, 0), (134, 139, -1, 1, 0), (140, 145, -1, 3, 0), (146, 149, -1, 1, 0), (150, 153, -1, 1, 0), (154, 160, -1, 4, 0), (161, 166, -1, 2, 0), (167, 170, -1, 9, 0), (171, 176, -1, 1, 0), (177, 180, -1, 1, 0), (181, 185, -1, 1, 0), (186, 189, -1, 8, 0), (190, 193, -1, 1, 0), (194, 199, -1, 7, 0), (200, 205, -1, 1, 0), (206, 210, -1, 1, 0), (211, 217, -1, 1, 0), (218, 224, -1, 3, 0), (225, 228, -1, 1, 0), (229, 233, -1, 1, 0), (234, 237, -1, 1, 0), (238, 244, -1, 1, 0), (245, 251, -1, 1, 0), (252, 255, -1, 8, 0)); A_6 : constant Among_Array_Type (0 .. 119) := ( (256, 258, -1, 1, 0), (259, 261, -1, 1, 0), (262, 263, -1, 1, 0), (264, 267, 2, 1, 0), (268, 271, 2, 1, 0), (272, 275, 2, 1, 0), (276, 278, -1, 1, 0), (279, 281, -1, 1, 0), (282, 284, -1, 1, 0), (285, 287, -1, 1, 0), (288, 291, -1, 1, 0), (292, 295, -1, 1, 0), (296, 299, -1, 1, 0), (300, 303, -1, 1, 0), (304, 307, -1, 1, 0), (308, 311, -1, 1, 0), (312, 313, -1, 1, 0), (314, 317, 16, 1, 0), (318, 321, 16, 1, 0), (322, 325, 16, 1, 0), (326, 327, -1, 1, 0), (328, 330, 20, 1, 0), (331, 335, 21, 1, 0), (336, 340, 21, 1, 0), (341, 345, 21, 1, 0), (346, 349, 20, 1, 0), (350, 353, 20, 1, 0), (354, 357, 20, 1, 0), (358, 361, 20, 1, 0), (362, 363, -1, 1, 0), (364, 367, 29, 1, 0), (368, 371, 29, 1, 0), (372, 375, 29, 1, 0), (376, 380, 29, 1, 0), (381, 385, 29, 1, 0), (386, 390, 29, 1, 0), (391, 393, -1, 1, 0), (394, 396, -1, 1, 0), (397, 400, -1, 1, 0), (401, 404, -1, 1, 0), (405, 408, -1, 1, 0), (409, 413, -1, 1, 0), (414, 418, -1, 1, 0), (419, 423, -1, 1, 0), (424, 425, -1, 1, 0), (426, 427, -1, 1, 0), (428, 429, -1, 1, 0), (430, 431, -1, 1, 0), (432, 435, 47, 1, 0), (436, 439, 47, 1, 0), (440, 442, 47, 1, 0), (443, 447, 50, 1, 0), (448, 452, 50, 1, 0), (453, 457, 50, 1, 0), (458, 461, 47, 1, 0), (462, 465, 47, 1, 0), (466, 469, 47, 1, 0), (470, 473, 47, 1, 0), (474, 475, -1, 1, 0), (476, 480, 58, 1, 0), (481, 485, 58, 1, 0), (486, 490, 58, 1, 0), (491, 494, 58, 1, 0), (495, 498, 58, 1, 0), (499, 502, 58, 1, 0), (503, 507, 58, 1, 0), (508, 512, 58, 1, 0), (513, 517, 58, 1, 0), (518, 522, 58, 1, 0), (523, 527, 58, 1, 0), (528, 532, 58, 1, 0), (533, 534, -1, 1, 0), (535, 537, 71, 1, 0), (538, 540, 71, 1, 0), (541, 545, 73, 1, 0), (546, 550, 73, 1, 0), (551, 555, 73, 1, 0), (556, 561, 73, 1, 0), (562, 567, 73, 1, 0), (568, 573, 73, 1, 0), (574, 580, 73, 1, 0), (581, 587, 73, 1, 0), (588, 594, 73, 1, 0), (595, 600, 73, 1, 0), (601, 605, 73, 1, 0), (606, 612, 84, 1, 0), (613, 619, 84, 1, 0), (620, 626, 84, 1, 0), (627, 630, -1, 1, 0), (631, 634, -1, 1, 0), (635, 638, -1, 1, 0), (639, 645, 90, 1, 0), (646, 652, 90, 1, 0), (653, 659, 90, 1, 0), (660, 666, 90, 1, 0), (667, 672, 90, 1, 0), (673, 680, 95, 1, 0), (681, 688, 95, 1, 0), (689, 696, 95, 1, 0), (697, 700, -1, 1, 0), (701, 706, 99, 1, 0), (707, 712, 99, 1, 0), (713, 718, 99, 1, 0), (719, 726, 99, 1, 0), (727, 734, 99, 1, 0), (735, 742, 99, 1, 0), (743, 746, -1, 1, 0), (747, 751, -1, 1, 0), (752, 756, -1, 1, 0), (757, 761, -1, 1, 0), (762, 766, -1, 1, 0), (767, 771, -1, 1, 0), (772, 776, -1, 1, 0), (777, 781, -1, 1, 0), (782, 783, -1, 1, 0), (784, 785, -1, 1, 0), (786, 787, -1, 1, 0), (788, 791, -1, 1, 0), (792, 795, -1, 1, 0), (796, 799, -1, 1, 0)); A_7 : constant Among_Array_Type (0 .. 6) := ( (800, 800, -1, 1, 0), (801, 801, -1, 1, 0), (802, 802, -1, 1, 0), (803, 804, -1, 1, 0), (805, 806, -1, 1, 0), (807, 808, -1, 1, 0), (809, 810, -1, 1, 0)); A_8 : constant Among_Array_Type (0 .. 3) := ( (811, 811, -1, 1, 0), (812, 813, -1, 2, 0), (814, 815, -1, 1, 0), (816, 817, -1, 1, 0)); procedure R_Prelude (Z : in out Context_Type; Result : out Boolean) is C : Result_Index; A : Integer; v_1 : Char_Index; begin -- repeat, line 36 <> loop v_1 := Z.C; -- (, line 36 Z.Bra := Z.C; -- [, line 37 -- substring, line 37 if Z.C + 1 >= Z.L or else (Character'Pos (Z.P (Z.C + 1 + 1)) /= 163 and then Character'Pos (Z.P (Z.C + 1 + 1)) /= 181) then A := 3; else -- substring, line 37 Find_Among (Z, A_0, Among_String, null, A); if A = 0 then goto lab1; end if; end if; Z.Ket := Z.C; -- ], line 37 -- among, line 37 case A is when 1 => -- (, line 38 -- <-, line 38 Slice_From (Z, ""a~""); when 2 => -- (, line 39 -- <-, line 39 Slice_From (Z, ""o~""); when 3 => -- (, line 40 -- next, line 40 C := Skip_Utf8 (Z); if C < 0 then goto lab1; end if; Z.C := C; when others => null; end case; goto lab0; <> Z.C := v_1; exit; end loop; Result := True; end R_Prelude; procedure R_Mark_regions (Z : in out Context_Type; Result : out Boolean) is C : Result_Index; A : Integer; v_1 : Char_Index; v_2 : Char_Index; v_3 : Char_Index; v_4 : Char_Index; v_5 : Char_Index; begin -- (, line 44 Z.I_PV := Z.L; Z.I_P1 := Z.L; Z.I_P2 := Z.L; -- do, line 50 v_1 := Z.C; -- (, line 50 -- or, line 52 v_2 := Z.C; -- (, line 51 In_Grouping (Z, G_V, 97, 250, False, C); if C /= 0 then goto lab2; end if; -- or, line 51 v_3 := Z.C; -- (, line 51 Out_Grouping (Z, G_V, 97, 250, False, C); if C /= 0 then goto lab4; end if; -- gopast, line 51 -- grouping v, line 51 Out_Grouping (Z, G_V, 97, 250, True, C); if C < 0 then goto lab4; end if; Z.C := Z.C + C; goto lab3; <> Z.C := v_3; -- (, line 51 In_Grouping (Z, G_V, 97, 250, False, C); if C /= 0 then goto lab2; end if; -- gopast, line 51 -- non v, line 51 In_Grouping (Z, G_V, 97, 250, True, C); if C < 0 then goto lab2; end if; Z.C := Z.C + C; <> goto lab1; <> Z.C := v_2; -- (, line 53 Out_Grouping (Z, G_V, 97, 250, False, C); if C /= 0 then goto lab0; end if; -- or, line 53 v_4 := Z.C; -- (, line 53 Out_Grouping (Z, G_V, 97, 250, False, C); if C /= 0 then goto lab8; end if; -- gopast, line 53 -- grouping v, line 53 Out_Grouping (Z, G_V, 97, 250, True, C); if C < 0 then goto lab8; end if; Z.C := Z.C + C; goto lab7; <> Z.C := v_4; -- (, line 53 In_Grouping (Z, G_V, 97, 250, False, C); if C /= 0 then goto lab0; end if; -- next, line 53 C := Skip_Utf8 (Z); if C < 0 then goto lab0; end if; Z.C := C; <> <> -- setmark pV, line 54 Z.I_PV := Z.C; <> Z.C := v_1; -- do, line 56 v_5 := Z.C; -- (, line 56 -- gopast, line 57 -- grouping v, line 57 Out_Grouping (Z, G_V, 97, 250, True, C); if C < 0 then goto lab10; end if; Z.C := Z.C + C; -- gopast, line 57 -- non v, line 57 In_Grouping (Z, G_V, 97, 250, True, C); if C < 0 then goto lab10; end if; Z.C := Z.C + C; -- setmark p1, line 57 Z.I_P1 := Z.C; -- gopast, line 58 -- grouping v, line 58 Out_Grouping (Z, G_V, 97, 250, True, C); if C < 0 then goto lab10; end if; Z.C := Z.C + C; -- gopast, line 58 -- non v, line 58 In_Grouping (Z, G_V, 97, 250, True, C); if C < 0 then goto lab10; end if; Z.C := Z.C + C; -- setmark p2, line 58 Z.I_P2 := Z.C; <> Z.C := v_5; Result := True; end R_Mark_regions; procedure R_Postlude (Z : in out Context_Type; Result : out Boolean) is C : Result_Index; A : Integer; v_1 : Char_Index; begin -- repeat, line 62 <> loop v_1 := Z.C; -- (, line 62 Z.Bra := Z.C; -- [, line 63 -- substring, line 63 if Z.C + 1 >= Z.L or else Character'Pos (Z.P (Z.C + 1 + 1)) /= 126 then A := 3; else -- substring, line 63 Find_Among (Z, A_1, Among_String, null, A); if A = 0 then goto lab1; end if; end if; Z.Ket := Z.C; -- ], line 63 -- among, line 63 case A is when 1 => -- (, line 64 -- <-, line 64 Slice_From (Z, ""ã""); when 2 => -- (, line 65 -- <-, line 65 Slice_From (Z, ""õ""); when 3 => -- (, line 66 -- next, line 66 C := Skip_Utf8 (Z); if C < 0 then goto lab1; end if; Z.C := C; when others => null; end case; goto lab0; <> Z.C := v_1; exit; end loop; Result := True; end R_Postlude; procedure R_RV (Z : in out Context_Type; Result : out Boolean) is begin Result := (Z.I_PV <= Z.C); end R_RV; procedure R_R1 (Z : in out Context_Type; Result : out Boolean) is begin Result := (Z.I_P1 <= Z.C); end R_R1; procedure R_R2 (Z : in out Context_Type; Result : out Boolean) is begin Result := (Z.I_P2 <= Z.C); end R_R2; procedure R_Standard_suffix (Z : in out Context_Type; Result : out Boolean) is C : Result_Index; A : Integer; v_1 : Char_Index; v_2 : Char_Index; v_3 : Char_Index; v_4 : Char_Index; begin -- (, line 76 Z.Ket := Z.C; -- [, line 77 -- substring, line 77 if Z.C - 2 <= Z.Lb or else Check_Among (Z, Z.C - 1, 3, 16#c9022#) then Result := False; return; -- substring, line 77 end if; Find_Among_Backward (Z, A_5, Among_String, null, A); if A = 0 then Result := False; return; end if; Z.Bra := Z.C; -- ], line 77 -- among, line 77 case A is when 1 => -- (, line 92 -- call R2, line 93 R_R2 (Z, Result); if not Result then Result := False; return; end if; -- delete, line 93 Slice_Del (Z); when 2 => -- (, line 97 -- call R2, line 98 R_R2 (Z, Result); if not Result then Result := False; return; end if; -- <-, line 98 Slice_From (Z, ""log""); when 3 => -- (, line 101 -- call R2, line 102 R_R2 (Z, Result); if not Result then Result := False; return; end if; -- <-, line 102 Slice_From (Z, ""u""); when 4 => -- (, line 105 -- call R2, line 106 R_R2 (Z, Result); if not Result then Result := False; return; end if; -- <-, line 106 Slice_From (Z, ""ente""); when 5 => -- (, line 109 -- call R1, line 110 R_R1 (Z, Result); if not Result then Result := False; return; end if; -- delete, line 110 Slice_Del (Z); -- try, line 111 v_1 := Z.L - Z.C; -- (, line 111 Z.Ket := Z.C; -- [, line 112 -- substring, line 112 if Z.C - 1 <= Z.Lb or else Check_Among (Z, Z.C - 1, 3, 16#480018#) then Z.C := Z.L - v_1; goto lab0; -- substring, line 112 end if; Find_Among_Backward (Z, A_2, Among_String, null, A); if A = 0 then Z.C := Z.L - v_1; goto lab0; end if; Z.Bra := Z.C; -- ], line 112 -- call R2, line 112 R_R2 (Z, Result); if not Result then Z.C := Z.L - v_1; goto lab0; end if; -- delete, line 112 Slice_Del (Z); -- among, line 112 case A is when 1 => -- (, line 113 Z.Ket := Z.C; -- [, line 113 -- literal, line 113 C := Eq_S_Backward (Z, ""at""); if C = 0 then Z.C := Z.L - v_1; goto lab0; end if; Z.C := Z.C - C; Z.Bra := Z.C; -- ], line 113 -- call R2, line 113 R_R2 (Z, Result); if not Result then Z.C := Z.L - v_1; goto lab0; end if; -- delete, line 113 Slice_Del (Z); when others => null; end case; <> when 6 => -- (, line 121 -- call R2, line 122 R_R2 (Z, Result); if not Result then Result := False; return; end if; -- delete, line 122 Slice_Del (Z); -- try, line 123 v_2 := Z.L - Z.C; -- (, line 123 Z.Ket := Z.C; -- [, line 124 -- substring, line 124 if Z.C - 3 <= Z.Lb or else (Character'Pos (Z.P (Z.C)) /= 101 and then Character'Pos (Z.P (Z.C)) /= 108) then Z.C := Z.L - v_2; goto lab1; -- substring, line 124 end if; Find_Among_Backward (Z, A_3, Among_String, null, A); if A = 0 then Z.C := Z.L - v_2; goto lab1; end if; Z.Bra := Z.C; -- ], line 124 -- (, line 127 -- call R2, line 127 R_R2 (Z, Result); if not Result then Z.C := Z.L - v_2; goto lab1; end if; -- delete, line 127 Slice_Del (Z); <> when 7 => -- (, line 133 -- call R2, line 134 R_R2 (Z, Result); if not Result then Result := False; return; end if; -- delete, line 134 Slice_Del (Z); -- try, line 135 v_3 := Z.L - Z.C; -- (, line 135 Z.Ket := Z.C; -- [, line 136 -- substring, line 136 if Z.C - 1 <= Z.Lb or else Check_Among (Z, Z.C - 1, 3, 16#401008#) then Z.C := Z.L - v_3; goto lab2; -- substring, line 136 end if; Find_Among_Backward (Z, A_4, Among_String, null, A); if A = 0 then Z.C := Z.L - v_3; goto lab2; end if; Z.Bra := Z.C; -- ], line 136 -- (, line 139 -- call R2, line 139 R_R2 (Z, Result); if not Result then Z.C := Z.L - v_3; goto lab2; end if; -- delete, line 139 Slice_Del (Z); <> when 8 => -- (, line 145 -- call R2, line 146 R_R2 (Z, Result); if not Result then Result := False; return; end if; -- delete, line 146 Slice_Del (Z); -- try, line 147 v_4 := Z.L - Z.C; -- (, line 147 Z.Ket := Z.C; -- [, line 148 -- literal, line 148 C := Eq_S_Backward (Z, ""at""); if C = 0 then Z.C := Z.L - v_4; goto lab3; end if; Z.C := Z.C - C; Z.Bra := Z.C; -- ], line 148 -- call R2, line 148 R_R2 (Z, Result); if not Result then Z.C := Z.L - v_4; goto lab3; end if; -- delete, line 148 Slice_Del (Z); <> when 9 => -- (, line 152 -- call RV, line 153 R_RV (Z, Result); if not Result then Result := False; return; end if; -- literal, line 153 C := Eq_S_Backward (Z, ""e""); if C = 0 then Result := False; return; end if; Z.C := Z.C - C; -- <-, line 154 Slice_From (Z, ""ir""); when others => null; end case; Result := True; end R_Standard_suffix; procedure R_Verb_suffix (Z : in out Context_Type; Result : out Boolean) is C : Result_Index; A : Integer; v_2 : Integer; begin if Z.C < Z.I_PV then Result := False; return; end if; v_2 := Z.Lb; Z.Lb := Z.I_PV; -- (, line 159 Z.Ket := Z.C; -- [, line 160 -- substring, line 160 Find_Among_Backward (Z, A_6, Among_String, null, A); if A = 0 then Z.Lb := v_2; Result := False; return; end if; Z.Bra := Z.C; -- ], line 160 -- (, line 179 -- delete, line 179 Slice_Del (Z); Z.Lb := v_2; Result := True; end R_Verb_suffix; procedure R_Residual_suffix (Z : in out Context_Type; Result : out Boolean) is C : Result_Index; A : Integer; begin -- (, line 183 Z.Ket := Z.C; -- [, line 184 -- substring, line 184 Find_Among_Backward (Z, A_7, Among_String, null, A); if A = 0 then Result := False; return; end if; Z.Bra := Z.C; -- ], line 184 -- (, line 187 -- call RV, line 187 R_RV (Z, Result); if not Result then Result := False; return; end if; -- delete, line 187 Slice_Del (Z); Result := True; end R_Residual_suffix; procedure R_Residual_form (Z : in out Context_Type; Result : out Boolean) is C : Result_Index; A : Integer; v_1 : Char_Index; v_2 : Char_Index; v_3 : Char_Index; begin -- (, line 191 Z.Ket := Z.C; -- [, line 192 -- substring, line 192 Find_Among_Backward (Z, A_8, Among_String, null, A); if A = 0 then Result := False; return; end if; Z.Bra := Z.C; -- ], line 192 -- among, line 192 case A is when 1 => -- (, line 194 -- call RV, line 194 R_RV (Z, Result); if not Result then Result := False; return; end if; -- delete, line 194 Slice_Del (Z); Z.Ket := Z.C; -- [, line 194 -- or, line 194 v_1 := Z.L - Z.C; -- (, line 194 -- literal, line 194 C := Eq_S_Backward (Z, ""u""); if C = 0 then goto lab1; end if; Z.C := Z.C - C; Z.Bra := Z.C; -- ], line 194 -- test, line 194 v_2 := Z.L - Z.C; -- literal, line 194 C := Eq_S_Backward (Z, ""g""); if C = 0 then goto lab1; end if; Z.C := Z.C - C; Z.C := Z.L - v_2; goto lab0; <> Z.C := Z.L - v_1; -- (, line 195 -- literal, line 195 C := Eq_S_Backward (Z, ""i""); if C = 0 then Result := False; return; end if; Z.C := Z.C - C; Z.Bra := Z.C; -- ], line 195 -- test, line 195 v_3 := Z.L - Z.C; -- literal, line 195 C := Eq_S_Backward (Z, ""c""); if C = 0 then Result := False; return; end if; Z.C := Z.C - C; Z.C := Z.L - v_3; <> -- call RV, line 195 R_RV (Z, Result); if not Result then Result := False; return; end if; -- delete, line 195 Slice_Del (Z); when 2 => -- (, line 196 -- <-, line 196 Slice_From (Z, ""c""); when others => null; end case; Result := True; end R_Residual_form; procedure Stem (Z : in out Context_Type; Result : out Boolean) is C : Result_Index; A : Integer; v_1 : Char_Index; v_3 : Char_Index; v_4 : Char_Index; v_5 : Char_Index; v_6 : Char_Index; v_7 : Char_Index; v_8 : Char_Index; v_9 : Char_Index; v_10 : Char_Index; begin -- (, line 201 -- do, line 202 v_1 := Z.C; -- call prelude, line 202 R_Prelude (Z, Result); Z.C := v_1; -- do, line 203 -- call mark_regions, line 203 R_Mark_regions (Z, Result); Z.Lb := Z.C; Z.C := Z.L; -- backwards, line 204 -- (, line 204 -- do, line 205 v_3 := Z.L - Z.C; -- or, line 209 v_4 := Z.L - Z.C; -- and, line 207 v_5 := Z.L - Z.C; -- or, line 206 v_6 := Z.L - Z.C; -- call standard_suffix, line 206 R_Standard_suffix (Z, Result); if not Result then goto lab4; end if; goto lab3; <> Z.C := Z.L - v_6; -- call verb_suffix, line 206 R_Verb_suffix (Z, Result); if not Result then goto lab2; end if; <> Z.C := Z.L - v_5; -- do, line 207 v_7 := Z.L - Z.C; -- (, line 207 Z.Ket := Z.C; -- [, line 207 -- literal, line 207 C := Eq_S_Backward (Z, ""i""); if C = 0 then goto lab5; end if; Z.C := Z.C - C; Z.Bra := Z.C; -- ], line 207 -- test, line 207 v_8 := Z.L - Z.C; -- literal, line 207 C := Eq_S_Backward (Z, ""c""); if C = 0 then goto lab5; end if; Z.C := Z.C - C; Z.C := Z.L - v_8; -- call RV, line 207 R_RV (Z, Result); if not Result then goto lab5; end if; -- delete, line 207 Slice_Del (Z); <> Z.C := Z.L - v_7; goto lab1; <> Z.C := Z.L - v_4; -- call residual_suffix, line 209 R_Residual_suffix (Z, Result); if not Result then goto lab0; end if; <> <> Z.C := Z.L - v_3; -- do, line 211 v_9 := Z.L - Z.C; -- call residual_form, line 211 R_Residual_form (Z, Result); Z.C := Z.L - v_9; Z.C := Z.Lb; -- do, line 213 v_10 := Z.C; -- call postlude, line 213 R_Postlude (Z, Result); Z.C := v_10; Result := True; end Stem; end Stemmer.Portuguese; ",12113,False,2140.338855428894,median "[[kafka-component]] = Kafka Component :page-source: components/camel-kafka/src/main/docs/kafka-component.adoc *Available as of Camel version 2.13* The Kafka component is used for communicating with http://kafka.apache.org/[Apache Kafka] message broker. Maven users will need to add the following dependency to their `pom.xml` for this component. [source,xml] ------------------------------------------------------------ org.apache.camel camel-kafka x.x.x ------------------------------------------------------------ == URI format [source,java] --------------------------- kafka:topic[?options] --------------------------- == Options // component options: START The Kafka component supports 8 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *configuration* (common) | Allows to pre-configure the Kafka component with common options that the endpoints will reuse. | | KafkaConfiguration | *brokers* (common) | URL of the Kafka brokers to use. The format is host1:port1,host2:port2, and the list can be a subset of brokers or a VIP pointing to a subset of brokers. This option is known as bootstrap.servers in the Kafka documentation. | | String | *workerPool* (advanced) | To use a shared custom worker pool for continue routing Exchange after kafka server has acknowledge the message that was sent to it from KafkaProducer using asynchronous non-blocking processing. If using this option then you must handle the lifecycle of the thread pool to shut the pool down when no longer needed. | | ExecutorService | *useGlobalSslContext Parameters* (security) | Enable usage of global SSL context parameters. | false | boolean | *breakOnFirstError* (consumer) | This options controls what happens when a consumer is processing an exchange and it fails. If the option is false then the consumer continues to the next message and processes it. If the option is true then the consumer breaks out, and will seek back to offset of the message that caused a failure, and then re-attempt to process this message. However this can lead to endless processing of the same message if its bound to fail every time, eg a poison message. Therefore its recommended to deal with that for example by using Camel's error handler. | false | boolean | *allowManualCommit* (consumer) | Whether to allow doing manual commits via KafkaManualCommit. If this option is enabled then an instance of KafkaManualCommit is stored on the Exchange message header, which allows end users to access this API and perform manual offset commits via the Kafka consumer. | false | boolean | *kafkaManualCommit Factory* (consumer) | Factory to use for creating KafkaManualCommit instances. This allows to plugin a custom factory to create custom KafkaManualCommit instances in case special logic is needed when doing manual commits that deviates from the default implementation that comes out of the box. | | KafkaManualCommitFactory | *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 Kafka endpoint is configured using URI syntax: ---- kafka:topic ---- with the following path and query parameters: === Path Parameters (1 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *topic* | *Required* Name of the topic to use. On the consumer you can use comma to separate multiple topics. A producer can only send a message to a single topic. | | String |=== === Query Parameters (95 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *brokers* (common) | URL of the Kafka brokers to use. The format is host1:port1,host2:port2, and the list can be a subset of brokers or a VIP pointing to a subset of brokers. This option is known as bootstrap.servers in the Kafka documentation. | | String | *clientId* (common) | The client id is a user-specified string sent in each request to help trace calls. It should logically identify the application making the request. | | String | *headerFilterStrategy* (common) | To use a custom HeaderFilterStrategy to filter header to and from Camel message. | | HeaderFilterStrategy | *reconnectBackoffMaxMs* (common) | The maximum amount of time in milliseconds to wait when reconnecting to a broker that has repeatedly failed to connect. If provided, the backoff per host will increase exponentially for each consecutive connection failure, up to this maximum. After calculating the backoff increase, 20% random jitter is added to avoid connection storms. | 1000 | Integer | *allowManualCommit* (consumer) | Whether to allow doing manual commits via KafkaManualCommit. If this option is enabled then an instance of KafkaManualCommit is stored on the Exchange message header, which allows end users to access this API and perform manual offset commits via the Kafka consumer. | false | boolean | *autoCommitEnable* (consumer) | If true, periodically commit to ZooKeeper the offset of messages already fetched by the consumer. This committed offset will be used when the process fails as the position from which the new consumer will begin. | true | Boolean | *autoCommitIntervalMs* (consumer) | The frequency in ms that the consumer offsets are committed to zookeeper. | 5000 | Integer | *autoCommitOnStop* (consumer) | Whether to perform an explicit auto commit when the consumer stops to ensure the broker has a commit from the last consumed message. This requires the option autoCommitEnable is turned on. The possible values are: sync, async, or none. And sync is the default value. | sync | String | *autoOffsetReset* (consumer) | What to do when there is no initial offset in ZooKeeper or if an offset is out of range: earliest : automatically reset the offset to the earliest offset latest : automatically reset the offset to the latest offset fail: throw exception to the consumer | latest | String | *breakOnFirstError* (consumer) | This options controls what happens when a consumer is processing an exchange and it fails. If the option is false then the consumer continues to the next message and processes it. If the option is true then the consumer breaks out, and will seek back to offset of the message that caused a failure, and then re-attempt to process this message. However this can lead to endless processing of the same message if its bound to fail every time, eg a poison message. Therefore its recommended to deal with that for example by using Camel's error handler. | false | 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 | *checkCrcs* (consumer) | Automatically check the CRC32 of the records consumed. This ensures no on-the-wire or on-disk corruption to the messages occurred. This check adds some overhead, so it may be disabled in cases seeking extreme performance. | true | Boolean | *consumerRequestTimeoutMs* (consumer) | The configuration controls the maximum amount of time the client will wait for the response of a request. If the response is not received before the timeout elapses the client will resend the request if necessary or fail the request if retries are exhausted. | 40000 | Integer | *consumersCount* (consumer) | The number of consumers that connect to kafka server | 1 | int | *consumerStreams* (consumer) | Number of concurrent consumers on the consumer | 10 | int | *fetchMaxBytes* (consumer) | The maximum amount of data the server should return for a fetch request This is not an absolute maximum, if the first message in the first non-empty partition of the fetch is larger than this value, the message will still be returned to ensure that the consumer can make progress. The maximum message size accepted by the broker is defined via message.max.bytes (broker config) or max.message.bytes (topic config). Note that the consumer performs multiple fetches in parallel. | 52428800 | Integer | *fetchMinBytes* (consumer) | The minimum amount of data the server should return for a fetch request. If insufficient data is available the request will wait for that much data to accumulate before answering the request. | 1 | Integer | *fetchWaitMaxMs* (consumer) | The maximum amount of time the server will block before answering the fetch request if there isn't sufficient data to immediately satisfy fetch.min.bytes | 500 | Integer | *groupId* (consumer) | A string that uniquely identifies the group of consumer processes to which this consumer belongs. By setting the same group id multiple processes indicate that they are all part of the same consumer group. This option is required for consumers. | | String | *heartbeatIntervalMs* (consumer) | The expected time between heartbeats to the consumer coordinator when using Kafka's group management facilities. Heartbeats are used to ensure that the consumer's session stays active and to facilitate rebalancing when new consumers join or leave the group. The value must be set lower than session.timeout.ms, but typically should be set no higher than 1/3 of that value. It can be adjusted even lower to control the expected time for normal rebalances. | 3000 | Integer | *kafkaHeaderDeserializer* (consumer) | Sets custom KafkaHeaderDeserializer for deserialization kafka headers values to camel headers values. | | KafkaHeaderDeserializer | *keyDeserializer* (consumer) | Deserializer class for key that implements the Deserializer interface. | org.apache.kafka.common.serialization.StringDeserializer | String | *maxPartitionFetchBytes* (consumer) | The maximum amount of data per-partition the server will return. The maximum total memory used for a request will be #partitions max.partition.fetch.bytes. This size must be at least as large as the maximum message size the server allows or else it is possible for the producer to send messages larger than the consumer can fetch. If that happens, the consumer can get stuck trying to fetch a large message on a certain partition. | 1048576 | Integer | *maxPollIntervalMs* (consumer) | The maximum delay between invocations of poll() when using consumer group management. This places an upper bound on the amount of time that the consumer can be idle before fetching more records. If poll() is not called before expiration of this timeout, then the consumer is considered failed and the group will rebalance in order to reassign the partitions to another member. | | Long | *maxPollRecords* (consumer) | The maximum number of records returned in a single call to poll() | 500 | Integer | *offsetRepository* (consumer) | The offset repository to use in order to locally store the offset of each partition of the topic. Defining one will disable the autocommit. | | StateRepository | *partitionAssignor* (consumer) | The class name of the partition assignment strategy that the client will use to distribute partition ownership amongst consumer instances when group management is used | org.apache.kafka.clients.consumer.RangeAssignor | String | *pollTimeoutMs* (consumer) | The timeout used when polling the KafkaConsumer. | 5000 | Long | *seekTo* (consumer) | Set if KafkaConsumer will read from beginning or end on startup: beginning : read from beginning end : read from end This is replacing the earlier property seekToBeginning | | String | *sessionTimeoutMs* (consumer) | The timeout used to detect failures when using Kafka's group management facilities. | 10000 | Integer | *specificAvroReader* (consumer) | This enables the use of a specific Avro reader for use with the Confluent Platform schema registry and the io.confluent.kafka.serializers.KafkaAvroDeserializer. This option is only available in the Confluent Platform (not standard Apache Kafka) | false | boolean | *topicIsPattern* (consumer) | Whether the topic is a pattern (regular expression). This can be used to subscribe to dynamic number of topics matching the pattern. | false | boolean | *valueDeserializer* (consumer) | Deserializer class for value that implements the Deserializer interface. | org.apache.kafka.common.serialization.StringDeserializer | 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. | | ExchangePattern | *bufferMemorySize* (producer) | The total bytes of memory the producer can use to buffer records waiting to be sent to the server. If records are sent faster than they can be delivered to the server the producer will either block or throw an exception based on the preference specified by block.on.buffer.full.This setting should correspond roughly to the total memory the producer will use, but is not a hard bound since not all memory the producer uses is used for buffering. Some additional memory will be used for compression (if compression is enabled) as well as for maintaining in-flight requests. | 33554432 | Integer | *compressionCodec* (producer) | This parameter allows you to specify the compression codec for all data generated by this producer. Valid values are none, gzip and snappy. | none | String | *connectionMaxIdleMs* (producer) | Close idle connections after the number of milliseconds specified by this config. | 540000 | Integer | *enableIdempotence* (producer) | If set to 'true' the producer will ensure that exactly one copy of each message is written in the stream. If 'false', producer retries may write duplicates of the retried message in the stream. If set to true this option will require max.in.flight.requests.per.connection to be set to 1 and retries cannot be zero and additionally acks must be set to 'all'. | false | boolean | *kafkaHeaderSerializer* (producer) | Sets custom KafkaHeaderDeserializer for serialization camel headers values to kafka headers values. | | KafkaHeaderSerializer | *key* (producer) | The record key (or null if no key is specified). If this option has been configured then it take precedence over header KafkaConstants#KEY | | String | *keySerializerClass* (producer) | The serializer class for keys (defaults to the same as for messages if nothing is given). | org.apache.kafka.common.serialization.StringSerializer | String | *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 | *lingerMs* (producer) | The producer groups together any records that arrive in between request transmissions into a single batched request. Normally this occurs only under load when records arrive faster than they can be sent out. However in some circumstances the client may want to reduce the number of requests even under moderate load. This setting accomplishes this by adding a small amount of artificial delaythat is, rather than immediately sending out a record the producer will wait for up to the given delay to allow other records to be sent so that the sends can be batched together. This can be thought of as analogous to Nagle's algorithm in TCP. This setting gives the upper bound on the delay for batching: once we get batch.size worth of records for a partition it will be sent immediately regardless of this setting, however if we have fewer than this many bytes accumulated for this partition we will 'linger' for the specified time waiting for more records to show up. This setting defaults to 0 (i.e. no delay). Setting linger.ms=5, for example, would have the effect of reducing the number of requests sent but would add up to 5ms of latency to records sent in the absense of load. | 0 | Integer | *maxBlockMs* (producer) | The configuration controls how long sending to kafka will block. These methods can be blocked for multiple reasons. For e.g: buffer full, metadata unavailable.This configuration imposes maximum limit on the total time spent in fetching metadata, serialization of key and value, partitioning and allocation of buffer memory when doing a send(). In case of partitionsFor(), this configuration imposes a maximum time threshold on waiting for metadata | 60000 | Integer | *maxInFlightRequest* (producer) | The maximum number of unacknowledged requests the client will send on a single connection before blocking. Note that if this setting is set to be greater than 1 and there are failed sends, there is a risk of message re-ordering due to retries (i.e., if retries are enabled). | 5 | Integer | *maxRequestSize* (producer) | The maximum size of a request. This is also effectively a cap on the maximum record size. Note that the server has its own cap on record size which may be different from this. This setting will limit the number of record batches the producer will send in a single request to avoid sending huge requests. | 1048576 | Integer | *metadataMaxAgeMs* (producer) | The period of time in milliseconds after which we force a refresh of metadata even if we haven't seen any partition leadership changes to proactively discover any new brokers or partitions. | 300000 | Integer | *metricReporters* (producer) | A list of classes to use as metrics reporters. Implementing the MetricReporter interface allows plugging in classes that will be notified of new metric creation. The JmxReporter is always included to register JMX statistics. | | String | *metricsSampleWindowMs* (producer) | The number of samples maintained to compute metrics. | 30000 | Integer | *noOfMetricsSample* (producer) | The number of samples maintained to compute metrics. | 2 | Integer | *partitioner* (producer) | The partitioner class for partitioning messages amongst sub-topics. The default partitioner is based on the hash of the key. | org.apache.kafka.clients.producer.internals.DefaultPartitioner | String | *partitionKey* (producer) | The partition to which the record will be sent (or null if no partition was specified). If this option has been configured then it take precedence over header KafkaConstants#PARTITION_KEY | | Integer | *producerBatchSize* (producer) | The producer will attempt to batch records together into fewer requests whenever multiple records are being sent to the same partition. This helps performance on both the client and the server. This configuration controls the default batch size in bytes. No attempt will be made to batch records larger than this size.Requests sent to brokers will contain multiple batches, one for each partition with data available to be sent.A small batch size will make batching less common and may reduce throughput (a batch size of zero will disable batching entirely). A very large batch size may use memory a bit more wastefully as we will always allocate a buffer of the specified batch size in anticipation of additional records. | 16384 | Integer | *queueBufferingMaxMessages* (producer) | The maximum number of unsent messages that can be queued up the producer when using async mode before either the producer must be blocked or data must be dropped. | 10000 | Integer | *receiveBufferBytes* (producer) | The size of the TCP receive buffer (SO_RCVBUF) to use when reading data. | 65536 | Integer | *reconnectBackoffMs* (producer) | The amount of time to wait before attempting to reconnect to a given host. This avoids repeatedly connecting to a host in a tight loop. This backoff applies to all requests sent by the consumer to the broker. | 50 | Integer | *recordMetadata* (producer) | Whether the producer should store the RecordMetadata results from sending to Kafka. The results are stored in a List containing the RecordMetadata metadata's. The list is stored on a header with the key KafkaConstants#KAFKA_RECORDMETA | true | boolean | *requestRequiredAcks* (producer) | The number of acknowledgments the producer requires the leader to have received before considering a request complete. This controls the durability of records that are sent. The following settings are common: acks=0 If set to zero then the producer will not wait for any acknowledgment from the server at all. The record will be immediately added to the socket buffer and considered sent. No guarantee can be made that the server has received the record in this case, and the retries configuration will not take effect (as the client won't generally know of any failures). The offset given back for each record will always be set to -1. acks=1 This will mean the leader will write the record to its local log but will respond without awaiting full acknowledgement from all followers. In this case should the leader fail immediately after acknowledging the record but before the followers have replicated it then the record will be lost. acks=all This means the leader will wait for the full set of in-sync replicas to acknowledge the record. This guarantees that the record will not be lost as long as at least one in-sync replica remains alive. This is the strongest available guarantee. | 1 | String | *requestTimeoutMs* (producer) | The amount of time the broker will wait trying to meet the request.required.acks requirement before sending back an error to the client. | 305000 | Integer | *retries* (producer) | Setting a value greater than zero will cause the client to resend any record whose send fails with a potentially transient error. Note that this retry is no different than if the client resent the record upon receiving the error. Allowing retries will potentially change the ordering of records because if two records are sent to a single partition, and the first fails and is retried but the second succeeds, then the second record may appear first. | 0 | Integer | *retryBackoffMs* (producer) | Before each retry, the producer refreshes the metadata of relevant topics to see if a new leader has been elected. Since leader election takes a bit of time, this property specifies the amount of time that the producer waits before refreshing the metadata. | 100 | Integer | *sendBufferBytes* (producer) | Socket write buffer size | 131072 | Integer | *serializerClass* (producer) | The serializer class for messages. | org.apache.kafka.common.serialization.StringSerializer | String | *workerPool* (producer) | To use a custom worker pool for continue routing Exchange after kafka server has acknowledge the message that was sent to it from KafkaProducer using asynchronous non-blocking processing. | | ExecutorService | *workerPoolCoreSize* (producer) | Number of core threads for the worker pool for continue routing Exchange after kafka server has acknowledge the message that was sent to it from KafkaProducer using asynchronous non-blocking processing. | 10 | Integer | *workerPoolMaxSize* (producer) | Maximum number of threads for the worker pool for continue routing Exchange after kafka server has acknowledge the message that was sent to it from KafkaProducer using asynchronous non-blocking processing. | 20 | Integer | *basicPropertyBinding* (advanced) | Whether the endpoint should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported). | false | boolean | *interceptorClasses* (monitoring) | Sets interceptors for producer or consumers. Producer interceptors have to be classes implementing org.apache.kafka.clients.producer.ProducerInterceptor Consumer interceptors have to be classes implementing org.apache.kafka.clients.consumer.ConsumerInterceptor Note that if you use Producer interceptor on a consumer it will throw a class cast exception in runtime | | String | *kerberosBeforeReloginMin Time* (security) | Login thread sleep time between refresh attempts. | 60000 | Integer | *kerberosInitCmd* (security) | Kerberos kinit command path. Default is /usr/bin/kinit | /usr/bin/kinit | String | *kerberosPrincipalToLocal Rules* (security) | A list of rules for mapping from principal names to short names (typically operating system usernames). The rules are evaluated in order and the first rule that matches a principal name is used to map it to a short name. Any later rules in the list are ignored. By default, principal names of the form \\{username\\}/\\{hostname\\}\\{REALM\\} are mapped to \\{username\\}. For more details on the format please see the security authorization and acls documentation.. Multiple values can be separated by comma | DEFAULT | String | *kerberosRenewJitter* (security) | Percentage of random jitter added to the renewal time. | 0.05 | Double | *kerberosRenewWindowFactor* (security) | Login thread will sleep until the specified window factor of time from last refresh to ticket's expiry has been reached, at which time it will try to renew the ticket. | 0.8 | Double | *saslJaasConfig* (security) | Expose the kafka sasl.jaas.config parameter Example: org.apache.kafka.common.security.plain.PlainLoginModule required username=USERNAME password=PASSWORD; | | String | *saslKerberosServiceName* (security) | The Kerberos principal name that Kafka runs as. This can be defined either in Kafka's JAAS config or in Kafka's config. | | String | *saslMechanism* (security) | The Simple Authentication and Security Layer (SASL) Mechanism used. For the valid values see a href= \\http://www.iana.org/assignments/sasl-mechanisms/sasl-mechanisms.xhtml\\http://www.iana.org/assignments/sasl-mechanisms/sasl-mechanisms.xhtml | GSSAPI | String | *securityProtocol* (security) | Protocol used to communicate with brokers. SASL_PLAINTEXT, PLAINTEXT and SSL are supported | PLAINTEXT | String | *sslCipherSuites* (security) | A list of cipher suites. This is a named combination of authentication, encryption, MAC and key exchange algorithm used to negotiate the security settings for a network connection using TLS or SSL network protocol.By default all the available cipher suites are supported. | | String | *sslContextParameters* (security) | SSL configuration using a Camel SSLContextParameters object. If configured it's applied before the other SSL endpoint parameters. | | SSLContextParameters | *sslEnabledProtocols* (security) | The list of protocols enabled for SSL connections. TLSv1.2, TLSv1.1 and TLSv1 are enabled by default. | TLSv1.2,TLSv1.1,TLSv1 | String | *sslEndpointAlgorithm* (security) | The endpoint identification algorithm to validate server hostname using server certificate. | | String | *sslKeymanagerAlgorithm* (security) | The algorithm used by key manager factory for SSL connections. Default value is the key manager factory algorithm configured for the Java Virtual Machine. | SunX509 | String | *sslKeyPassword* (security) | The password of the private key in the key store file. This is optional for client. | | String | *sslKeystoreLocation* (security) | The location of the key store file. This is optional for client and can be used for two-way authentication for client. | | String | *sslKeystorePassword* (security) | The store password for the key store file.This is optional for client and only needed if ssl.keystore.location is configured. | | String | *sslKeystoreType* (security) | The file format of the key store file. This is optional for client. Default value is JKS | JKS | String | *sslProtocol* (security) | The SSL protocol used to generate the SSLContext. Default setting is TLS, which is fine for most cases. Allowed values in recent JVMs are TLS, TLSv1.1 and TLSv1.2. SSL, SSLv2 and SSLv3 may be supported in older JVMs, but their usage is discouraged due to known security vulnerabilities. | TLS | String | *sslProvider* (security) | The name of the security provider used for SSL connections. Default value is the default security provider of the JVM. | | String | *sslTrustmanagerAlgorithm* (security) | The algorithm used by trust manager factory for SSL connections. Default value is the trust manager factory algorithm configured for the Java Virtual Machine. | PKIX | String | *sslTruststoreLocation* (security) | The location of the trust store file. | | String | *sslTruststoreType* (security) | The file format of the trust store file. Default value is JKS. | JKS | String | *schemaRegistryURL* (confluent) | URL of the Confluent Platform schema registry servers to use. The format is host1:port1,host2:port2. This is known as schema.registry.url in the Confluent Platform documentation. This option is only available in the Confluent Platform (not standard Apache Kafka) | | String | *sslTruststorePassword* (security) | The password for the trust store file. | | 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-kafka-starter x.x.x ---- The component supports 98 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *camel.component.kafka.allow-manual-commit* | Whether to allow doing manual commits via KafkaManualCommit. If this option is enabled then an instance of KafkaManualCommit is stored on the Exchange message header, which allows end users to access this API and perform manual offset commits via the Kafka consumer. | false | Boolean | *camel.component.kafka.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.kafka.break-on-first-error* | This options controls what happens when a consumer is processing an exchange and it fails. If the option is false then the consumer continues to the next message and processes it. If the option is true then the consumer breaks out, and will seek back to offset of the message that caused a failure, and then re-attempt to process this message. However this can lead to endless processing of the same message if its bound to fail every time, eg a poison message. Therefore its recommended to deal with that for example by using Camel's error handler. | false | Boolean | *camel.component.kafka.brokers* | URL of the Kafka brokers to use. The format is host1:port1,host2:port2, and the list can be a subset of brokers or a VIP pointing to a subset of brokers. This option is known as bootstrap.servers in the Kafka documentation. | | String | *camel.component.kafka.configuration.allow-manual-commit* | Whether to allow doing manual commits via {@link KafkaManualCommit}.

If this option is enabled then an instance of {@link KafkaManualCommit} is stored on the {@link Exchange} message header, which allows end users to access this API and perform manual offset commits via the Kafka consumer. | false | Boolean | *camel.component.kafka.configuration.auto-commit-enable* | If true, periodically commit to ZooKeeper the offset of messages already fetched by the consumer. This committed offset will be used when the process fails as the position from which the new consumer will begin. | true | Boolean | *camel.component.kafka.configuration.auto-commit-interval-ms* | The frequency in ms that the consumer offsets are committed to zookeeper. | 5000 | Integer | *camel.component.kafka.configuration.auto-commit-on-stop* | Whether to perform an explicit auto commit when the consumer stops to ensure the broker has a commit from the last consumed message. This requires the option autoCommitEnable is turned on. The possible values are: sync, async, or none. And sync is the default value. | sync | String | *camel.component.kafka.configuration.auto-offset-reset* | What to do when there is no initial offset in ZooKeeper or if an offset is out of range: earliest : automatically reset the offset to the earliest offset latest : automatically reset the offset to the latest offset fail: throw exception to the consumer | latest | String | *camel.component.kafka.configuration.break-on-first-error* | This options controls what happens when a consumer is processing an exchange and it fails. If the option is false then the consumer continues to the next message and processes it. If the option is true then the consumer breaks out, and will seek back to offset of the message that caused a failure, and then re-attempt to process this message. However this can lead to endless processing of the same message if its bound to fail every time, eg a poison message. Therefore its recommended to deal with that for example by using Camel's error handler. | false | Boolean | *camel.component.kafka.configuration.brokers* | URL of the Kafka brokers to use. The format is host1:port1,host2:port2, and the list can be a subset of brokers or a VIP pointing to a subset of brokers.

This option is known as bootstrap.servers in the Kafka documentation. | | String | *camel.component.kafka.configuration.buffer-memory-size* | The total bytes of memory the producer can use to buffer records waiting to be sent to the server. If records are sent faster than they can be delivered to the server the producer will either block or throw an exception based on the preference specified by block.on.buffer.full.This setting should correspond roughly to the total memory the producer will use, but is not a hard bound since not all memory the producer uses is used for buffering. Some additional memory will be used for compression (if compression is enabled) as well as for maintaining in-flight requests. | 33554432 | Integer | *camel.component.kafka.configuration.check-crcs* | Automatically check the CRC32 of the records consumed. This ensures no on-the-wire or on-disk corruption to the messages occurred. This check adds some overhead, so it may be disabled in cases seeking extreme performance. | true | Boolean | *camel.component.kafka.configuration.client-id* | The client id is a user-specified string sent in each request to help trace calls. It should logically identify the application making the request. | | String | *camel.component.kafka.configuration.compression-codec* | This parameter allows you to specify the compression codec for all data generated by this producer. Valid values are ""none"", ""gzip"" and ""snappy"". | none | String | *camel.component.kafka.configuration.connection-max-idle-ms* | Close idle connections after the number of milliseconds specified by this config. | 540000 | Integer | *camel.component.kafka.configuration.consumer-request-timeout-ms* | The configuration controls the maximum amount of time the client will wait for the response of a request. If the response is not received before the timeout elapses the client will resend the request if necessary or fail the request if retries are exhausted. | 40000 | Integer | *camel.component.kafka.configuration.consumer-streams* | Number of concurrent consumers on the consumer | 10 | Integer | *camel.component.kafka.configuration.consumers-count* | The number of consumers that connect to kafka server | 1 | Integer | *camel.component.kafka.configuration.enable-idempotence* | If set to 'true' the producer will ensure that exactly one copy of each message is written in the stream. If 'false', producer retries may write duplicates of the retried message in the stream. If set to true this option will require max.in.flight.requests.per.connection to be set to 1 and retries cannot be zero and additionally acks must be set to 'all'. | false | Boolean | *camel.component.kafka.configuration.fetch-max-bytes* | The maximum amount of data the server should return for a fetch request This is not an absolute maximum, if the first message in the first non-empty partition of the fetch is larger than this value, the message will still be returned to ensure that the consumer can make progress. The maximum message size accepted by the broker is defined via message.max.bytes (broker config) or max.message.bytes (topic config). Note that the consumer performs multiple fetches in parallel. | 52428800 | Integer | *camel.component.kafka.configuration.fetch-min-bytes* | The minimum amount of data the server should return for a fetch request. If insufficient data is available the request will wait for that much data to accumulate before answering the request. | 1 | Integer | *camel.component.kafka.configuration.fetch-wait-max-ms* | The maximum amount of time the server will block before answering the fetch request if there isn't sufficient data to immediately satisfy fetch.min.bytes | 500 | Integer | *camel.component.kafka.configuration.group-id* | A string that uniquely identifies the group of consumer processes to which this consumer belongs. By setting the same group id multiple processes indicate that they are all part of the same consumer group. This option is required for consumers. | | String | *camel.component.kafka.configuration.header-filter-strategy* | To use a custom HeaderFilterStrategy to filter header to and from Camel message. | | HeaderFilterStrategy | *camel.component.kafka.configuration.heartbeat-interval-ms* | The expected time between heartbeats to the consumer coordinator when using Kafka's group management facilities. Heartbeats are used to ensure that the consumer's session stays active and to facilitate rebalancing when new consumers join or leave the group. The value must be set lower than session.timeout.ms, but typically should be set no higher than 1/3 of that value. It can be adjusted even lower to control the expected time for normal rebalances. | 3000 | Integer | *camel.component.kafka.configuration.interceptor-classes* | Sets interceptors for producer or consumers. Producer interceptors have to be classes implementing {@link org.apache.kafka.clients.producer.ProducerInterceptor} Consumer interceptors have to be classes implementing {@link org.apache.kafka.clients.consumer.ConsumerInterceptor} Note that if you use Producer interceptor on a consumer it will throw a class cast exception in runtime | | String | *camel.component.kafka.configuration.kafka-header-deserializer* | Sets custom KafkaHeaderDeserializer for deserialization kafka headers values to camel headers values. | | KafkaHeaderDeserializer | *camel.component.kafka.configuration.kafka-header-serializer* | Sets custom KafkaHeaderDeserializer for serialization camel headers values to kafka headers values. | | KafkaHeaderSerializer | *camel.component.kafka.configuration.kerberos-before-relogin-min-time* | Login thread sleep time between refresh attempts. | 60000 | Integer | *camel.component.kafka.configuration.kerberos-init-cmd* | Kerberos kinit command path. Default is /usr/bin/kinit | /usr/bin/kinit | String | *camel.component.kafka.configuration.kerberos-principal-to-local-rules* | A list of rules for mapping from principal names to short names (typically operating system usernames). The rules are evaluated in order and the first rule that matches a principal name is used to map it to a short name. Any later rules in the list are ignored. By default, principal names of the form \\{username\\}/\\{hostname\\}@\\{REALM\\} are mapped to \\{username\\}. For more details on the format please see the security authorization and acls documentation..

Multiple values can be separated by comma | DEFAULT | String | *camel.component.kafka.configuration.kerberos-renew-jitter* | Percentage of random jitter added to the renewal time. | 0.05 | Double | *camel.component.kafka.configuration.kerberos-renew-window-factor* | Login thread will sleep until the specified window factor of time from last refresh to ticket's expiry has been reached, at which time it will try to renew the ticket. | 0.8 | Double | *camel.component.kafka.configuration.key* | The record key (or null if no key is specified). If this option has been configured then it take precedence over header {@link KafkaConstants#KEY} | | String | *camel.component.kafka.configuration.key-deserializer* | Deserializer class for key that implements the Deserializer interface. | org.apache.kafka.common.serialization.StringDeserializer | String | *camel.component.kafka.configuration.key-serializer-class* | The serializer class for keys (defaults to the same as for messages if nothing is given). | org.apache.kafka.common.serialization.StringSerializer | String | *camel.component.kafka.configuration.linger-ms* | The producer groups together any records that arrive in between request transmissions into a single batched request. Normally this occurs only under load when records arrive faster than they can be sent out. However in some circumstances the client may want to reduce the number of requests even under moderate load. This setting accomplishes this by adding a small amount of artificial delay—that is, rather than immediately sending out a record the producer will wait for up to the given delay to allow other records to be sent so that the sends can be batched together. This can be thought of as analogous to Nagle's algorithm in TCP. This setting gives the upper bound on the delay for batching: once we get batch.size worth of records for a partition it will be sent immediately regardless of this setting, however if we have fewer than this many bytes accumulated for this partition we will 'linger' for the specified time waiting for more records to show up. This setting defaults to 0 (i.e. no delay). Setting linger.ms=5, for example, would have the effect of reducing the number of requests sent but would add up to 5ms of latency to records sent in the absense of load. | 0 | Integer | *camel.component.kafka.configuration.max-block-ms* | The configuration controls how long sending to kafka will block. These methods can be blocked for multiple reasons. For e.g: buffer full, metadata unavailable.This configuration imposes maximum limit on the total time spent in fetching metadata, serialization of key and value, partitioning and allocation of buffer memory when doing a send(). In case of partitionsFor(), this configuration imposes a maximum time threshold on waiting for metadata | 60000 | Integer | *camel.component.kafka.configuration.max-in-flight-request* | The maximum number of unacknowledged requests the client will send on a single connection before blocking. Note that if this setting is set to be greater than 1 and there are failed sends, there is a risk of message re-ordering due to retries (i.e., if retries are enabled). | 5 | Integer | *camel.component.kafka.configuration.max-partition-fetch-bytes* | The maximum amount of data per-partition the server will return. The maximum total memory used for a request will be #partitions * max.partition.fetch.bytes. This size must be at least as large as the maximum message size the server allows or else it is possible for the producer to send messages larger than the consumer can fetch. If that happens, the consumer can get stuck trying to fetch a large message on a certain partition. | 1048576 | Integer | *camel.component.kafka.configuration.max-poll-interval-ms* | The maximum delay between invocations of poll() when using consumer group management. This places an upper bound on the amount of time that the consumer can be idle before fetching more records. If poll() is not called before expiration of this timeout, then the consumer is considered failed and the group will rebalance in order to reassign the partitions to another member. | | Long | *camel.component.kafka.configuration.max-poll-records* | The maximum number of records returned in a single call to poll() | 500 | Integer | *camel.component.kafka.configuration.max-request-size* | The maximum size of a request. This is also effectively a cap on the maximum record size. Note that the server has its own cap on record size which may be different from this. This setting will limit the number of record batches the producer will send in a single request to avoid sending huge requests. | 1048576 | Integer | *camel.component.kafka.configuration.metadata-max-age-ms* | The period of time in milliseconds after which we force a refresh of metadata even if we haven't seen any partition leadership changes to proactively discover any new brokers or partitions. | 300000 | Integer | *camel.component.kafka.configuration.metric-reporters* | A list of classes to use as metrics reporters. Implementing the MetricReporter interface allows plugging in classes that will be notified of new metric creation. The JmxReporter is always included to register JMX statistics. | | String | *camel.component.kafka.configuration.metrics-sample-window-ms* | The number of samples maintained to compute metrics. | 30000 | Integer | *camel.component.kafka.configuration.no-of-metrics-sample* | The number of samples maintained to compute metrics. | 2 | Integer | *camel.component.kafka.configuration.offset-repository* | The offset repository to use in order to locally store the offset of each partition of the topic. Defining one will disable the autocommit. | | StateRepository | *camel.component.kafka.configuration.partition-assignor* | The class name of the partition assignment strategy that the client will use to distribute partition ownership amongst consumer instances when group management is used | org.apache.kafka.clients.consumer.RangeAssignor | String | *camel.component.kafka.configuration.partition-key* | The partition to which the record will be sent (or null if no partition was specified). If this option has been configured then it take precedence over header {@link KafkaConstants#PARTITION_KEY} | | Integer | *camel.component.kafka.configuration.partitioner* | The partitioner class for partitioning messages amongst sub-topics. The default partitioner is based on the hash of the key. | org.apache.kafka.clients.producer.internals.DefaultPartitioner | String | *camel.component.kafka.configuration.poll-timeout-ms* | The timeout used when polling the KafkaConsumer. | 5000 | Long | *camel.component.kafka.configuration.producer-batch-size* | The producer will attempt to batch records together into fewer requests whenever multiple records are being sent to the same partition. This helps performance on both the client and the server. This configuration controls the default batch size in bytes. No attempt will be made to batch records larger than this size.Requests sent to brokers will contain multiple batches, one for each partition with data available to be sent.A small batch size will make batching less common and may reduce throughput (a batch size of zero will disable batching entirely). A very large batch size may use memory a bit more wastefully as we will always allocate a buffer of the specified batch size in anticipation of additional records. | 16384 | Integer | *camel.component.kafka.configuration.queue-buffering-max-messages* | The maximum number of unsent messages that can be queued up the producer when using async mode before either the producer must be blocked or data must be dropped. | 10000 | Integer | *camel.component.kafka.configuration.receive-buffer-bytes* | The size of the TCP receive buffer (SO_RCVBUF) to use when reading data. | 65536 | Integer | *camel.component.kafka.configuration.reconnect-backoff-max-ms* | The maximum amount of time in milliseconds to wait when reconnecting to a broker that has repeatedly failed to connect. If provided, the backoff per host will increase exponentially for each consecutive connection failure, up to this maximum. After calculating the backoff increase, 20% random jitter is added to avoid connection storms. | 1000 | Integer | *camel.component.kafka.configuration.reconnect-backoff-ms* | The amount of time to wait before attempting to reconnect to a given host. This avoids repeatedly connecting to a host in a tight loop. This backoff applies to all requests sent by the consumer to the broker. | 50 | Integer | *camel.component.kafka.configuration.record-metadata* | Whether the producer should store the {@link RecordMetadata} results from sending to Kafka. The results are stored in a {@link List} containing the {@link RecordMetadata} metadata's. The list is stored on a header with the key {@link KafkaConstants#KAFKA_RECORDMETA} | true | Boolean | *camel.component.kafka.configuration.request-required-acks* | The number of acknowledgments the producer requires the leader to have received before considering a request complete. This controls the durability of records that are sent. The following settings are common: acks=0 If set to zero then the producer will not wait for any acknowledgment from the server at all. The record will be immediately added to the socket buffer and considered sent. No guarantee can be made that the server has received the record in this case, and the retries configuration will not take effect (as the client won't generally know of any failures). The offset given back for each record will always be set to -1. acks=1 This will mean the leader will write the record to its local log but will respond without awaiting full acknowledgement from all followers. In this case should the leader fail immediately after acknowledging the record but before the followers have replicated it then the record will be lost. acks=all This means the leader will wait for the full set of in-sync replicas to acknowledge the record. This guarantees that the record will not be lost as long as at least one in-sync replica remains alive. This is the strongest available guarantee. | 1 | String | *camel.component.kafka.configuration.request-timeout-ms* | The amount of time the broker will wait trying to meet the request.required.acks requirement before sending back an error to the client. | 305000 | Integer | *camel.component.kafka.configuration.retries* | Setting a value greater than zero will cause the client to resend any record whose send fails with a potentially transient error. Note that this retry is no different than if the client resent the record upon receiving the error. Allowing retries will potentially change the ordering of records because if two records are sent to a single partition, and the first fails and is retried but the second succeeds, then the second record may appear first. | 0 | Integer | *camel.component.kafka.configuration.retry-backoff-ms* | Before each retry, the producer refreshes the metadata of relevant topics to see if a new leader has been elected. Since leader election takes a bit of time, this property specifies the amount of time that the producer waits before refreshing the metadata. | 100 | Integer | *camel.component.kafka.configuration.sasl-jaas-config* | Expose the kafka sasl.jaas.config parameter Example: org.apache.kafka.common.security.plain.PlainLoginModule required username=""USERNAME"" password=""PASSWORD""; | | String | *camel.component.kafka.configuration.sasl-kerberos-service-name* | The Kerberos principal name that Kafka runs as. This can be defined either in Kafka's JAAS config or in Kafka's config. | | String | *camel.component.kafka.configuration.sasl-mechanism* | The Simple Authentication and Security Layer (SASL) Mechanism used. For the valid values see \\http://www.iana.org/assignments/sasl-mechanisms/sasl-mechanisms.xhtml | GSSAPI | String | *camel.component.kafka.configuration.schema-registry-u-r-l* | URL of the Confluent Platform schema registry servers to use. The format is host1:port1,host2:port2. This is known as schema.registry.url in the Confluent Platform documentation. This option is only available in the Confluent Platform (not standard Apache Kafka) | | String | *camel.component.kafka.configuration.security-protocol* | Protocol used to communicate with brokers. SASL_PLAINTEXT, PLAINTEXT and SSL are supported | PLAINTEXT | String | *camel.component.kafka.configuration.seek-to* | Set if KafkaConsumer will read from beginning or end on startup: beginning : read from beginning end : read from end This is replacing the earlier property seekToBeginning | | String | *camel.component.kafka.configuration.send-buffer-bytes* | Socket write buffer size | 131072 | Integer | *camel.component.kafka.configuration.serializer-class* | The serializer class for messages. | org.apache.kafka.common.serialization.StringSerializer | String | *camel.component.kafka.configuration.session-timeout-ms* | The timeout used to detect failures when using Kafka's group management facilities. | 10000 | Integer | *camel.component.kafka.configuration.specific-avro-reader* | This enables the use of a specific Avro reader for use with the Confluent Platform schema registry and the io.confluent.kafka.serializers.KafkaAvroDeserializer. This option is only available in the Confluent Platform (not standard Apache Kafka) | false | Boolean | *camel.component.kafka.configuration.ssl-cipher-suites* | A list of cipher suites. This is a named combination of authentication, encryption, MAC and key exchange algorithm used to negotiate the security settings for a network connection using TLS or SSL network protocol.By default all the available cipher suites are supported. | | String | *camel.component.kafka.configuration.ssl-context-parameters* | SSL configuration using a Camel {@link SSLContextParameters} object. If configured it's applied before the other SSL endpoint parameters. | | SSLContextParameters | *camel.component.kafka.configuration.ssl-enabled-protocols* | The list of protocols enabled for SSL connections. TLSv1.2, TLSv1.1 and TLSv1 are enabled by default. | TLSv1.2,TLSv1.1,TLSv1 | String | *camel.component.kafka.configuration.ssl-endpoint-algorithm* | The endpoint identification algorithm to validate server hostname using server certificate. | | String | *camel.component.kafka.configuration.ssl-key-password* | The password of the private key in the key store file. This is optional for client. | | String | *camel.component.kafka.configuration.ssl-keymanager-algorithm* | The algorithm used by key manager factory for SSL connections. Default value is the key manager factory algorithm configured for the Java Virtual Machine. | SunX509 | String | *camel.component.kafka.configuration.ssl-keystore-location* | The location of the key store file. This is optional for client and can be used for two-way authentication for client. | | String | *camel.component.kafka.configuration.ssl-keystore-password* | The store password for the key store file.This is optional for client and only needed if ssl.keystore.location is configured. | | String | *camel.component.kafka.configuration.ssl-keystore-type* | The file format of the key store file. This is optional for client. Default value is JKS | JKS | String | *camel.component.kafka.configuration.ssl-protocol* | The SSL protocol used to generate the SSLContext. Default setting is TLS, which is fine for most cases. Allowed values in recent JVMs are TLS, TLSv1.1 and TLSv1.2. SSL, SSLv2 and SSLv3 may be supported in older JVMs, but their usage is discouraged due to known security vulnerabilities. | TLS | String | *camel.component.kafka.configuration.ssl-provider* | The name of the security provider used for SSL connections. Default value is the default security provider of the JVM. | | String | *camel.component.kafka.configuration.ssl-trustmanager-algorithm* | The algorithm used by trust manager factory for SSL connections. Default value is the trust manager factory algorithm configured for the Java Virtual Machine. | PKIX | String | *camel.component.kafka.configuration.ssl-truststore-location* | The location of the trust store file. | | String | *camel.component.kafka.configuration.ssl-truststore-password* | The password for the trust store file. | | String | *camel.component.kafka.configuration.ssl-truststore-type* | The file format of the trust store file. Default value is JKS. | JKS | String | *camel.component.kafka.configuration.topic* | Name of the topic to use. On the consumer you can use comma to separate multiple topics. A producer can only send a message to a single topic. | | String | *camel.component.kafka.configuration.topic-is-pattern* | Whether the topic is a pattern (regular expression). This can be used to subscribe to dynamic number of topics matching the pattern. | false | Boolean | *camel.component.kafka.configuration.value-deserializer* | Deserializer class for value that implements the Deserializer interface. | org.apache.kafka.common.serialization.StringDeserializer | String | *camel.component.kafka.configuration.worker-pool* | To use a custom worker pool for continue routing {@link Exchange} after kafka server has acknowledge the message that was sent to it from {@link KafkaProducer} using asynchronous non-blocking processing. | | ExecutorService | *camel.component.kafka.configuration.worker-pool-core-size* | Number of core threads for the worker pool for continue routing {@link Exchange} after kafka server has acknowledge the message that was sent to it from {@link KafkaProducer} using asynchronous non-blocking processing. | 10 | Integer | *camel.component.kafka.configuration.worker-pool-max-size* | Maximum number of threads for the worker pool for continue routing {@link Exchange} after kafka server has acknowledge the message that was sent to it from {@link KafkaProducer} using asynchronous non-blocking processing. | 20 | Integer | *camel.component.kafka.enabled* | Enable kafka component | true | Boolean | *camel.component.kafka.kafka-manual-commit-factory* | Factory to use for creating KafkaManualCommit instances. This allows to plugin a custom factory to create custom KafkaManualCommit instances in case special logic is needed when doing manual commits that deviates from the default implementation that comes out of the box. The option is a org.apache.camel.component.kafka.KafkaManualCommitFactory type. | | String | *camel.component.kafka.use-global-ssl-context-parameters* | Enable usage of global SSL context parameters. | false | Boolean | *camel.component.kafka.worker-pool* | To use a shared custom worker pool for continue routing Exchange after kafka server has acknowledge the message that was sent to it from KafkaProducer using asynchronous non-blocking processing. If using this option then you must handle the lifecycle of the thread pool to shut the pool down when no longer needed. The option is a java.util.concurrent.ExecutorService type. | | String |=== // spring-boot-auto-configure options: END For more information about Producer/Consumer configuration: http://kafka.apache.org/documentation.html#newconsumerconfigs[http://kafka.apache.org/documentation.html#newconsumerconfigs] http://kafka.apache.org/documentation.html#producerconfigs[http://kafka.apache.org/documentation.html#producerconfigs] == Message headers === Consumer headers The following headers are available when consuming messages from Kafka. [width=""100%"",cols=""2m,2m,1m,5"",options=""header""] |=== | Header constant | Header value | Type | Description | KafkaConstants.TOPIC | ""kafka.TOPIC"" | String | The topic from where the message originated | KafkaConstants.PARTITION | ""kafka.PARTITION"" | Integer | The partition where the message was stored | KafkaConstants.OFFSET | ""kafka.OFFSET"" | Long | The offset of the message | KafkaConstants.KEY | ""kafka.KEY"" | Object | The key of the message if configured | KafkaConstants.HEADERS | ""kafka.HEADERS"" | org.apache.kafka.common.header.Headers | The record headers | KafkaConstants.LAST_RECORD_BEFORE_COMMIT | ""kafka.LAST_RECORD_BEFORE_COMMIT"" | Boolean | Whether or not it's the last record before commit (only available if `autoCommitEnable` endpoint parameter is `false`) | KafkaConstants.MANUAL_COMMIT | ""CamelKafkaManualCommit"" | KafkaManualCommit | Can be used for forcing manual offset commit when using Kafka consumer. | |=== === Producer headers Before sending a message to Kafka you can configure the following headers. [width=""100%"",cols=""2m,2m,1m,5"",options=""header""] |=== | Header constant | Header value | Type | Description | KafkaConstants.KEY | ""kafka.KEY"" | Object | *Required* The key of the message in order to ensure that all related message goes in the same partition | KafkaConstants.OVERRIDE_TOPIC | ""kafka.OVERRIDE_TOPIC"" | String | The topic to which send the message (override and takes precedence), and the header is not preserved. | | KafkaConstants.PARTITION_KEY | ""kafka.PARTITION_KEY"" | Integer | Explicitly specify the partition (only used if the `KafkaConstants.KEY` header is defined) |=== If you want to send a message to a dynamic topic then use `KafkaConstants.OVERRIDE_TOPIC` as its used as a one-time header that are not send along the message, as its removed in the producer. After the message is sent to Kafka, the following headers are available [width=""100%"",cols=""2m,2m,1m,5"",options=""header""] |=== | Header constant | Header value | Type | Description | KafkaConstants.KAFKA_RECORDMETA | ""org.apache.kafka.clients.producer.RecordMetadata"" | List | The metadata (only configured if `recordMetadata` endpoint parameter is `true` |=== == Samples === Consuming messages from Kafka Here is the minimal route you need in order to read messages from Kafka. [source,java] ---- from(""kafka:test?brokers=localhost:9092"") .log(""Message received from Kafka : ${body}"") .log("" on the topic ${headers[kafka.TOPIC]}"") .log("" on the partition ${headers[kafka.PARTITION]}"") .log("" with the offset ${headers[kafka.OFFSET]}"") .log("" with the key ${headers[kafka.KEY]}"") ---- If you need to consume messages from multiple topics you can use a comma separated list of topic names [source,java] ---- from(""kafka:test,test1,test2?brokers=localhost:9092"") .log(""Message received from Kafka : ${body}"") .log("" on the topic ${headers[kafka.TOPIC]}"") .log("" on the partition ${headers[kafka.PARTITION]}"") .log("" with the offset ${headers[kafka.OFFSET]}"") .log("" with the key ${headers[kafka.KEY]}"") ---- When consuming messages from Kafka you can use your own offset management and not delegate this management to Kafka. In order to keep the offsets the component needs a `StateRepository` implementation such as `FileStateRepository`. This bean should be available in the registry. Here how to use it : [source,java] ---- // Create the repository in which the Kafka offsets will be persisted FileStateRepository repository = FileStateRepository.fileStateRepository(new File(""/path/to/repo.dat"")); // Bind this repository into the Camel registry Registry registry = createCamelRegistry(); registry.bind(""offsetRepo"", repository); // Configure the camel context DefaultCamelContext camelContext = new DefaultCamelContext(registry); camelContext.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from(""kafka:"" + TOPIC + ""?brokers=localhost:{{kafkaPort}}"" + // Setup the topic and broker address ""&groupId=A"" + // The consumer processor group ID ""&autoOffsetReset=earliest"" + // Ask to start from the beginning if we have unknown offset ""&offsetRepository=#offsetRepo"") // Keep the offsets in the previously configured repository .to(""mock:result""); } }); ---- === Producing messages to Kafka Here is the minimal route you need in order to write messages to Kafka. [source,java] ---- from(""direct:start"") .setBody(constant(""Message from Camel"")) // Message to send .setHeader(KafkaConstants.KEY, constant(""Camel"")) // Key of the message .to(""kafka:test?brokers=localhost:9092""); ---- == SSL configuration You have 2 different ways to configure the SSL communication on the Kafka` component. The first way is through the many SSL endpoint parameters [source,java] ---- from(""kafka:"" + TOPIC + ""?brokers=localhost:{{kafkaPort}}"" + ""&groupId=A"" + ""&sslKeystoreLocation=/path/to/keystore.jks"" + ""&sslKeystorePassword=changeit"" + ""&sslKeyPassword=changeit"" + ""&securityProtocol=SSL"") .to(""mock:result""); ---- The second way is to use the `sslContextParameters` endpoint parameter. [source,java] ---- // Configure the SSLContextParameters object KeyStoreParameters ksp = new KeyStoreParameters(); ksp.setResource(""/path/to/keystore.jks""); ksp.setPassword(""changeit""); KeyManagersParameters kmp = new KeyManagersParameters(); kmp.setKeyStore(ksp); kmp.setKeyPassword(""changeit""); SSLContextParameters scp = new SSLContextParameters(); scp.setKeyManagers(kmp); // Bind this SSLContextParameters into the Camel registry Registry registry = createCamelRegistry(); registry.bind(""ssl"", scp); // Configure the camel context DefaultCamelContext camelContext = new DefaultCamelContext(registry); camelContext.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from(""kafka:"" + TOPIC + ""?brokers=localhost:{{kafkaPort}}"" + // Setup the topic and broker address ""&groupId=A"" + // The consumer processor group ID ""&sslContextParameters=#ssl"" + // The security protocol ""&securityProtocol=SSL) // Reference the SSL configuration .to(""mock:result""); } }); ---- == Using the Kafka idempotent repository *Available from Camel 2.19* The `camel-kafka` library provides a Kafka topic-based idempotent repository. This repository stores broadcasts all changes to idempotent state (add/remove) in a Kafka topic, and populates a local in-memory cache for each repository's process instance through event sourcing. The topic used must be unique per idempotent repository instance. The mechanism does not have any requirements about the number of topic partitions; as the repository consumes from all partitions at the same time. It also does not have any requirements about the replication factor of the topic. Each repository instance that uses the topic (e.g. typically on different machines running in parallel) controls its own consumer group, so in a cluster of 10 Camel processes using the same topic each will control its own offset. On startup, the instance subscribes to the topic and rewinds the offset to the beginning, rebuilding the cache to the latest state. The cache will not be considered warmed up until one poll of `pollDurationMs` in length returns 0 records. Startup will not be completed until either the cache has warmed up, or 30 seconds go by; if the latter happens the idempotent repository may be in an inconsistent state until its consumer catches up to the end of the topic. A `KafkaIdempotentRepository` has the following properties: [width=""100%"",cols=""2m,5"",options=""header""] |=== | Property | Description | topic | The name of the Kafka topic to use to broadcast changes. (required) | bootstrapServers | The `bootstrap.servers` property on the internal Kafka producer and consumer. Use this as shorthand if not setting `consumerConfig` and `producerConfig`. If used, this component will apply sensible default configurations for the producer and consumer. | producerConfig | Sets the properties that will be used by the Kafka producer that broadcasts changes. Overrides `bootstrapServers`, so must define the Kafka `bootstrap.servers` property itself | consumerConfig | Sets the properties that will be used by the Kafka consumer that populates the cache from the topic. Overrides `bootstrapServers`, so must define the Kafka `bootstrap.servers` property itself | maxCacheSize | How many of the most recently used keys should be stored in memory (default 1000). | pollDurationMs | The poll duration of the Kafka consumer. The local caches are updated immediately. This value will affect how far behind other peers that update their caches from the topic are relative to the idempotent consumer instance that sent the cache action message. The default value of this is 100 ms. + If setting this value explicitly, be aware that there is a tradeoff between the remote cache liveness and the volume of network traffic between this repository's consumer and the Kafka brokers. The cache warmup process also depends on there being one poll that fetches nothing - this indicates that the stream has been consumed up to the current point. If the poll duration is excessively long for the rate at which messages are sent on the topic, there exists a possibility that the cache cannot be warmed up and will operate in an inconsistent state relative to its peers until it catches up. |=== The repository can be instantiated by defining the `topic` and `bootstrapServers`, or the `producerConfig` and `consumerConfig` property sets can be explicitly defined to enable features such as SSL/SASL. To use, this repository must be placed in the Camel registry, either manually or by registration as a bean in Spring/Blueprint, as it is `CamelContext` aware. Sample usage is as follows: [source,java] ---- KafkaIdempotentRepository kafkaIdempotentRepository = new KafkaIdempotentRepository(""idempotent-db-inserts"", ""localhost:9091""); SimpleRegistry registry = new SimpleRegistry(); registry.put(""insertDbIdemRepo"", kafkaIdempotentRepository); // must be registered in the registry, to enable access to the CamelContext CamelContext context = new CamelContext(registry); // later in RouteBuilder... from(""direct:performInsert"") .idempotentConsumer(header(""id"")).messageIdRepositoryRef(""insertDbIdemRepo"") // once-only insert into database .end() ---- In XML: [source,xml] ---- localhost:9091 localhost:9091 ---- == Using manual commit with Kafka consumer *Available as of Camel 2.21* By default the Kafka consumer will use auto commit, where the offset will be committed automatically in the background using a given interval. In case you want to force manual commits, you can use `KafkaManualCommit` API from the Camel Exchange, stored on the message header. This requires to turn on manual commits by either setting the option `allowManualCommit` to `true` on the `KafkaComponent` or on the endpoint, for example: [source,java] ---- KafkaComponent kafka = new KafkaComponent(); kafka.setAllowManualCommit(true); ... camelContext.addComponent(""kafka"", kafka); ---- You can then use the `KafkaManualCommit` from Java code such as a Camel `Processor`: [source,java] ---- public void process(Exchange exchange) { KafkaManualCommit manual = exchange.getIn().getHeader(KafkaConstants.MANUAL_COMMIT, KafkaManualCommit.class); manual.commitSync(); } ---- This will force a synchronous commit which will block until the commit is acknowledge on Kafka, or if it fails an exception is thrown. If you want to use a custom implementation of `KafkaManualCommit` then you can configure a custom `KafkaManualCommitFactory` on the `KafkaComponent` that creates instances of your custom implementation. == Kafka Headers propagation *Available as of Camel 2.22* When consuming messages from Kafka, headers will be propagated to camel exchange headers automatically. Producing flow backed by same behaviour - camel headers of particular exchange will be propagated to kafka message headers. Since kafka headers allows only `byte[]` values, in order camel exchnage header to be propagated its value should be serialized to `bytes[]`, otherwise header will be skipped. Following header value types are supported: `String`, `Integer`, `Long`, `Double`, `Boolean`, `byte[]`. Note: all headers propagated *from* kafka *to* camel exchange will contain `byte[]` value by default. In order to override default functionality uri parameters can be set: `kafkaHeaderDeserializer` for `from` route and `kafkaHeaderSerializer` for `to` route. Example: ``` from(""kafka:my_topic?kafkaHeaderDeserializer=#myDeserializer"") ... .to(""kafka:my_topic?kafkaHeaderSerializer=#mySerializer"") ``` By default all headers are being filtered by `KafkaHeaderFilterStrategy`. Strategy filters out headers which start with `Camel` or `org.apache.camel` prefixes. Default strategy can be overridden by using `headerFilterStrategy` uri parameter in both `to` and `from` routes: ``` from(""kafka:my_topic?headerFilterStrategy=#myStrategy"") ... .to(""kafka:my_topic?headerFilterStrategy=#myStrategy"") ``` `myStrategy` object should be subclass of `HeaderFilterStrategy` and must be placed in the Camel registry, either manually or by registration as a bean in Spring/Blueprint, as it is `CamelContext` aware. ",16163,True,3407.526579894393,median ":toc: = Stantinko Indicators of Compromise (IOCs) == Stantinko botnet adds cryptomining to its pool of criminal activities (blog) These IoCs are related to the blog https://www.welivesecurity.com/2019/11/26/stantinko-botnet-adds-cryptomining-criminal-activities/[_Stantinko botnet adds cryptomining to its pool of criminal activities_] published on https://www.welivesecurity.com[WeLiveSecurity] November 26th 2019. === ESET detection names - Win32/CoinMiner.Stantinko - Win64/CoinMiner.Stantinko === Hashes Hashes can be found in the following files: - SHA-1: link:cryptominer/samples.sha1[`samples.sha1`] - MD5: link:cryptominer/samples.md5[`samples.md5`] - SHA-256: link:cryptominer/samples.sha256[`samples.sha256`] === Filenames - `api-ms-win-crt-io-l1-1-0.dll` - `libcr64.dll` - `C:\\Windows\\TEMP\\%RANDOM%\\%RANDOM_GUID%.dll` === Mutex name and RC4 key - `3,141592653589793238462643` === YouTube URLs with mining proxy configuration data - `\\https://www.youtube.com/watch?v=kS1jXg99WiM` - `\\https://www.youtube.com/watch?v=70g4kw2iRGo` - `\\https://www.youtube.com/watch?v=cAW1xEpyr7Y` - `\\https://www.youtube.com/watch?v=6SSKQdE5Vjo` - `\\https://www.youtube.com/watch?v=fACKZewW22M` - `\\https://www.youtube.com/watch?v=FDQOa5zCv3s` - `\\https://www.youtube.com/watch?v=TpyOURRvFmE` - `\\https://www.youtube.com/watch?v=2fpiR4NIpsU` - `\\https://www.youtube.com/watch?v=TwnD0Kp_Ohc` - `\\https://www.youtube.com/watch?v=wJsbj8zPPNs` === IP addresses of mining proxies - 3.16.150[.]123 - 3.16.152[.]201 - 3.16.152[.]64 - 3.16.167[.]92 - 3.16.30[.]155 - 3.16.31[.]23 - 3.17.167[.]43 - 3.17.23[.]144 - 3.17.25[.]11 - 3.17.59[.]6 - 3.17.61[.]161 - 3.18.108[.]152 - 3.18.223[.]195 - 13.58.182[.]92 - 13.58.22[.]81 - 13.58.77[.]225 - 13.59.31[.]61 - 18.188.122[.]218 - 18.188.126[.]190 - 18.188.249[.]210 - 18.188.47[.]132 - 18.188.93[.]252 - 18.191.104[.]117 - 18.191.173[.]48 - 18.191.216[.]242 - 18.191.230[.]253 - 18.191.241[.]159 - 18.191.47[.]76 - 18.216.127[.]143 - 18.216.37[.]78 - 18.216.55[.]205 - 18.216.71[.]102 - 18.217.146[.]44 - 18.217.177[.]214 - 18.218.20[.]166 - 18.220.29[.]72 - 18.221.25[.]98 - 18.221.46[.]136 - 18.222.10[.]104 - 18.222.187[.]174 - 18.222.198[.]38 - 18.222.213[.]203 - 18.222.253[.]209 - 18.222.56[.]98 - 18.223.111[.]224 - 18.223.112[.]155 - 18.223.131[.]52 - 18.223.136[.]87 - 18.225.31[.]210 - 18.225.32[.]44 - 18.225.7[.]128 - 18.225.8[.]249 - 52.14.103[.]72 - 52.14.221[.]47 - 52.15.184[.]25 - 52.15.222[.]174 == Statinko -- Teddy Bear Surfing Out of Sight (white paper) These IoCs are related to ESET's investigation on Stantinko. The full report about Stantinko is available at https://www.welivesecurity.com/wp-content/uploads/2017/07/Stantinko.pdf. The condensed blog post about Stantinko is available at https://www.welivesecurity.com/2017/07/20/stantinko-massive-adware-campaign-operating-covertly-since-2012/. These IoCs are also available in MISP event format: link:stantinko.misp-event.json[`stantinko.misp-event.json`] === Samples .APIHelper.dll ---- 84A055D8E4BDF1F140C4DCA3D2D7738027E07115 ---- .APIHelper_64.dll ---- BCBC28219D47097FBCE312DA450B84079689A0BF ---- .bhctrl32.exe ---- 125CEDE073FC3578C9D4C92A858B92C6D551BB0E A2956B05909E48F82F6FC9A690A64D4F0B2A61C8 D40CAC5DB9A23B372E606039DCE080BCFB9830CC FE25D078DFD99091C3EF189567728BD087750FAE ---- .biosysrt.dll ---- 3A543E3CFE380AE404759FCCE4B3E25DE52246C9 ---- .bstreamsvc.dll ---- 1D50CF65D326545B02C3EAEF99FAEAAA5629AE94 C7A04F5A7A09D9674B2CA50EDAD882E050785169 EAE094FDA8D431CB8CDEFC9687C8B4CB1B7E2A22 ---- .bstreamsvc_setup.dll ---- B8AA1B3DEC9B4B16B6A4BC274C093EED09E2BC4C ---- .clearcache.dll ---- 899A71BAABFCF47F5FE31A651271D038C2619EDF ---- .create_certificate.dll ---- 729B6F4D97F76DCE0F474D7D9F5E15FDD01E4998 ---- .certificate.dll ---- DB83BE912A25D99F501212FED8FA45672D362E67 ---- .d3dadapter.dll ---- 11354E648E41529972E6696631E035CF8BF0C537 1817B2B958FE7FCE0D0383B8D304BD55A6FECEB2 1BAF0A6E8C9DDBDFFF825686C2BA7E846FB65AEC 272AECA0B66ED1DEA435059481C8EE7045E44E23 31883581FE416A454A00B223357ECAF6E4353497 31E119C3D252C2AE1C18E554DCF47ED359A67AD2 36E11C5BFA3C05094B3FBBA39697533F63B299DB 52D9D26EF37A3B42A0D68E4383B73FD4D2B10018 56696CA2E4C85541909391E086E7D934601656D8 587659A8AB5617594F8064EF16CAAD082A773C7A 84D9F7F46810B1ADD636B07C4068517AD1B3FD07 8843F69F530A712568567A2D53DA01889FF9ACB9 957C69E52E2A3A16838051598A7B2E5BA3D54836 ACAF69EFC397031A7CA14E8E4B6E2D9E9DE28892 D2770182CE996454AA8EAFA5C96629ACCF05A06A D6A59F6DD9E39EE26059C43D2E097A823770E161 F9DC53A63D721D0936BE8C04331E341AC2558162 ---- .d3dadapter dropper ---- B14AF8814FE0398FFA8F5B0D76141B576E5CCE27 FBDBABC6C3E274B99BDFDAB79E53B29ECCF114EF ---- .fdclient.dll ---- 0876F8D54F152B1ABA741004635C53A835007226 51196DD8D364947B17ACFA3EFCFC1AFA86CD44C3 886749473A29B887E8F8A79A7C3FB620D30BCB01 96B3A1FDFE1AA113B7791C15A57CFBBD360CC223 B35DA904E72868361954A27E87521EE4E0FD0AC6 B705F104DE0E8E43DA9AC13BA5F42DD3DA21037B D06DE631AAA7A7BC1FFFA12054111BEC2A7D838D ---- .FileTour related files ---- 06EB77205E4822A4369E9C7B43F4554248DD6FFA 2E9F4C6BD233799AA2AFEC9C440C737AE4114DDE 30139FB0B37472D02FE5ECB62F211CCFE727FD6D 40863793206684A021ABB1E24D524FDDF8410AB6 7167649EB03569C2643BCF2C2F2164EA0D803A8D 8E3D8606ED916152B8F70D5E38026569BB7A20C4 A5C3076F4E38A9E497F120558DB669FDD139E702 D274FD9C8AFC8FB2DAE8E81E4F6CC41592C385DF ---- .ghstore.exe ---- E2F2532632A0ACBC6367716F82F7B62D64B896B5 ---- .ihctrl32_setup.dll ---- C9C2D2239C5371DCD6A36AE66380B615578E5B04 ---- .ihctrl32.dll ---- 032B324368B3854F4EC96BE74E067D146B43F856 0B64F28DD56D4869ED7ECAEA81D0F7E6DCBEFA36 4FD7A5F602E4645EB8F21BAA127EDEB9C76CCB50 728718D1AD01B07FCD31C0A4FA2C975B98DB29F1 742EA38F09FF53626194D8B411E290B09F93EDA4 80C4A4FD10409742C10B4399AD7C31AFEA726A8D B6CFDA9777EEF218E36A1A082C175CB6121CDB48 BC126956059188E2155113D2F77D5FF632B9D420 CB89F13D6EFBB8EBA87AB3FE3AC92A0AA738AD2D D00C953FD7D6CB686036BB264D52F38C2CECEA76 F74ED6DFB1719924197459D7E5CFDF00568B86FB ---- .ir16_32.dll ---- 8EF4E038E14E2C853DD304DF78C3CF09176ADB65 962AA58834B2D071D3F8C68E893D3FDC2FEE32F3 9F79F982F8EEF45D5A1FC3120C5DEA2D8EC618A0 B85E4652910D413D19718B819736B44133FDB332 C269C83B3D18C01DAF9C296A198323889D339B9F C9F1232DC368A828F576D6F9E8922C0DF27A33DB E8D9F9A6BEC99BE13FFDF3D2F5EF74EF634EB508 ---- .kbdmai.dll ---- 0FA4A2C2F41056E071097BF9DB5312E820E3512A 199DA0C38EB00E495D864D95F078912EEB35639A 5287CE5827FFEEC6957F1F6DC769D25482479EE3 DA4634BD5B96519697D06D9A8F18B735302A65EA ---- .kbdmai dropper ---- 526B86CA02CCEAF5D23C467C1D1F81DD0A36E4B9 E79ACFBF8D339507373B892700B27B3B795E424F ---- .KBDMAI_ExtInstaller.dll ---- 343E52B0D30775305951252101526EAEDC8A0D01 D212F66683F29B5A88AFE2B6B9450DAE3DD73EB4 ---- .npapihelper.dll ---- 1ACCD83D48F041FF362C2B8F2DCF96D6F1583168 ---- .optsatadc.dll ---- 3B2D848030289F8F569C80193DD940FA3AE396C2 4D3A703DB690E975540D6D29CDAB2F75FBBCB61C ADE31CC1161C06A968B68C15E4CE249AE82BC35D BE756BA78F52061AE745FC3D01D97300F06F70F6 ---- .optsatadc_setup.dll ---- 326406A85486418B0DF5878B38A2436F11082411 ---- .remote_safe_surfing_flag ---- A9C96E00C1D1B7AAEE01C30719C5068BBE196B20 ---- .themctrl.dll ---- 03A5849E0DBE89E0727C8C37F4259623C9C131E3 544ED609F59C6FB2C96A566631293109172375F9 6004089B1678104252E02E272443A993106C912B 6B0FC0F7BCF63DB2778634644F5819E6247AD524 6DB4BE7100B317FD9CBC136DC95C4017F6D56612 F09352158B443FA3DB0567EF4147D94D37DBDD09 F3846AEF680EAA1931F75977B2ADD060D2BD3167 ---- .udsetup.exe ---- 52F44D45563944CF7735BCB6F0C448C3E9F19D04 ---- .udservice.exe ---- 0A7C1817A49E9C258DF7B3CFC416BC16A8D28C0B 352E05DC607AF2EE7CD3BD3FFCC546D3D29F786E ---- .udservice_dropper ---- 0146F1042B360C8080D4D05FF523C3B80AC88069 EF3AFF545C48F658C021DC3E5F574AED50BE726E ---- .vp9core.dll ---- C897A193A13A60CC98AAAD9CB9E18AECB68797DE FF9181C441AAA9108BC35B45B989B2725AD4BBF9 ---- .wbiosrvp.dll ---- 420A98F44832C11D4E56037F1F267207830BA03B 8750E5E2647C6A9DAB1E0AE60CC42246DA2186B2 F613948CE8F5358B9940EE22E9FCFC26F171637D ---- .wlanmgr.dll ---- 10E2B8A796766A6F83278799BE16B1BF47544F2B 12553394AE9C099D9079DF19F0680CBE5CD780D4 1C8D54F0DB1136FA067F88A0AD8F0A8225854E72 3AF1739A03B3A70705E44049B008DF34290CE3BD 6141110309EF5C08DEC5746DBFB25B6302C6D887 6FAE5E3BB8910FCCF89208E3377C8AAD802D9BF8 7743BCAB7A2D77F83197F31A01C754C73BE46EAA ---- .wsaudio.dll ---- 138ADDB8845C5F1999E2CCADB3BB7FC57D8ACCE8 2A9A15ED58CD54142E149DB48511B8FD4EFB1E89 5B54776D3C0085596ED7FF695A90B299B575DAFB 758FE5DF8EDAC61101AF35AA1F4440DBEC617F25 8BBA63FD06FC0948579A0F780EC4C0916F265D29 b84598b0329dde4b93fc32be2abac020f7b1e7d8 ---- .Linux/TrojanProxy.Stantinko.A ---- C55918ADC6D2E74809777B306E361EA01A35FC05 ---- .wsaudio_setup.dll ---- CD47C020BF420964BE329A3F2BC7FEE83BD2FACE ---- .yasetup.exe ---- D1F774D54BCC176AC33900085B27F62A1732B9B7 ---- .get_hdd.dll ---- F90BBF5444F42B383B26350231DFDA002911801A ---- .remove_plugins_installer.dll ---- AD4E55CF03F9C24ABE2C533EE33FACD7C70A2EDA C9DE95EC81BE649D796C73B5BC90CAC95C5EBBD8 ---- .brutplugin.dll ---- 5FA986F18BDDA5C6AD4C2F2CF9608752AC797377 ---- .facebook_bot.dll ---- D643F426B9FAF032FF5AF7D070D2E5115B3C2E46 ---- .radmin.dll ---- BFC7C0383CD87382575543C89E99EB41898F59EB ---- .zaxar.dll ---- C05D2646029DF48E262061DEF69DD8A55BF40F75 ---- .search_parser.dll ---- 2E726A679D32D6A29ECC7A9215409DEFA3085150 ---- .Malicious Browser Extensions ---- The Safe Surfing Teddy Protection ---- .The Safe Surfing NaCl binaries ---- 340622C8D335CDE73EEAA96F461440EDCB7D4C52 43A108A22925282D9AC02B8752EACF796B532C1E 49603FEC4DFA0AC5AF3300039522855920D84530 ---- === C&C servers [option=""header""] .Stantinko's C&C servers |===== |Family name | Component | Domain |Adstantinko | udsetup.exe | clients1.ultimate-discounter[.]com |Adstantinko | udsetup.exe | clients2.ultimate-discounter[.]com |Adstantinko | udsetup.exe | clients3.ultimate-discounter[.]com |Browser Extension | APIHelper | apihelper[.]org |Browser Extension | The Safe Surfing | safesurfing[.]me |Browser Extension | Teddy Protection (Lite) | teddy-protection[.]com |Browser Extension | Teddy Protection (Lite) | superbear[.]pro |Browser Extension | Teddy Protection (Lite) | teddysave[.]me |Browser Extension | Teddy Protection (Lite) | judgebear[.]pro |Browser Extension Downloader Service | ihctrl32.dll | icloudsrv[.]com |Browser Extension Downloader Service | ihctrl32.dll | icloudsrv[.]org |Browser Extension Downloader Service | ihctrl32.dll | icloudsrv[.]info |Browser Extension Downloader Service | ihctrl32.dll | icloudsrv[.]net |Browser Extension Downloader Service | themctrl.dll | robothemes[.]net |Browser Extension Downloader Service | themctrl.dll | tmrobo[.]com |Browser Extension Downloader Service | themctrl.dll | tmrobo[.]org |Browser Extension Downloader Service | opsatadc.dll | hdr-group[.]org |Browser Extension Downloader Service | opsatadc.dll | hdr-group[.]info |Browser Extension Downloader Service | opsatadc.dll | hdr-group[.]net |Linux Trojan Proxy | / | 185.28.22[.]22:81 |Linux Trojan Proxy | / | 195.226.218.[.]234:80 |Old Browser Extension Downloader Service | ir16_32.dll | wsslupdate[.]org |Old Plugin Downloader Service | d3dadapter.dll | d3dupdate[.]com |Old Plugin Downloader Service | d3dadapter.dll | mserrep[.]org |Old Plugin Downloader Service | KBDMAI.dll | kbdmai[.]net |Old Plugin Downloader Service | KBDMAI.dll | wupdateservice[.]us |Old Plugin Downloader Service | wlanmgr.dll | wadgeotrust[.]com |Plugin Downloader Service | wsaudio.dll | wsaudio[.]com |Plugin Downloader Service | wsaudio.dll | wsaudio[.]net |Plugin Downloader Service | wsaudio.dll | wsaudio[.]org |Plugin Downloader Service | bstreamsvc.dll | vp9codec[.]com |Plugin Downloader Service | bstreamsvc.dll | vp9codec[.]net |Plugin Downloader Service | wbiosrvp.dll | biosysltd[.]com |Plugin Downloader Service | wbiosrvp.dll | biosysltd[.]org |PDS Plugin | get_hdd.dll | 185.28.22[.]22 |PDS Plugin | search_parser.dll | hxxp://raw.githubusercontent.com/brenev/collection/master/index |PDS Plugin | brut_plugin.dll | 185.28.22[.]22 |PDS Plugin | facebook_bot.dll | 185.28.22[.]22 |PDS Plugin | radmin.dll | 93.188.161[.]17:8000 |Stantinko Installer | udservice.exe | update.ultimate-discounter[.]com |Stantinko Installer | udservice.exe | udiscount[.]net |Stantinko Installer | udservice.exe | ultimate-discounter[.]org |Stantinko Installer | udservice.exe | upd-discounter[.]com |Stantinko Installer | udservice.exe | udiscounter[.]org |Stantinko Installer | udservice.exe | wannaupdate[.]com |Stantinko Installer | ghstore.exe | ghosterystore[.]com |Stantinko Installer | bhctrl32.exe | nvccupdate[.]com |Stantinko Installer | redisd.exe | rdsbase[.]com |===== ==== Stantinko GitHub repositories ---- hxxps://www.github.com/brenev/collection hxxps://www.github.com/svetlanachudinovskih/core hxxps://www.github.com/alexandra-ivanyan/png hxxps://www.github.com/romochka-shevchenko-2015/rebranding hxxps://www.github.com/elina-golubeva/style hxxps://www.github.com/kurenkov2014/attachments hxxps://www.github.com/lenusyashparteeva/losed_data hxxps://www.github.com/varvarakayusova/images hxxps://www.github.com/anatoly-mescheryakov/icons hxxps://www.github.com/vlabygina/clipart hxxps://www.github.com/grishenka-kobzar/promo hxxps://www.github.com/kabanovmihail/static hxxps://www.github.com/shapovalovnikolayy/static hxxps://www.github.com/SaintJson/core hxxps://www.github.com/umnoffvladislaw/core ---- ==== IP Addresses ---- 13.58.23[.]11 13.58.249[.]138 18.220.21[.]112 37.97.245[.]128 62.109.0[.]227 80.82.67[.]154 80.87.202[.]246 82.146.59[.]86 85.17.194[.]202 88.99.154[.]39 89.108.124[.]228 91.206.30[.]108 91.206.30[.]109 93.188.161[.]17 95.213.235[.]197 95.46.98[.]12 104.237.4[.]37 107.174.224[.]254 107.181.174[.]28 136.144.141[.]253 144.217.240[.]28 149.56.201[.]76 178.20.157[.]140 178.20.157[.]187 178.20.157[.]189 178.20.157[.]227 178.20.159[.]56 178.20.159[.]77 178.20.159[.]89 185.118.164[.]190 185.125.218[.]74 185.127.24[.]151 185.28.22[.]22 185.28.22[.]69 185.47.62[.]128 185.48.239[.]11 185.86.76[.]113 195.226.218[.]234 204.155.30[.]72 210.16.101[.]206 217.12.203[.]18 ---- ==== List of compromised websites with their date of first appearance (Search parser C&C) ---- Jan 21, 2014 | hxxp://www.corsionlinemtpromozione.it/images/banners/b1/index.php Jan 21, 2014 | hxxp://xn--elprincipenorteo-lub.com.ar/images/banners/b1/index.php Jan 21, 2014 | hxxp://www.ucguabira.com/images/banners/b1/index.php Jan 21, 2014 | hxxp://www.unioncasa.org/images/banners/b1/index.php Jan 21, 2014 | hxxp://localhost/searchparser/index.php Jan 21, 2014 | hxxp://www.unique7000.org/en/images/banners/b1/index.php Feb 19, 2014 | hxxp://www.sfcu.com.au/sfcu/images/banners/b1/index.php Feb 19, 2014 | hxxp://eventsbyexcellence.com/photography/images/banners/b1/index.php Feb 19, 2014 | hxxp://grupoportusalud.net/images/banners/b1/index.php Feb 19, 2014 | hxxp://missionlocalenyonspierrelatte.com/images/banners/b1/index.php Feb 19, 2014 | hxxp://talsma-co.nl/images/banners/b1/index.php Nov 5, 2014 | hxxp://scorzapesquisa.net/site/images/banners/b1/index.php Nov 5, 2014 | hxxp://fotopercepcja.pl/images/banners/b1/index.php Apr 16, 2015 | hxxp://cdvet.ch/images/banners/b1/index.php Apr 16, 2015 | hxxp://www.menicon.fr/porteurs/images/banners/b1/index.php Apr 16, 2015 | hxxp://topperclean.nl/images/banners/b1/index.php Apr 16, 2015 | hxxp://iguabaonline.com.br/quasar/images/banners/b1/index.php Apr 17, 2015 | hxxp://hlcl.org/joomla15/images/banners/b1/index.php Apr 27, 2015 | hxxp://www.corsionlinemtpromozione.it/frigocontact/images/banners/b1/index.php Apr 27, 2015 | hxxp://lucerne.websitewelcome.com/~trinityc/images/banners/b1/index.php Apr 27, 2015 | hxxp://portal.antreprenor.upb.ro/images/banners/b1/index.php Apr 27, 2015 | hxxp://gruppo89.org/images/banners/b1/index.php Apr 27, 2015 | hxxp://79.170.44.132/nn-projects.co.uk/images/banners/b1/index.php Apr 27, 2015 | hxxp://veterinariostijuana.com/images/banners/b1/index.php May 30, 2015 | hxxp://xado1.md/images/banners/b1/index.php Jun 10, 2015 | hxxp://z272081.infobox.ru/images/banners/b1/index.php Jun 10, 2015 | hxxp://oyqrznx.wwwhl.ru/2014/images/banners/b1/index.php Jun 23, 2015 | hxxp://bernadettejansen.nl/site/images/banners/b1/index.php Jun 23, 2015 | hxxp://srpskicetnickipokret.org/scp/images/banners/b1/index.php Jun 23, 2015 | hxxp://blau-weiss-grenzenlos.de/images/banners/b1/index.php Aug 5, 2015 | hxxp://liceosilvestri.it/cms/images/banners/b1/index.php Aug 10, 2015 | hxxp://esportesnovasoure.com.br/images/banners/b1/index.php Aug 10, 2015 | hxxp://hotel-idol.com/tr/images/banners/b1/index.php Aug 24, 2015 | hxxp://wiewiese.bauernhof-urlaub.or.at/images/banners/b1/index.php Aug 24, 2015 | hxxp://www.swrs-weinsberg.de/images/banners/b1/index.php Aug 27, 2015 | hxxp://hohnstorf-basketball.de/alt/images/banners/b1/index.php Nov 26, 2015 | hxxp://www.ismailagenturen.com/images/banners/b1/index.php Nov 26, 2015 | hxxp://judoclub2haine.be/images/banners/b1/index.php Nov 26, 2015 | hxxp://moradiaecidadania.org.br/images/banners/b1/index.php Nov 26, 2015 | hxxp://romsee-stavelot-romsee.be/images/banners/b1/index.php Nov 26, 2015 | hxxp://parafia-srokowo.pl/images/banners/b1/index.php Dec 4, 2015 | hxxp://soymocano54.com/images/banners/b1/index.php Dec 4, 2015 | hxxp://sleepatastridlindgrensworld.se/images/banners/b1/index.php Dec 4, 2015 | hxxp://antalyainsaatdergisi.com/images/banners/b1/index.php Dec 4, 2015 | hxxp://www2.karate-st-georgen.at/images/banners/b1/index.php Feb 23, 2016 | hxxp://ns2.huespedvirtualserver.com/images/banners/b1/index.php Feb 24, 2016 | hxxp://www.uvdr-vg.hr/images/banners/b1/index.php Feb 24, 2016 | hxxp://jason.shigadigsample.com/images/banners/b1/index.php Feb 24, 2016 | hxxp://informatikundgesellschaft.de/joomla/images/banners/b1/index.php Apr 20, 2016 | hxxp://scuolasanfrancescodassisi.net/images/banners/b1/index.php Apr 20, 2016 | hxxp://gesund-bewegen.ch/cms/images/banners/b1/index.php Apr 20, 2016 | hxxp://quali-kleen.com/taste/images/banners/b1/index.php Apr 20, 2016 | hxxp://kevin-drieschner.de/feuerwehr_cms/images/banners/b1/index.php Apr 20, 2016 | hxxp://sv-limbach.de/images/banners/b1/index.php Apr 20, 2016 | hxxp://wittmund-restaurant-residenz.de/images/banners/b1/index.php Apr 20, 2016 | hxxp://old.novedvory.eu/dokumenty/banners/b1/index.php Apr 20, 2016 | hxxp://www.parkbetreuung-margareten.at/cms/images/banners/b1/index.php Apr 20, 2016 | hxxp://www.lambertrentals.com/portal/images/banners/b1/index.php Apr 20, 2016 | hxxp://www.goldundpartner.at/images/banners/b1/index.php Apr 20, 2016 | hxxp://egypttoursgate.com/family-holidays-luxury-vacations/images/banners/b1/index.php Apr 20, 2016 | hxxp://pepijnenvalerie.nl/joomla/images/banners/b1/index.php Apr 20, 2016 | hxxp://kmz-buchen.de/joomla/images/banners/b1/index.php May 25, 2016 | hxxp://mobilhome.montourey.free.fr/images/banners/b1/index.php Jun 23, 2016 | hxxp://sailbajaadventures.com/images/banners/b1/index.php Jun 23, 2016 | hxxp://weddingsbeautiful.com.mx/weddings/images/banners/b1/index.php Jul 1, 2016 | hxxp://s17drohobych.freehostia.com/images/banners/b1/index.php Jul 1, 2016 | hxxp://zharyk.com.kz/rus/images/banners/b1/index.php Jul 4, 2016 | hxxp://otmetka5ballov.ru/images/banners/b1/index.php Jul 18, 2016 | hxxp://parafia-srokowo.pcspace.pl/images/banners/b1/index.php Jul 18, 2016 | hxxp://www.florestal.gov.br/pngf/images/banners/b1/index.php Jul 18, 2016 | hxxp://multfestas.com.br/2013/images/banners/b1/index.php Jul 31, 2016 | hxxp://asti.bplaced.net/images/banners/b1/index.php Aug 4, 2016 | hxxp://yorkshire-chimneys.co.uk/images/banners/b1/index.php Aug 4, 2016 | hxxp://regionarequipa.gob.pe/dependencias/grcet/images/banners/b1/index.php Aug 4, 2016 | hxxp://pescarafclive.altervista.org/images/banners/b1/index.php Aug 4, 2016 | hxxp://www.powisstreetdentalpractice.com/images/banners/b1/index.php Aug 4, 2016 | hxxp://mytrade-agriculture.com/images/banners/b1/index.php Aug 4, 2016 | hxxp://alexincerti.xoom.it/images/banners/b1/index.php Aug 9, 2016 | hxxp://zarin-daneh.com/images/banners/b1/index.php Aug 23, 2016 | hxxp://explora.ulagos.cl/cienciaviva/images/banners/b1/index.php Aug 26, 2016 | hxxp://d2062745.instant.xoom.it/siteapps/66587/htdocs/images/banners/b1/index.php Aug 26, 2016 | hxxp://waldwichtel-haemelerwald.de/images/banners/b1/index.php Sep 2, 2016 | hxxp://royerodistrilab.com/nelsonroyero/images/banners/b1/index.php Sep 12, 2016 | hxxp://152.74.9.14/UNITEP/images/banners/b1/index.php Sep 12, 2016 | hxxp://vinculacion.coparmexcoahuila.org.mx/images/banners/b1/index.php Sep 12, 2016 | hxxp://kreds19-frederikshavn.dk/images/banners/b1/index.php Sep 12, 2016 | hxxp://mult.chandra.ac.th/cw/ge/images/banners/b1/index.php Sep 13, 2016 | hxxp://m2mobili.com/images/banners/b1/index.php Sep 13, 2016 | hxxp://rha93.free.fr/images/banners/b1/index.php Sep 16, 2016 | hxxp://l2campus.com/images/banners/b1/index.php Oct 5, 2016 | hxxp://codigosurbanos.com/v4/images/banners/b1/index.php Oct 6, 2016 | hxxp://codigosurbanos.com/v4/images/banners/b1/index_n.php Oct 6, 2016 | hxxp://feuerwehr-hartenstein.de/images/banners/b1/index.php Oct 7, 2016 | hxxp://st-johannesstift.de/images/banners/b1/index.php Oct 7, 2016 | hxxp://scrisoaredelamosul.ro/santa/images/banners/b1/index.php Oct 7, 2016 | hxxp://oneshote.com/Site/joomla/images/banners/b1/index.php Oct 13, 2016 | hxxp://conceptosgrupocreativo.com/visionamosSalud/images/banners/b1/index.php Oct 14, 2016 | hxxp://www.tangosex.it/images/banners/b1/index.php Oct 17, 2016 | hxxp://smksoretulungagung.sch.id/images/banners/b1/index.php Oct 19, 2016 | hxxp://shapinglivesconference.com/images/banners/b1/index.php Oct 19, 2016 | hxxp://vn-net29.homedns.org/fewo-primbs/images/banners/b1/index.php Oct 20, 2016 | hxxp://hinanumbufoundationgh.org/images/banners/b1/index.php Oct 20, 2016 | hxxp://dorazio.altervista.org/images/banners/b1/index.php Oct 20, 2016 | hxxp://k3bweb78.altervista.org/images/banners/b1/index.php Oct 20, 2016 | hxxp://pepekswiata.com.pl/starealejare/images/banners/b1/index.php Oct 20, 2016 | hxxp://www.chantalligraphics.com/health101.old/images/banners/b1/index.php Oct 20, 2016 | hxxp://banchio.com/pendientes/images/banners/b1/index.php Oct 20, 2016 | hxxp://southswimming.com/content/images/banners/b1/index.php Oct 20, 2016 | hxxp://edomerlomat.altervista.org/images/banners/b1/index.php Oct 24, 2016 | hxxp://roanokecares.com/images/banners/b1/index.php Oct 24, 2016 | hxxp://cadexchuquisaca.org.bo/images/banners/b1/index.php Oct 25, 2016 | hxxp://laboratoriochimicoveneto.it/lcv/images/banners/b1/index.php Oct 25, 2016 | hxxp://142-4-18-114.unifiedlayer.com/images/banners/b1/index.php Oct 25, 2016 | hxxp://bobonana.com/familien/images/banners/b1/index.php Oct 26, 2016 | hxxp://panaderiasantalibrada.com/main/images/banners/b1/index.php Oct 26, 2016 | hxxp://notre370z.com/images/banners/b1/index.php Oct 26, 2016 | hxxp://barangayugong.com/images/banners/b1/index.php Nov 3, 2016 | hxxp://alkiviadistours.gr/tour/images/banners/b1/index.php Nov 8, 2016 | hxxp://syl-diavitikon-nthess.gr/images/banners/b1/index.php Nov 8, 2016 | hxxp://lksavvas.gr/images/banners/b1/index.php Nov 9, 2016 | hxxp://tagaras.gr/images/banners/b1/index.php Nov 9, 2016 | hxxp://debian.itbiz.gr/enoria_kastaneris/images/banners/b1/index.php Nov 9, 2016 | hxxp://energymix.xp3.biz/joomla/images/banners/b1/index.php Nov 10, 2016 | hxxp://archiv.nezavisli-zruc.cz/images/banners/b1/index.php Dec 1, 2016 | hxxp://kapatex.iluze.com/images/banners/b1/index.php Dec 15, 2016 | hxxp://derecskeikutyaiskola.hu/images/banners/b1/index.php Dec 15, 2016 | hxxp://alhwaidi4hybrid.com/ar/images/banners/b1/index.php Dec 15, 2016 | hxxp://mst.etravelsystem.com/eztproperty/images/banners/b1/index.php Dec 15, 2016 | hxxp://alzwea.com/itech-iraq.com/images/banners/b1/index.php Dec 20, 2016 | hxxp://zawodnicy.baseball.pl/images/banners/b1/index.php Dec 21, 2016 | hxxp://intranet2.marne.chambagri.fr/joomla/images/banners/b1/index.php Dec 21, 2016 | hxxp://www.daydream-lab.com/flsh/main/images/banners/b1/index.php Dec 21, 2016 | hxxp://rouken.sakura.ne.jp/fittest/images/mod.php Dec 21, 2016 | hxxp://rouken.sakura.ne.jp/fittest/images/banners/b1/index.php Dec 21, 2016 | hxxp://asandoosh.com/images/banners/b1/index.php Dec 21, 2016 | hxxp://smabugisiah.edu.my/images/banners/b1/index.php Dec 26, 2016 | hxxp://alhayat-aljadedah.com/images/banners/b1/index.php Dec 26, 2016 | hxxp://leadershipacademy.ps/english/images/banners/b1/index.php Dec 26, 2016 | hxxp://www.agencija-jajce.ba/arabic/images/banners/b1/index.php Dec 26, 2016 | hxxp://vanocnidarky.provsechny.net/images/banners/b1/index.php Dec 26, 2016 | hxxp://millerjw.com/czechpoint/images/banners/b1/index.php Dec 26, 2016 | hxxp://edomerlomat.altervista.org/images/banners/b1/index.php Dec 26, 2016 | hxxp://krystiank.home.pl/autoinstalator/joomla15/images/banners/b1/index.php Dec 27, 2016 | hxxp://tommasobocchetti.it/images/banners/b1/index.php Jan 30, 2017 | hxxp://vmedia.mk/GinekomedikaCalculators/images/banners/b1/index.php Jan 30, 2017 | hxxp://xn----7sbpbmda7aknrei7dwb9f.xn--p1ai/images/banners/b1/index.php Jan 30, 2017 | hxxp://vehicleteams.scripts.mit.edu/home/images/banners/b1/index.php Jan 30, 2017 | hxxp://dvz.ppi.net.ua/images/banners/b1/index.php Jan 31, 2017 | hxxp://irina-petrenko.by/images/banners/b1/index.php Jan 31, 2017 | hxxp://usreturns.com/images/banners/b1/index.php Jan 31, 2017 | hxxp://wolnywww.instytutslowacki.pl/images/banners/b1/index.php Jan 31, 2017 | hxxp://www.kalamari-notes.gr/joomla/images/banners/b1/index.php Jan 31, 2017 | hxxp://bukaeva.lg.ua/images/banners/b1/index.php Jan 31, 2017 | hxxp://xier.avalon.biz.ua/images/banners/b1/index.php Feb 15, 2017 | hxxp://xray.bmc.uu.se/spb/images/banners/b1/index.php Feb 15, 2017 | hxxp://aupair-germany.eu/inhalt/images/banners/b1/index.php Feb 15, 2017 | hxxp://vicaweb.talentoshow.com/Joomla/images/banners/b1/index.php Feb 16, 2017 | hxxp://yik.edu.my/sekolah/mspp/images/banners/b1/index.php Feb 16, 2017 | hxxp://treningmentalny.home.pl/m_dddd/images/banners/b1/index.php Mar 16, 2017 | hxxp://the-dreamweaver.net/portal/images/banners/b1/index.php Mar 16, 2017 | hxxp://eki.szie.hu/erasmusip/images/banners/b1/index.php Mar 16, 2017 | hxxp://erasmus.sp9.slupsk.pl/images/banners/b1/index.php Apr 3, 2017 | hxxp://sceptretoursandtravel.com/images/banners/b1/index.php Apr 25, 2017 | hxxp://alcaldiadematurin.gob.ve/portal3/images/banners/b1/index.php Apr 25, 2017 | hxxp://thegamerszone-mgc.com/images/banners/b1/index.php May 8, 2017 | hxxp://banueventsolutions.com/images/banners/b1/index.php May 23, 2017 | hxxp://kryonschule-ahaus.de/images/banners/b1/index.php May 23, 2017 | hxxp://aklcosmetics.com.au/images/banners/b1/index.php May 24, 2017 | hxxp://lotto4phone.altervista.org/images/banners/b1/index.php May 25, 2017 | hxxp://tim-johnson.com/images/banners/b1/index.php May 25, 2017 | hxxp://scrapbook-stickers.com/images/banners/b1/index.php May 26, 2017 | hxxp://doscerodesign.com/hele/images/banners/b1/index.php ---- ==== FileTour click-fraud doorway websites ---- hxxp://good-journal.net hxxp://nano-news.info hxxp://newssocial.org hxxp://news-true.net ---- ==== FileTour click-fraud bitly redirections ---- hxxps://bitly.com/2mfUhWn2 hxxps://bitly.com/2lzYhUo ---- === Windows Artifacts ==== Mutexes ---- Global\\BitStreamSvc Global\\D3DAdapter_ServiceEvent Global\\Intel_hctrl32 Global\\KBDMAIServiceEvent Global\\Kbdmai_ServiceEvent Global\\OptimizeSataDevices Global\\ServiceLibEvent Global\\ThemeControl Global\\WBiosrvp Global\\Wlan_Manager_Initialize Global\\Wsaudio_Initialize ---- ==== Windows Registry keys ---- HKLM\\SYSTEM\\CurrentControlSet\\Services\\BitStreamSvc\\ HKLM\\SYSTEM\\CurrentControlSet\\services\\Bonjoiur Host Controller\\ HKLM\\SYSTEM\\CurrentControlSet\\services\\Coupons Browser Update Service\\ HKLM\\SYSTEM\\CurrentControlSet\\services\\d3dadapter\\ HKLM\\SYSTEM\\CurrentControlSet\\Services\\Ghostery Storage Server\\ HKLM\\SYSTEM\\CurrentControlSet\\services\\ihctrl32\\ HKLM\\SYSTEM\\CurrentControlSet\\services\\ir16_32\\ HKLM\\SYSTEM\\CurrentControlSet\\services\\KBDMAI\\ HKLM\\SYSTEM\\CurrentControlSet\\Services\\optsatadc\\ HKLM\\SYSTEM\\CurrentControlSet\\services\\themctrl\\ HKLM\\SYSTEM\\CurrentControlSet\\Services\\wbiosrvp\\ HKLM\\SYSTEM\\CurrentControlSet\\Services\\wlanmgr\\ HKLM\\SYSTEM\\CurrentControlSet\\Services\\wsaudio\\ HKLM\\SOFTWARE\\Classes\\[0-9A-F]{4}.FieldListCtrl.1\\ HKLM\\SOFTWARE\\Classes\\[0-9A-F]{4}.CoreClass.2\\ ---- ==== PDB Paths ---- D:\\work\\brut\\cms\\facebook\\facebookbot\\Release\\facebookbot.pdb D:\\work\\service\\plugins\\Release\\get_hdd_serial_number.pdb D:\\work\\service\\plugins\\Release\\remove_plugins_installer.pdb D:\\work\\service\\plugins\\Release\\remove_zaxar.pdb D:\\work\\service\\plugins\\Release\\reset_safesurfing_flag.pdb D:\\work\\service\\service\\Release\\bstreamsvc.pdb D:\\work\\service\\service\\Release\\bstreamsvc_setup.pdb D:\\work\\service\\service\\Release DRTIPROV\\ir16_32.pdb D:\\work\\service\\service\\Release\\first_service.pdb D:\\work\\service\\service\\Release\\first_service_setup.pdb D:\\work\\service\\service\\Release\\ihctrl32.pdb D:\\work\\service\\service\\Release\\ihctrl32_setup.pdb D:\\work\\service\\service\\Release\\ir16_32.pdb D:\\work\\service\\service\\Release\\optsatadc.pdb D:\\work\\service\\service\\Release\\optsatadc_setup.pdb D:\\work\\service\\service\\Release\\themctrl.pdb D:\\work\\service\\service\\Release\\themctrl_setup.pdb D:\\work\\service\\service\\Release\\wbiosrvp_setup.pdb D:\\work\\service\\service\\Release\\wsaudio_setup.pdb D:\\work\\ultdr\\udsetup\\Release\\udsetup_winapi_morphed.pdb Z:\\source\\service\\Release\\ir16_32.pdb Z:\\source\\service\\Release\\setup_serv.pdb ---- === The Safe Surfing injected script [source, javascript] ---- var _________subscribe_checker = { _detect_text: [""((\\u0443\\u0441\\u043b\\u043e\\u0432|\\u0443\\u043f\\u0440\\u0430\\u0432\\u043b)(.*)\\u043f\\u043e\\u0434\\u043f\\u0438\\u0441\\u043a)|(\\u043f\\u043e\\u0434\\u043f\\u0438\\u0441\\u043a(.*)(\\u0443\\u0441\\u043b\\u043e\\u0432|\\u0443\\u043f\\u0440\\u0430\\u0432\\u043b))"", ""\\u043f\\u0440\\u0430\\u0432\\u0438\\u043b(.*)\\u043f\\u043e\\u0434\\u043f\\u0438\\u0441\\u043a"", ""\\u0441\\u0442\\u043e\\u0438\\u043c\\u043e\\u0441(.*)\\u0443\\u0441\\u043b\\u0443\\u0433""], _detected_text_count: 0, _hrefs: [], _description_regex: /(\\u0441\\u043c\\u0441|sms)[- ]\\u0441\\u043e\\u043e\\u0431\\u0449\\u0435\\u043d(.*)\\u0441(.*)(\\u0441\\u043b\\u043e\\u0432|\\u0442\\u0435\\u043a\\u0441\\u0442|\\u043a\\u043e\\u043c\\u0430\\u043d\\u0434)(.*)(\\u0441\\u0442\\u043e\\u043f|stop)/, check: function() { if (this.isExcluded()) return !1; this._hrefs = document.links; return 1 == this.checkSiteBySubscribeTextInUrls() ? (this.send(""by_text_in_urls""), !0) : 1 == this.checkSiteBySubscribeDescriptionText() ? (this.send(""by_subscribe_text""), !0) : !1 }, isExcluded: function() { return ""http:"" != document.location.protocol && ""https:"" != document.location.protocol || this.isExludedDomain(document.location.host) || this.isExludedDomain(document.referrer) ? !0 : this.isExcludedUrl() }, checkSiteBySubscribeTextInUrls: function() { for (var a in this._hrefs) if (this._hrefs[a].href && this.isSubscribeText(this._hrefs[a].textContent) && 0 == this._detect_text.length) return !0; return !1 }, checkSiteBySubscribeDescriptionText: function() { if (0 == this._detected_text_count) return !1; var a = document.body.textContent.split("".""), b; for (b in a) if (a[b].toLocaleLowerCase) { var c = a[b].toLocaleLowerCase().replace(/(\\n)/g, "" "").replace(/(\\r)/g, """"); if (this._description_regex.test(c)) return !0 } return !1 }, isExludedDomain: function(a) { var b = ""mts rt megafonpro megafon mpoisk mail google yandex ya rambler youtube dfiles turbobit prom zakupka pravo letitbit ozon urokitio kismia webnice toy mdmbank tele2 roboforex share4web 7do dixy kiino 4allforum delo-press raskachaem satu spmag yugcontract narodnoe materinstvo dimonvideo kia-club deal icloud littlebyte maxpark 24video vdgb trud appsruel tiu blanker aucland office ontabfile microsoft shopotam shareflare autoportal stilagoby malina depositfiles hitfile crocs telecom effectfree forum.calorizator.ru traektoria cdek takko circ-a tinydeal otzyv mamba rusfolder irn labirint vip-file 10.150.0.104"".split("" ""); a = a.split("".""); if (2 <= a.length) for (var c in b) if (a[a.length - 2] == b[c]) return !0; return !1 }, isExcludedUrl: function() { for (var a = [""a-elite/scrpop-promka/psr-""], b = 0; b < a.length; ++b) if (-1 != document.location.pathname.indexOf(a[b])) return !0; return !1 }, isSubscribeText: function(a) { a = a.toLowerCase().replace(/(\\n)/g, "" "").replace(/(\\r)/g, """"); for (var b in this._detect_text) if (""string"" === typeof this._detect_text[b] && 0 != this._detect_text[b].length && (new RegExp(this._detect_text[b].toLowerCase())).test(a)) return this._detect_text.splice(b, 1), ++this._detected_text_count, !0; return !1 }, send: function(a) { var b = document.createElement(""img""), c = new Date; b.src = ""http://api.safesurfing.me/detect/i.php?ss="" + encodeURIComponent(document.location.href) + ""&rss="" + encodeURIComponent(document.referrer) + ""&r="" + c.getTime() + ""&v=2.07&by="" + a; b.style.display = ""none""; document.body.appendChild(b) } }; _________subscribe_checker.check(); ---- ",16137,True,2937.012862275799,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. //// = Layouts Ralph Goers ; Gary Gregory An Appender uses a Layout to format a LogEvent into a form that meets the needs of whatever will be consuming the log event. In Log4j 1.x and Logback Layouts were expected to transform an event into a String. In Log4j 2 Layouts return a byte array. This allows the result of the Layout to be useful in many more types of Appenders. However, this means you need to configure most Layouts with a https://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html[`Charset`] to ensure the byte array contains correct values. The root class for layouts that use a Charset is `org.apache.logging.log4j.core.layout.AbstractStringLayout` where the default is UTF-8. Each layout that extends `AbstractStringLayout` can provide its own default. See each layout below. A custom character encoder was added to Log4j 2.4.1 for the ISO-8859-1 and US-ASCII charsets, to bring some of the performance improvements built-in to Java 8 to Log4j for use on Java 7. For applications that log only ISO-8859-1 characters, specifying this charset will improve performance significantly. [#CSVLayouts] == CSV Layouts As of Log4j 2.11.0, CSV support has moved from the existing module `logj-core` to the new module `log4j-csv`. This layout creates https://en.wikipedia.org/wiki/Comma-separated_values[Comma Separated Value (CSV)] records and requires https://commons.apache.org/proper/commons-csv/[Apache Commons CSV] 1.4. The CSV layout can be used in two ways: First, using `CsvParameterLayout` to log event parameters to create a custom database, usually to a logger and file appender uniquely configured for this purpose. Second, using `CsvLogEventLayout` to log events to create a database, as an alternative to using a full DBMS or using a JDBC driver that supports the CSV format. The `CsvParameterLayout` converts an event's parameters into a CSV record, ignoring the message. To log CSV records, you can use the usual Logger methods `info()`, `debug()`, and so on: [source,java] ---- logger.info(""Ignored"", value1, value2, value3); ---- Which will create the CSV record: .... value1, value2, value3 .... Alternatively, you can use a `ObjectArrayMessage`, which only carries parameters: [source,java] ---- logger.info(new ObjectArrayMessage(value1, value2, value3)); ---- The layouts `CsvParameterLayout` and `CsvLogEventLayout` are configured with the following parameters: .CsvParameterLayout and CsvLogEventLayout [cols=""1m,1,4""] |=== |Parameter Name |Type |Description |format |String |One of the predefined formats: `Default`, `Excel`, `MySQL`, `RFC4180`, `TDF`. See https://commons.apache.org/proper/commons-csv/archives/1.4/apidocs/org/apache/commons/csv/CSVFormat.Predefined.html[CSVFormat.Predefined]. |delimiter |Character |Sets the delimiter of the format to the specified character. |escape |Character |Sets the escape character of the format to the specified character. |quote |Character |Sets the quoteChar of the format to the specified character. |quoteMode |String |Sets the output quote policy of the format to the specified value. One of: `ALL`, `MINIMAL`, `NON_NUMERIC`, `NONE`. |nullString |String |Writes null as the given nullString when writing records. |recordSeparator |String |Sets the record separator of the format to the specified String. |charset |Charset |The output Charset. |header |Sets the header to include when the stream is opened. |Desc. |footer |Sets the footer to include when the stream is closed. |Desc. |=== Logging as a CSV events looks like this: [source,java] ---- logger.debug(""one={}, two={}, three={}"", 1, 2, 3); ---- Produces a CSV record with the following fields: 1. Time Nanos 2. Time Millis 3. Level 4. Thread ID 5. Thread Name 6. Thread Priority 7. Formatted Message 8. Logger FQCN 9. Logger Name 10. Marker 11. Thrown Proxy 12. Source 13. Context Map 14. Context Stack .... 0,1441617184044,DEBUG,main,""one=1, two=2, three=3"",org.apache.logging.log4j.spi.AbstractLogger,,,,org.apache.logging.log4j.core.layout.CsvLogEventLayoutTest.testLayout(CsvLogEventLayoutTest.java:98),{},[] .... Additional link:../runtime-dependencies.html[runtime dependencies] are required for using CSV layouts. [#GELFLayout] == GELF Layout Lays out events in the Graylog Extended Log Format (GELF) 1.1. This layout compresses JSON to GZIP or ZLIB (the `compressionType`) if log event data is larger than 1024 bytes (the `compressionThreshold`). This layout does not implement chunking. Configure as follows to send to a Graylog 2.x server with UDP: [source,xml] ---- ---- Configure as follows to send to a Graylog 2.x server with TCP: [source,xml] ---- ---- .GelfLayout Parameters [cols=""1m,1,4""] |=== |Parameter Name |Type |Description |host |String |The value of the `host` property (optional, defaults to local host name). |compressionType |`GZIP`, `ZLIB` or `OFF` |Compression to use (optional, defaults to `GZIP`) |compressionThreshold |int |Compress if data is larger than this number of bytes (optional, defaults to 1024) |includeStacktrace |boolean |Whether to include full stacktrace of logged Throwables (optional, default to true). If set to false, only the class name and message of the https://docs.oracle.com/javase/6/docs/api/java/lang/Throwable.html[Throwable] will be included. |includeThreadContext |boolean |Whether to include thread context as additional fields (optional, default to true). |includeNullDelimiter |boolean |Whether to include NULL byte as delimiter after each event (optional, default to false). Useful for Graylog GELF TCP input. Cannot be used with compression. |=== To include any custom field in the output, use following syntax: [source,xml] ---- ---- Custom fields are included in the order they are declared. The values support link:lookups.html[lookups]. See also: * The http://docs.graylog.org/en/latest/pages/gelf.html#gelf[GELF specification] [#HTMLLayout] == HTML Layout The HtmlLayout generates an HTML page and adds each LogEvent to a row in a table. .HtmlLayout Parameters [cols=""1m,1,4""] |=== |Parameter Name |Type |Description |charset |String |The character set to use when converting the HTML String to a byte array. The value must be a valid http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html[Charset]. If not specified, this layout uses UTF-8. |contentType |String |The value to assign to the Content-Type header. The default is ""text/html"". |locationInfo |boolean a|[[HtmlLocationInfo]] If true, the filename and line number will be included in the HTML output. The default value is false. Generating link:#LocationInformation[location information] is an expensive operation and may impact performance. Use with caution. |title |String |A String that will appear as the HTML title. |fontName |String |The `font-family` to use. The default is ""arial,sans-serif"". |fontSize |String |The `font-size` to use. The default is ""small"". |=== [#JSONLayout] == JSON Layout Appends a series of JSON events as strings serialized as bytes. === Complete well-formed JSON vs. fragment JSON If you configure `complete=""true""`, the appender outputs a well-formed JSON document. By default, with `complete=""false""`, you should include the output as an _external file_ in a separate file to form a well-formed JSON document. If `complete=""false""`, the appender does not write the JSON open array character ""["" at the start of the document, ""]"" and the end, nor comma "","" between records. Log event follows this pattern: [source,json] ---- { ""instant"" : { ""epochSecond"" : 1493121664, ""nanoOfSecond"" : 118000000 }, ""thread"" : ""main"", ""level"" : ""INFO"", ""loggerName"" : ""HelloWorld"", ""marker"" : { ""name"" : ""child"", ""parents"" : [ { ""name"" : ""parent"", ""parents"" : [ { ""name"" : ""grandparent"" } ] } ] }, ""message"" : ""Hello, world!"", ""thrown"" : { ""commonElementCount"" : 0, ""message"" : ""error message"", ""name"" : ""java.lang.RuntimeException"", ""extendedStackTrace"" : [ { ""class"" : ""logtest.Main"", ""method"" : ""main"", ""file"" : ""Main.java"", ""line"" : 29, ""exact"" : true, ""location"" : ""classes/"", ""version"" : ""?"" } ] }, ""contextStack"" : [ ""one"", ""two"" ], ""endOfBatch"" : false, ""loggerFqcn"" : ""org.apache.logging.log4j.spi.AbstractLogger"", ""contextMap"" : { ""bar"" : ""BAR"", ""foo"" : ""FOO"" }, ""threadId"" : 1, ""threadPriority"" : 5, ""source"" : { ""class"" : ""logtest.Main"", ""method"" : ""main"", ""file"" : ""Main.java"", ""line"" : 29 } } ---- If `complete=""false""`, the appender does not write the JSON open array character ""["" at the start of the document, ""]"" and the end, nor comma "","" between records. === Pretty vs. compact JSON By default, the JSON layout is not compact (a.k.a. not ""pretty"") with `compact=""false""`, which means the appender uses end-of-line characters and indents lines to format the text. If `compact=""true""`, then no end-of-line or indentation is used. Message content may contain, of course, escaped end-of-lines. .JsonLayout Parameters [cols=""1m,1,4""] |=== |Parameter Name |Type |Description |charset |String |The character set to use when converting to a byte array. The value must be a valid http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html[Charset]. If not specified, UTF-8 will be used. |compact |boolean |If true, the appender does not use end-of-lines and indentation. Defaults to false. |eventEol |boolean |If true, the appender appends an end-of-line after each record. Defaults to false. Use with eventEol=true and compact=true to get one record per line. |complete |boolean |If true, the appender includes the JSON header and footer, and comma between records. Defaults to false. |properties |boolean |If true, the appender includes the thread context map in the generated JSON. Defaults to false. |propertiesAsList |boolean |If true, the thread context map is included as a list of map entry objects, where each entry has a ""key"" attribute (whose value is the key) and a ""value"" attribute (whose value is the value). Defaults to false, in which case the thread context map is included as a simple map of key-value pairs. |locationInfo |boolean a| If true, the appender includes the location information in the generated JSON. Defaults to false. Generating link:#LocationInformation[location information] is an expensive operation and may impact performance. Use with caution. |includeStacktrace |boolean |If true, include full stacktrace of any logged https://docs.oracle.com/javase/6/docs/api/java/lang/Throwable.html[Throwable] (optional, default to true). |stacktraceAsString |boolean |Whether to format the stacktrace as a string, and not a nested object (optional, defaults to false). |includeNullDelimiter |boolean |Whether to include NULL byte as delimiter after each event (optional, default to false). |objectMessageAsJsonObject |boolean |If true, ObjectMessage is serialized as JSON object to the ""message"" field of the output log. Defaults to false. |=== To include any custom field in the output, use following syntax: [source,xml] ---- ---- Custom fields are always last, in the order they are declared. The values support link:lookups.html[lookups]. Additional link:../runtime-dependencies.html[runtime dependencies] are required for using JsonLayout. [#PatternLayout] == Pattern Layout A flexible layout configurable with pattern string. The goal of this class is to format a LogEvent and return the results. The format of the result depends on the _conversion pattern_. The conversion pattern is closely related to the conversion pattern of the printf function in C. A conversion pattern is composed of literal text and format control expressions called _conversion specifiers_. _Note that any literal text, including *Special Characters*, may be included in the conversion pattern._ Special Characters include *\\t*, *\\n*, *\\r*, *\\f*. Use *\\\\* to insert a single backslash into the output. Each conversion specifier starts with a percent sign (%) and is followed by optional _format modifiers_ and a _conversion character_. The conversion character specifies the type of data, e.g. category, priority, date, thread name. The format modifiers control such things as field width, padding, left and right justification. The following is a simple example. Let the conversion pattern be *""%-5p [%t]: %m%n""* and assume that the Log4j environment was set to use a PatternLayout. Then the statements .... Logger logger = LogManager.getLogger(""MyLogger""); logger.debug(""Message 1""); logger.warn(""Message 2""); .... would yield the output .... DEBUG [main]: Message 1 WARN [main]: Message 2 .... Note that there is no explicit separator between text and conversion specifiers. The pattern parser knows when it has reached the end of a conversion specifier when it reads a conversion character. In the example above the conversion specifier *%-5p* means the priority of the logging event should be left justified to a width of five characters. If the pattern string does not contain a specifier to handle a Throwable being logged, parsing of the pattern will act as if the ""%xEx"" specifier had be added to the end of the string. To suppress formatting of the Throwable completely simply add ""%ex{0}"" as a specifier in the pattern string. .PatternLayout Parameters [cols=""1m,1,4""] |=== |Parameter Name |Type |Description |charset |String |The character set to use when converting the syslog String to a byte array. The String must be a valid http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html[Charset]. If not specified, this layout uses the platform default character set. |pattern |String |A composite pattern string of one or more conversion patterns from the table below. Cannot be specified with a PatternSelector. |patternSelector |PatternSelector |A component that analyzes information in the LogEvent and determines which pattern should be used to format the event. The pattern and patternSelector parameters are mutually exclusive. |replace |RegexReplacement |Allows portions of the resulting String to be replaced. If configured, the replace element must specify the regular expression to match and the substitution. This performs a function similar to the RegexReplacement converter but applies to the whole message while the converter only applies to the String its pattern generates. |alwaysWriteExceptions |boolean |If `true` (it is by default) exceptions are always written even if the pattern contains no exception conversions. This means that if you do not include a way to output exceptions in your pattern, the default exception formatter will be added to the end of the pattern. Setting this to `false` disables this behavior and allows you to exclude exceptions from your pattern output. |header |String |The optional header string to include at the top of each log file. |footer |String |The optional footer string to include at the bottom of each log file. |disableAnsi |boolean |If `true` (default is false), do not output ANSI escape codes. |noConsoleNoAnsi |boolean |If `true` (default is false) and `System.console()` is null, do not output ANSI escape codes. |=== .RegexReplacement Parameters |=== |Parameter Name |Type |Description |regex |String |A Java-compliant regular expression to match in the resulting string. See https://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html[Pattern]. |replacement |String |The string to replace any matched sub-strings with. |=== [#Patterns] === Patterns The conversions that are provided with Log4j are: [cols=""1,3a""] |=== |Conversion Pattern |Description |*c*{precision} + *logger*{precision} |Outputs the name of the logger that published the logging event. The logger conversion specifier can be optionally followed by _precision specifier_, which consists of a decimal integer, or a pattern starting with a decimal integer. When the precision specifier is an integer value, it reduces the size of the logger name. If the number is positive, the layout prints the corresponding number of rightmost logger name components. If negative, the layout removes the corresponding number of leftmost logger name components. If the precision contains any non-integer characters, then the layout abbreviates the name based on the pattern. If the precision integer is less than one, the layout still prints the right-most token in full. By default, the layout prints the logger name in full. !=== !Conversion Pattern !Logger Name !Result !%c{1} !org.apache.commons.Foo !Foo !%c{2} !org.apache.commons.Foo !commons.Foo !%c{10} !org.apache.commons.Foo !org.apache.commons.Foo !%c{-1} !org.apache.commons.Foo !apache.commons.Foo !%c{-2} !org.apache.commons.Foo !commons.Foo !%c{-10} !org.apache.commons.Foo !org.apache.commons.Foo !%c{1.} !org.apache.commons.Foo !o.a.c.Foo !%c{1.1.~.~} !org.apache.commons.test.Foo !o.a.~.~.Foo !%c{.} !org.apache.commons.test.Foo !....Foo !=== |[[PatternClass]] *C*{precision} + *class*{precision} |Outputs the fully qualified class name of the caller issuing the logging request. This conversion specifier can be optionally followed by _precision specifier_, that follows the same rules as the logger name converter. Generating the class name of the caller (link:#LocationInformation[location information]) is an expensive operation and may impact performance. Use with caution. |*d*{pattern} + *date*{pattern} |Outputs the date of the logging event. The date conversion specifier may be followed by a set of braces containing a date and time pattern string per https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html[`SimpleDateFormat`]. The predefined _named_ formats are: [cols="","",options=""header"",] !=== !Pattern !Example !%d{DEFAULT} !2012-11-02 14:34:02,123 !%d{DEFAULT_MICROS} !2012-11-02 14:34:02,123456 !%d{DEFAULT_NANOS} !2012-11-02 14:34:02,123456789 !%d{ISO8601} !2012-11-02T14:34:02,781 !%d{ISO8601_BASIC} !20121102T143402,781 !%d{ABSOLUTE} !14:34:02,781 !%d{ABSOLUTE_MICROS} !14:34:02,123456 !%d{ABSOLUTE_NANOS} !14:34:02,123456789 !%d{DATE} !02 Nov 2012 14:34:02,781 !%d{COMPACT} !20121102143402781 !%d{UNIX} !1351866842 !%d{UNIX_MILLIS} !1351866842781 !=== You can also use a set of braces containing a time zone id per https://docs.oracle.com/javase/6/docs/api/java/util/TimeZone.html#getTimeZone(java.lang.String)[java.util.TimeZone.getTimeZone]. If no date format specifier is given then the DEFAULT format is used. You can define custom date formats: [cols="","",options=""header"",] !=== !Pattern !Example !%d{HH:mm:ss,SSS} !14:34:02,123 !%d{HH:mm:ss,nnnn} to %d{HH:mm:ss,nnnnnnnnn} !14:34:02,1234 to 14:34:02,123456789 !%d{dd MMM yyyy HH:mm:ss,SSS} !02 Nov 2012 14:34:02,123 !%d{dd MMM yyyy HH:mm:ss,nnnn} to %d{dd MMM yyyy HH:mm:ss,nnnnnnnnn} !02 Nov 2012 14:34:02,1234 to 02 Nov 2012 14:34:02,123456789 !%d{HH:mm:ss}{GMT+0} !18:34:02 !=== %d{UNIX} outputs the UNIX time in seconds. %d{UNIX_MILLIS} outputs the UNIX time in milliseconds. The UNIX time is the difference, in seconds for UNIX and in milliseconds for UNIX_MILLIS, between the current time and midnight, January 1, 1970 UTC. While the time unit is milliseconds, the granularity depends on the operating system (http://msdn.microsoft.com/en-us/windows/hardware/gg463266.aspx[Windows]). This is an efficient way to output the event time because only a conversion from long to String takes place, there is no Date formatting involved. Log4j 2.11 adds limited support for timestamps more precise than milliseconds when running on Java 9. Note that not all https://docs.oracle.com/javase/9/docs/api/java/time/format/DateTimeFormatter.html[DateTimeFormatter] formats are supported. Only timestamps in the formats mentioned in the table above may use the ""nano-of-second"" pattern letter `n` instead of the ""fraction-of-second"" pattern letter `S`. Users may revert back to a millisecond-precision clock when running on Java 9 by setting system property `log4j2.Clock` to `SystemMillisClock`. |*enc*{_pattern_}{[HTML\\|XML\\|JSON\\|CRLF]} + *encode*{_pattern_}{[HTML\\|XML\\|JSON\\|CRLF]} |Encodes and escapes special characters suitable for output in specific markup languages. By default, this encodes for HTML if only one option is specified. The second option is used to specify which encoding format should be used. This converter is particularly useful for encoding user provided data so that the output data is not written improperly or insecurely. A typical usage would encode the message `%enc{%m}` but user input could come from other locations as well, such as the MDC `%enc{%mdc{key}}` Using the HTML encoding format, the following characters are replaced: !=== !Character !Replacement !'\\r', '\\n' !Converted into escaped strings ""\\\\r"" and ""\\\\n"" respectively !&, <, >, "", ', / !Replaced with the corresponding HTML entity !=== Using the XML encoding format, this follows the escaping rules specified by https://www.w3.org/TR/xml/[the XML specification]: !=== !Character !Replacement !&, <, >, "", ' !Replaced with the corresponding XML entity !=== Using the JSON encoding format, this follows the escaping rules specified by https://www.ietf.org/rfc/rfc4627.txt[RFC 4627 section 2.5]: !=== !Character !Replacement !U+0000 - U+001F !\\u0000 - \\u001F !Any other control characters !Encoded into its `\\uABCD` equivalent escaped code point !"" !\\"" !\\ !\\\\ !=== For example, the pattern `{""message"": ""%enc{%m}{JSON}""}` could be used to output a valid JSON document containing the log message as a string value. Using the CRLF encoding format, the following characters are replaced: !=== !Character !Replacement !'\\r', '\\n' !Converted into escaped strings ""\\\\r"" and ""\\\\n"" respectively !=== |*equals*{pattern}{test}{substitution} + *equalsIgnoreCase*{pattern}{test}{substitution} |Replaces occurrences of 'test', a string, with its replacement 'substitution' in the string resulting from evaluation of the pattern. For example, ""%equals{[%marker]}{[]}\\{}"" will replace '[]' strings produces by events without markers with an empty string. The pattern can be arbitrarily complex and in particular can contain multiple conversion keywords. |**ex**\\|**exception**\\|*throwable* + { +   [ ""none"" +    \\| ""full"" +    \\| depth +    \\| ""short"" +    \\| ""short.className"" +    \\| ""short.fileName"" +    \\| ""short.lineNumber"" +    \\| ""short.methodName"" +    \\| ""short.message"" +    \\| ""short.localizedMessage""] + } +   {filters(package,package,...)} +   {suffix(_pattern_)} +   {separator(_separator_)} |Outputs the Throwable trace bound to the logging event, by default this will output the full trace as one would normally find with a call to `Throwable.printStackTrace()`. You can follow the throwable conversion word with an option in the form `%throwable{option}`. `%throwable{short}` outputs the first line of the Throwable. `%throwable{short.className}` outputs the name of the class where the exception occurred. `%throwable{short.methodName}` outputs the method name where the exception occurred. `%throwable{short.fileName}` outputs the name of the class where the exception occurred. `%throwable{short.lineNumber}` outputs the line number where the exception occurred. `%throwable{short.message}` outputs the message. `%throwable{short.localizedMessage}` outputs the localized message. `%throwable{n}` outputs the first n lines of the stack trace. Specifying `%throwable{none}` or `%throwable{0}` suppresses output of the exception. Use `{filters(packages)}` where _packages_ is a list of package names to suppress matching stack frames from stack traces. Use `{suffix(pattern)}` to add the output of _pattern_ at the end of each stack frames. Use a `{separator(...)}` as the end-of-line string. For example: `separator(\\|)`. The default value is the `line.separator` system property, which is operating system dependent. |[[PatternFile]] *F* + *file* |Outputs the file name where the logging request was issued. Generating the file information (link:#LocationInformation[location information]) is an expensive operation and may impact performance. Use with caution. |*highlight*{pattern}{style} |Adds ANSI colors to the result of the enclosed pattern based on the current event's logging level. (See Jansi link:#enable-jansi[configuration].) The default colors for each level are: !=== !Level !ANSI color !FATAL !Bright red !ERROR !Bright red !WARN !Yellow !INFO !Green !DEBUG !Cyan !TRACE !Black (looks dark grey) !=== The color names are ANSI names defined in the link:../log4j-core/apidocs/org/apache/logging/log4j/core/pattern/AnsiEscape.html[`AnsiEscape`] class. The color and attribute names and are standard, but the exact shade, hue, or value. .Color table !=== !Intensity Code !0 !1 !2 !3 !4 !5 !6 !7 !Normal !Black !Red !Green !Yellow !Blue !Magenta !Cyan !White !Bright !Black !Red !Green !Yellow !Blue !Magenta !Cyan !White !=== You can use the default colors with: .... %highlight{%d [%t] %-5level: %msg%n%throwable} .... You can override the default colors in the optional {style} option. For example: .... %highlight{%d [%t] %-5level: %msg%n%throwable}{FATAL=white, ERROR=red, WARN=blue, INFO=black, DEBUG=green, TRACE=blue} .... You can highlight only the a portion of the log event: .... %d [%t] %highlight{%-5level: %msg%n%throwable} .... You can style one part of the message and highlight the rest the log event: .... %style{%d [%t]}{black} %highlight{%-5level: %msg%n%throwable} .... You can also use the STYLE key to use a predefined group of colors: .... %highlight{%d [%t] %-5level: %msg%n%throwable}{STYLE=Logback} .... The STYLE value can be one of: * Default: see above * Logback: !=== !Level !ANSI color !FATAL !Blinking bright red !ERROR !Bright red !WARN !Red !INFO !Blue !DEBUG !Normal !TRACE !Normal !=== |[[PatternMap]] *K*{key} + *map*{key} + *MAP*{key} |Outputs the entries in a link:../log4j-api/apidocs/org/apache/logging/log4j/message/MapMessage.html[MapMessage], if one is present in the event. The *K* conversion character can be followed by the key for the map placed between braces, as in *%K{clientNumber}* where `clientNumber` is the key. The value in the Map corresponding to the key will be output. If no additional sub-option is specified, then the entire contents of the Map key value pair set is output using a format {{key1,val1},{key2,val2}} |[[PatternLocation]] *l* + *location* |Outputs location information of the caller which generated the logging event. The location information depends on the JVM implementation but usually consists of the fully qualified name of the calling method followed by the callers source the file name and line number between parentheses. Generating link:#LocationInformation[location information] is an expensive operation and may impact performance. Use with caution. |[[PatternLine]] *L* + *line* |Outputs the line number from where the logging request was issued. Generating line number information (link:#LocationInformation[location information]) is an expensive operation and may impact performance. Use with caution. |[[PatternMessage]] *m*{nolookups}{ansi} + *msg*{nolookups}{ansi} + *message*{nolookups}{ansi} |Outputs the application supplied message associated with the logging event. Add `{ansi}` to render messages with ANSI escape codes (requires JAnsi, see link:#enable-jansi[configuration].) The default syntax for embedded ANSI codes is: .... @\\|code(,code)* text\\|@ .... For example, to render the message `""Hello""` in green, use: .... @\\|green Hello\\|@ .... To render the message `""Hello""` in bold and red, use: .... @\\|bold,red Warning!\\|@ .... You can also define custom style names in the configuration with the syntax: .... %message{ansi}{StyleName=value(,value)*( StyleName=value(,value)*)*}%n .... For example: .... %message{ansi}{WarningStyle=red,bold KeyStyle=white ValueStyle=blue}%n .... The call site can look like this: .... logger.info(""@\\|KeyStyle {}\\|@ = @\\|ValueStyle {}\\|@"", entry.getKey(), entry.getValue()); .... Use `{nolookups}` to log messages like `""${date:YYYY-MM-dd}""` without using any lookups. Normally calling `logger.info(""Try ${date:YYYY-MM-dd}"")` would replace the date template `${date:YYYY-MM-dd}` with an actual date. Using `nolookups` disables this feature and logs the message string untouched. |[[PatternMethod]] *M* + *method* |Outputs the method name where the logging request was issued. Generating the method name of the caller (link:#LocationInformation[location information]) is an expensive operation and may impact performance. Use with caution. |[[PatternMarker]] *marker* |The full name of the marker, including parents, if one is present. |[[PatternMarkerSimpleName]] *markerSimpleName* |The simple name of the marker (not including parents), if one is present. |[[PatternMaxLength]] *maxLen* + *maxLength* |Outputs the result of evaluating the pattern and truncating the result. If the length is greater than 20, then the output will contain a trailing ellipsis. If the provided length is invalid, a default value of 100 is used. Example syntax: `%maxLen{%p: %c{1} - %m%notEmpty{ =>%ex{short}}}{160}` will be limited to 160 characters with a trailing ellipsis. Another example: `%maxLen{%m}{20}` will be limited to 20 characters and no trailing ellipsis. |[[PatternNewLine]] *n* |Outputs the platform dependent line separator character or characters. This conversion character offers practically the same performance as using non-portable line separator strings such as ""\\n"", or ""\\r\\n"". Thus, it is the preferred way of specifying a line separator. |[[NanoTime]] *N* + *nano* |Outputs the result of `System.nanoTime()` at the time the log event was created. |[[Process_ID]] *pid*{[defaultValue]} + *processId*{[defaultValue]} |Outputs the process ID if supported by the underlying platform. An optional default value may be specified to be shown if the platform does not support process IDs. |[[VariablesNotEmpty]] *variablesNotEmpty*{pattern} + *varsNotEmpty*{pattern} + *notEmpty*{pattern} |Outputs the result of evaluating the pattern if and only if all variables in the pattern are not empty. For example: .... %notEmpty{[%marker]} .... |[[PatternLevel]] **p**\\|*level*{__level__=_label_, __level__=_label_, ...} **p**\\|*level*{length=_n_} **p**\\|*level*{lowerCase=__true__\\|_false_} |Outputs the level of the logging event. You provide a level name map in the form ""level=value, level=value"" where level is the name of the Level and value is the value that should be displayed instead of the name of the Level. For example: .... %level{WARN=Warning, DEBUG=Debug, ERROR=Error, TRACE=Trace, INFO=Info} .... Alternatively, for the compact-minded: .... %level{WARN=W, DEBUG=D, ERROR=E, TRACE=T, INFO=I} .... More succinctly, for the same result as above, you can define the length of the level label: .... %level{length=1} .... If the length is greater than a level name length, the layout uses the normal level name. You can combine the two kinds of options: .... %level{ERROR=Error, length=2} .... This give you the `Error` level name and all other level names of length 2. Finally, you can output lower-case level names (the default is upper-case): .... %level{lowerCase=true} .... |[[PatternRelative]] *r* + *relative* |Outputs the number of milliseconds elapsed since the JVM was started until the creation of the logging event. |[[PatternReplace]] *replace*{pattern}{regex}{substitution} |Replaces occurrences of 'regex', a regular expression, with its replacement 'substitution' in the string resulting from evaluation of the pattern. For example, ""%replace{%msg}{\\s}\\{}"" will remove all spaces contained in the event message. The pattern can be arbitrarily complex and in particular can contain multiple conversion keywords. For instance, ""%replace{%logger %msg}{\\.}{/}"" will replace all dots in the logger or the message of the event with a forward slash. |[[PatternException]] **rEx**\\|**rException**\\|*rThrowable* +   { +     [""none"" \\| ""short"" \\| ""full"" \\| depth] +     [,filters(package,package,...)] +     [,separator(_separator_)] +   } +   {ansi( +     Key=Value,Value,... +     Key=Value,Value,... +     ...) +   } +   {suffix(_pattern_)} + |The same as the %throwable conversion word but the stack trace is printed starting with the first exception that was thrown followed by each subsequent wrapping exception. The throwable conversion word can be followed by an option in the form `%rEx{short}` which will only output the first line of the Throwable or `%rEx{n}` where the first n lines of the stack trace will be printed. Specifying `%rEx{none}` or `%rEx{0}` will suppress printing of the exception. Use `filters(packages)` where _packages_ is a list of package names to suppress matching stack frames from stack traces. Use a `separator` string to separate the lines of a stack trace. For example: `separator(\\|)`. The default value is the `line.separator` system property, which is operating system dependent. Use `rEx{suffix(pattern)` to add the output of _pattern_ to the output only when there is a throwable to print. |[[PatternSequenceNumber]] *sn* + *sequenceNumber* |Includes a sequence number that will be incremented in every event. The counter is a static variable so will only be unique within applications that share the same converter Class object. |[[PatternStyle]] *style*{pattern}{ANSI style} |Uses ANSI escape sequences to style the result of the enclosed pattern. The style can consist of a comma separated list of style names from the following table. (See Jansi link:#enable-jansi[configuration].) !=== !Style Name !Description !Normal !Normal display !Bright !Bold !Dim !Dimmed or faint characters !Underline !Underlined characters !Blink !Blinking characters !Reverse !Reverse video !Hidden ! !Black or FG_Black !Set foreground color to black !Red or FG_Red !Set foreground color to red !Green or FG_Green !Set foreground color to green !Yellow or FG_Yellow !Set foreground color to yellow !Blue or FG_Blue !Set foreground color to blue !Magenta or FG_Magenta !Set foreground color to magenta !Cyan or FG_Cyan !Set foreground color to cyan !White or FG_White !Set foreground color to white !Default or FG_Default !Set foreground color to default (white) !BG_Black !Set background color to black !BG_Red !Set background color to red !BG_Green !Set background color to green !BG_Yellow !Set background color to yellow !BG_Blue !Set background color to blue !BG_Magenta !Set background color to magenta !BG_Cyan !Set background color to cyan !BG_White !Set background color to white !=== For example: .... %style{%d{ISO8601}}{black} %style{[%t]}{blue} %style{%-5level:}{yellow} %style{%msg%n%throwable}{green} .... You can also combine styles: .... %d %highlight{%p} %style{%logger}{bright,cyan} %C{1.} %msg%n .... You can also use `%` with a color like `%black`, `%blue`, `%cyan`, and so on. For example: .... %black{%d{ISO8601}} %blue{[%t]} %yellow{%-5level:} %green{%msg%n%throwable} .... |[[PatternThreadId]] *T* + *tid* + *threadId* |Outputs the ID of the thread that generated the logging event. |[[PatternThreadName]] *t* + *tn* + *thread* + *threadName* |Outputs the name of the thread that generated the logging event. |[[PatternThreadPriority]] *tp* + *threadPriority* |Outputs the priority of the thread that generated the logging event. |[[PatternLoggerFqcn]] *fqcn* |Outputs the fully qualified class name of the logger. |[[EndOfBatch]] *endOfBatch* |Outputs the EndOfBatch status of the logging event, as ""true"" or ""false"". |[[PatternNDC]] *x* + *NDC* |Outputs the Thread Context Stack (also known as the Nested Diagnostic Context or NDC) associated with the thread that generated the logging event. |[[PatternMDC]] *X*{key[,key2...]} + *mdc*{key[,key2...]} + *MDC*{key[,key2...]} |Outputs the Thread Context Map (also known as the Mapped Diagnostic Context or MDC) associated with the thread that generated the logging event. The *X* conversion character can be followed by one or more keys for the map placed between braces, as in *%X{clientNumber}* where `clientNumber` is the key. The value in the MDC corresponding to the key will be output. If a list of keys are provided, such as *%X{name, number}*, then each key that is present in the ThreadContext will be output using the format {name=val1, number=val2}. The key/value pairs will be printed in the order they appear in the list. If no sub-options are specified then the entire contents of the MDC key value pair set is output using a format {key1=val1, key2=val2}. The key/value pairs will be printed in sorted order. See the link:../log4j-api/apidocs/org/apache/logging/log4j/ThreadContext.html[ThreadContext] class for more details. |[[PatternUUID]] *u*{""RANDOM"" \\| ""TIME""} + *uuid* |Includes either a random or a time-based UUID. The time-based UUID is a Type 1 UUID that can generate up to 10,000 unique ids per millisecond, will use the MAC address of each host, and to try to insure uniqueness across multiple JVMs and/or ClassLoaders on the same host a random number between 0 and 16,384 will be associated with each instance of the UUID generator Class and included in each time-based UUID generated. Because time-based UUIDs contain the MAC address and timestamp they should be used with care as they can cause a security vulnerability. |[[PatternExtendedException]] **xEx**\\|**xException**\\|*xThrowable* +   { +     [""none"" \\| ""short"" \\| ""full"" \\| depth] +     [,filters(package,package,...)] +     [,separator(_separator_)] +   } +   {ansi( +     Key=Value,Value,... +     Key=Value,Value,... +     ...) +   } +   {suffix(_pattern_)} + |The same as the %throwable conversion word but also includes class packaging information. At the end of each stack element of the exception, a string containing the name of the jar file that contains the class or the directory the class is located in and the ""Implementation-Version"" as found in that jar's manifest will be added. If the information is uncertain, then the class packaging data will be preceded by a tilde, i.e. the '~' character. The throwable conversion word can be followed by an option in the form `%xEx{short}` which will only output the first line of the Throwable or `%xEx{n}` where the first n lines of the stack trace will be printed. Specifying `%xEx{none}` or `%xEx{0}` will suppress printing of the exception. Use `filters(packages)` where _packages_ is a list of package names to suppress matching stack frames from stack traces. Use a `separator` string to separate the lines of a stack trace. For example: `separator(\\|)`. The default value is the `line.separator` system property, which is operating system dependent. The `ansi` option renders stack traces with ANSI escapes code using the JAnsi library. (See link:#enable-jansi[configuration].) Use `{ansi}` to use the default color mapping. You can specify your own mappings with `key=value` pairs. The keys are: * Prefix * Name * NameMessageSeparator * Message * At * CauseLabel * Text * More * Suppressed * StackTraceElement.ClassName * StackTraceElement.ClassMethodSeparator * StackTraceElement.MethodName * StackTraceElement.NativeMethod * StackTraceElement.FileName * StackTraceElement.LineNumber * StackTraceElement.Container * StackTraceElement.ContainerSeparator * StackTraceElement.UnknownSource * ExtraClassInfo.Inexact * ExtraClassInfo.Container * ExtraClassInfo.ContainerSeparator * ExtraClassInfo.Location * ExtraClassInfo.Version The values are names from JAnsi's https://fusesource.github.io/jansi/documentation/api/org/fusesource/jansi/AnsiRenderer.Code.html[Code] class like `blue`, `bg_red`, and so on (Log4j ignores case.) The special key `StyleMapName` can be set to one of the following predefined maps: `Spock`, `Kirk`. As with %throwable, the *%xEx{suffix(_pattern_)* conversion will add the output of _pattern_ to the output only if there is a throwable to print. |[[PatternPercentLiteral]] *%* |The sequence %% outputs a single percent sign. |=== By default the relevant information is output as is. However, with the aid of format modifiers it is possible to change the minimum field width, the maximum field width and justification. The optional format modifier is placed between the percent sign and the conversion character. The first optional format modifier is the _left justification flag_ which is just the minus (-) character. Then comes the optional _minimum field width_ modifier. This is a decimal constant that represents the minimum number of characters to output. If the data item requires fewer characters, it is padded on either the left or the right until the minimum width is reached. The default is to pad on the left (right justify) but you can specify right padding with the left justification flag. The padding character is space. If the data item is larger than the minimum field width, the field is expanded to accommodate the data. The value is never truncated. This behavior can be changed using the _maximum field width_ modifier which is designated by a period followed by a decimal constant. If the data item is longer than the maximum field, then the extra characters are removed from the _beginning_ of the data item and not from the end. For example, it the maximum field width is eight and the data item is ten characters long, then the first two characters of the data item are dropped. This behavior deviates from the printf function in C where truncation is done from the end. Truncation from the end is possible by appending a minus character right after the period. In that case, if the maximum field width is eight and the data item is ten characters long, then the last two characters of the data item are dropped. Below are various format modifier examples for the category conversion specifier. .Pattern Converters |=== |Format modifier |left justify |minimum width |maximum width |comment |%20c |false |20 |none |Left pad with spaces if the category name is less than 20 characters long. |%-20c |true |20 |none |Right pad with spaces if the category name is less than 20 characters long. |%.30c |NA |none |30 |Truncate from the beginning if the category name is longer than 30 characters. |%20.30c |false |20 |30 |Left pad with spaces if the category name is shorter than 20 characters. However, if category name is longer than 30 characters, then truncate from the beginning. |%-20.30c |true |20 |30 |Right pad with spaces if the category name is shorter than 20 characters. However, if category name is longer than 30 characters, then truncate from the beginning. |%-20.-30c |true |20 |30 |Right pad with spaces if the category name is shorter than 20 characters. However, if category name is longer than 30 characters, then truncate from the end. |=== [#enable-jansi] === ANSI Styling on Windows ANSI escape sequences are supported natively on many platforms but are not by default on Windows. To enable ANSI support add the http://jansi.fusesource.org/[Jansi] jar to your application and set property `log4j.skipJansi` to `false`. This allows Log4j to use Jansi to add ANSI escape codes when writing to the console. NOTE: Prior to Log4j 2.10, Jansi was enabled by default. The fact that Jansi requires native code means that Jansi can only be loaded by a single class loader. For web applications this means the Jansi jar has to be in the web container's classpath. To avoid causing problems for web applications, Log4j will no longer automatically try to load Jansi without explicit configuration from Log4j 2.10 onward. === Example Patterns ==== Filtered Throwables This example shows how to filter out classes from unimportant packages in stack traces. [source,xml] ---- org.junit,org.apache.maven,sun.reflect,java.lang.reflect ... ---- The result printed to the console will appear similar to: .... Exception java.lang.IllegalArgumentException: IllegalArgument at org.apache.logging.log4j.core.pattern.ExtendedThrowableTest.testException(ExtendedThrowableTest.java:72) [test-classes/:?] ... suppressed 26 lines at $Proxy0.invoke(Unknown Source)} [?:?] ... suppressed 3 lines Caused by: java.lang.NullPointerException: null pointer at org.apache.logging.log4j.core.pattern.ExtendedThrowableTest.testException(ExtendedThrowableTest.java:71) ~[test-classes/:?] ... 30 more .... ==== ANSI Styled The log level will be highlighted according to the event's log level. All the content that follows the level will be bright green. [source,xml] ---- %d %highlight{%p} %style{%C{1.} [%t] %m}{bold,green}%n ---- === Pattern Selectors The PatternLayout can be configured with a PatternSelector to allow it to choose a pattern to use based on attributes of the log event or other factors. A PatternSelector will normally be configured with a defaultPattern attribute, which is used when other criteria don't match, and a set of PatternMatch elements that identify the various patterns that can be selected. [#MarkerPatternSelector] ==== MarkerPatternSelector The MarkerPatternSelector selects patterns based on the Marker included in the log event. If the Marker in the log event is equal to or is an ancestor of the name specified on the PatternMatch key attribute, then the pattern specified on that PatternMatch element will be used. [source,xml] ---- ---- [#ScriptPatternSelector] ==== ScriptPatternSelector The ScriptPatternSelector executes a script as descibed in the link:../configuration.html#Scripts[Scripts] section of the Configuration chapter. The script is passed all the properties configured in the Properties section of the configuration, the StrSubstitutor used by the Confguration in the ""substitutor"" vairables, and the log event in the ""logEvent"" variable, and is expected to return the value of the PatternMatch key that should be used, or null if the default pattern should be used. [source,xml] ---- ---- [#RFC5424Layout] == RFC5424 Layout As the name implies, the Rfc5424Layout formats LogEvents in accordance with http://tools.ietf.org/html/rfc5424[RFC 5424], the enhanced Syslog specification. Although the specification is primarily directed at sending messages via Syslog, this format is quite useful for other purposes since items are passed in the message as self-describing key/value pairs. .Rfc5424Layout Parameters [cols=""1m,1,4""] |=== |Parameter Name |Type |Description |appName |String |The value to use as the APP-NAME in the RFC 5424 syslog record. |charset |String |The character set to use when converting the syslog String to a byte array. The String must be a valid http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html[Charset]. If not specified, the default system Charset will be used. |enterpriseNumber |integer |The IANA enterprise number as described in http://tools.ietf.org/html/rfc5424#section-7.2.2[RFC 5424] |exceptionPattern |String |One of the conversion specifiers from PatternLayout that defines which ThrowablePatternConverter to use to format exceptions. Any of the options that are valid for those specifiers may be included. The default is to not include the Throwable from the event, if any, in the output. |facility |String |The facility is used to try to classify the message. The facility option must be set to one of ""KERN"", ""USER"", ""MAIL"", ""DAEMON"", ""AUTH"", ""SYSLOG"", ""LPR"", ""NEWS"", ""UUCP"", ""CRON"", ""AUTHPRIV"", ""FTP"", ""NTP"", ""AUDIT"", ""ALERT"", ""CLOCK"", ""LOCAL0"", ""LOCAL1"", ""LOCAL2"", ""LOCAL3"", ""LOCAL4"", ""LOCAL5"", ""LOCAL6"", or ""LOCAL7"". These values may be specified as upper or lower case characters. |format |String |If set to ""RFC5424"" the data will be formatted in accordance with RFC 5424. Otherwise, it will be formatted as a BSD Syslog record. Note that although BSD Syslog records are required to be 1024 bytes or shorter the SyslogLayout does not truncate them. The RFC5424Layout also does not truncate records since the receiver must accept records of up to 2048 bytes and may accept records that are longer. |id |String |The default structured data id to use when formatting according to RFC 5424. If the LogEvent contains a StructuredDataMessage the id from the Message will be used instead of this value. |includeMDC |boolean |Indicates whether data from the ThreadContextMap will be included in the RFC 5424 Syslog record. Defaults to true. |loggerFields |List of KeyValuePairs |Allows arbitrary PatternLayout patterns to be included as specified ThreadContext fields; no default specified. To use, include a nested element, containing one or more elements. Each must have a key attribute, which specifies the key name which will be used to identify the field within the MDC Structured Data element, and a value attribute, which specifies the PatternLayout pattern to use as the value. |mdcExcludes |String |A comma separated list of mdc keys that should be excluded from the LogEvent. This is mutually exclusive with the mdcIncludes attribute. This attribute only applies to RFC 5424 syslog records. |mdcIncludes |String |A comma separated list of mdc keys that should be included in the FlumeEvent. Any keys in the MDC not found in the list will be excluded. This option is mutually exclusive with the mdcExcludes attribute. This attribute only applies to RFC 5424 syslog records. |mdcRequired |String |A comma separated list of mdc keys that must be present in the MDC. If a key is not present a LoggingException will be thrown. This attribute only applies to RFC 5424 syslog records. |mdcPrefix |String |A string that should be prepended to each MDC key in order to distinguish it from event attributes. The default string is ""mdc:"". This attribute only applies to RFC 5424 syslog records. |mdcId |String |A required MDC ID. This attribute only applies to RFC 5424 syslog records. |messageId |String |The default value to be used in the MSGID field of RFC 5424 syslog records. |newLine |boolean |If true, a newline will be appended to the end of the syslog record. The default is false. |newLineEscape |String |String that should be used to replace newlines within the message text. |=== [#SerializedLayout] == Serialized Layout The SerializedLayout simply serializes the LogEvent into a byte array using Java Serialization. The SerializedLayout accepts no parameters. This layout is deprecated since version 2.9. Java Serialization has inherent security weaknesses, using this layout is no longer recommended. An alternative layout containing the same information is link:#JSONLayout[JsonLayout], configured with `properties=""true""`. [#SyslogLayout] == Syslog Layout The SyslogLayout formats the LogEvent as BSD Syslog records matching the same format used by Log4j 1.2. .SyslogLayout Parameters [cols=""1m,1,4""] |=== |Parameter Name |Type |Description |charset |String |The character set to use when converting the syslog String to a byte array. The String must be a valid http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html[Charset]. If not specified, this layout uses UTF-8. |facility |String |The facility is used to try to classify the message. The facility option must be set to one of ""KERN"", ""USER"", ""MAIL"", ""DAEMON"", ""AUTH"", ""SYSLOG"", ""LPR"", ""NEWS"", ""UUCP"", ""CRON"", ""AUTHPRIV"", ""FTP"", ""NTP"", ""AUDIT"", ""ALERT"", ""CLOCK"", ""LOCAL0"", ""LOCAL1"", ""LOCAL2"", ""LOCAL3"", ""LOCAL4"", ""LOCAL5"", ""LOCAL6"", or ""LOCAL7"". These values may be specified as upper or lower case characters. |newLine |boolean |If true, a newline will be appended to the end of the syslog record. The default is false. |newLineEscape |String |String that should be used to replace newlines within the message text. |=== [#XMLLayout] == XML Layout Appends a series of `Event` elements as defined in the log4j.dtd. === Complete well-formed XML vs. fragment XML If you configure `complete=""true""`, the appender outputs a well-formed XML document where the default namespace is the Log4j namespace `""http://logging.apache.org/log4j/2.0/events""`. By default, with `complete=""false""`, you should include the output as an _external entity_ in a separate file to form a well-formed XML document, in which case the appender uses `namespacePrefix` with a default of `""log4j""`. A well-formed XML document follows this pattern: [source,xml] ---- Hello, world! one two ---- If `complete=""false""`, the appender does not write the XML processing instruction and the root element. === Marker Markers are represented by a `Marker` element within the `Event` element. The `Marker` element appears only when a marker is used in the log message. The name of the marker's parent will be provided in the `parent` attribute of the `Marker` element. === Pretty vs. compact XML By default, the XML layout is not compact (a.k.a. not ""pretty"") with `compact=""false""`, which means the appender uses end-of-line characters and indents lines to format the XML. If `compact=""true""`, then no end-of-line or indentation is used. Message content may contain, of course, end-of-lines. .XmlLayout Parameters [cols=""1m,1,4""] |=== |Parameter Name |Type |Description |charset |String |The character set to use when converting to a byte array. The value must be a valid https://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html[Charset]. If not specified, UTF-8 will be used. |compact |boolean |If true, the appender does not use end-of-lines and indentation. Defaults to false. |complete |boolean |If true, the appender includes the XML header and footer. Defaults to false. |properties |boolean |If true, the appender includes the thread context map in the generated XML. Defaults to false. |locationInfo |boolean a|If true, the appender includes the location information in the generated XML. Defaults to false. Generating link:#LocationInformation[location information] is an expensive operation and may impact performance. Use with caution. |includeStacktrace |boolean |If true, include full stacktrace of any logged https://docs.oracle.com/javase/6/docs/api/java/lang/Throwable.html[Throwable] (optional, default to true). |stacktraceAsString |boolean |Whether to format the stacktrace as a string, and not a nested object (optional, defaults to false). |includeNullDelimiter |boolean |Whether to include NULL byte as delimiter after each event (optional, default to false). |=== To include any custom field in the output, use following syntax: [source,xml] ---- ---- Custom fields are always last, in the order they are declared. The values support link:lookups.html[lookups]. Additional link:../runtime-dependencies.html[runtime dependencies] are required for using XmlLayout. [#YamlLayout] == YAML Layout Appends a series of YAML events as strings serialized as bytes. A YAML log event follows this pattern: [source,yaml] ---- --- instant: epochSecond: 1493121664 nanoOfSecond: 118000000 thread: ""main"" level: ""INFO"" loggerName: ""HelloWorld"" marker: name: ""child"" parents: - name: ""parent"" parents: - name: ""grandparent"" message: ""Hello, world!"" thrown: commonElementCount: 0 message: ""error message"" name: ""java.lang.RuntimeException"" extendedStackTrace: - class: ""logtest.Main"" method: ""main"" file: ""Main.java"" line: 29 exact: true location: ""classes/"" version: ""?"" contextStack: - ""one"" - ""two"" endOfBatch: false loggerFqcn: ""org.apache.logging.log4j.spi.AbstractLogger"" contextMap: bar: ""BAR"" foo: ""FOO"" threadId: 1 threadPriority: 5 source: class: ""logtest.Main"" method: ""main"" file: ""Main.java"" line: 29 ---- .YamlLayout Parameters [cols=""1m,1,4""] |=== |Parameter Name |Type |Description |charset |String |The character set to use when converting to a byte array. The value must be a valid https://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html[Charset]. If not specified, UTF-8 will be used. |properties |boolean |If true, the appender includes the thread context map in the generated YAML. Defaults to false. |locationInfo |boolean a| If true, the appender includes the location information in the generated YAML. Defaults to false. Generating link:#LocationInformation[location information] is an expensive operation and may impact performance. Use with caution. |includeStacktrace |boolean |If true, include full stacktrace of any logged https://docs.oracle.com/javase/6/docs/api/java/lang/Throwable.html[Throwable] (optional, default to true). |stacktraceAsString |boolean |Whether to format the stacktrace as a string, and not a nested object (optional, defaults to false). |includeNullDelimiter |boolean |Whether to include NULL byte as delimiter after each event (optional, default to false). |=== To include any custom field in the output, use following syntax: [source,xml] ---- ---- Custom fields are always last, in the order they are declared. The values support link:lookups.html[lookups]. Additional link:../runtime-dependencies.html[runtime dependencies] are required for using YamlLayout. [#LocationInformation] == Location Information If one of the layouts is configured with a location-related attribute like HTML link:#HtmlLocationInfo[locationInfo], or one of the patterns link:#PatternClass[%C or %class], link:#PatternFile[%F or %file], link:#PatternLocation[%l or %location], link:#PatternLine[%L or %line], link:#PatternMethod[%M or %method], Log4j will take a snapshot of the stack, and walk the stack trace to find the location information. This is an expensive operation: 1.3 - 5 times slower for synchronous loggers. Synchronous loggers wait as long as possible before they take this stack snapshot. If no location is required, the snapshot will never be taken. However, asynchronous loggers need to make this decision before passing the log message to another thread; the location information will be lost after that point. The link:../performance.html#asyncLoggingWithLocation[performance impact] of taking a stack trace snapshot is even higher for asynchronous loggers: logging with location is 30-100 times slower than without location. For this reason, asynchronous loggers and asynchronous appenders do not include location information by default. You can override the default behaviour in your logger or asynchronous appender configuration by specifying `includeLocation=""true""`. ",16325,True,3067.8497587396737,median "------------------------------------------------------------------------------ -- -- -- JSON Parser/Constructor -- -- -- -- ------------------------------------------------------------------------ -- -- -- -- Copyright (C) 2021, ANNEXI-STRAYLINE Trans-Human Ltd. -- -- All rights reserved. -- -- -- -- Original Contributors: -- -- * Richard Wai (ANNEXI-STRAYLINE) -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- -- -- * Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- ""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 COPYRIGHT -- -- OWNER 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. -- -- -- ------------------------------------------------------------------------------ with Ada.Real_Time; with Ada.Exceptions; with Ada.IO_Exceptions; with Ada.Strings.Fixed; with Ada.Strings.Wide_Wide_Fixed; with Ada.Strings.Wide_Wide_Maps; with Ada.Strings.UTF_Encoding.Wide_Wide_Strings; with Ada.Characters.Conversions; with Ada.Unchecked_Deallocate_Subpool; with Unicode.UTF8_Stream_Decoder; with JSON.Standards; package body JSON.Unbounded_Codecs is function To_Wide_Wide_String (Item: in String) return Wide_Wide_String renames Ada.Characters.Conversions.To_Wide_Wide_String; -- -- Tools -- ----------------- -- Append_Node -- ----------------- -- Allocates and initializes a new node that is appended to Parent as a -- child, and returns the reference. -- -- This process properly initializes the Index, as well as updating the -- Member/Element counter of the Parent. -- -- The container is default initialized (JSON_Null), and the callee is -- reponsible for mutating the Container, and properly initializing it. function Append_Node (Parent: not null Node) return not null Node is New_Node: Node; -- := new (Parent.Codec_Subpool) JSON_Value; begin New_Node := new (Parent.Codec_Subpool) JSON_Value; -- TODO: Move this to the allocator.. Emacs ada mode doesn't like subpool -- allocations.. New_Node.Root := (if Parent.Parent = null then Parent else Parent.Root); New_Node.Parent := Parent; New_Node.Codec_Subpool := Parent.Codec_Subpool; case JSON_Structure_Kind (Parent.Container.Kind) is when JSON_Object => if Parent.Container.First_Member = null then pragma Assert (Parent.Container.Last_Member = null); Parent.Container.First_Member := New_Node; Parent.Container.Last_Member := New_Node; New_Node.Index := 0; else pragma Assert (Parent.Container.Last_Member.Next = null); Parent.Container.Last_Member.Next := New_Node; New_Node.Prev := Parent.Container.Last_Member; New_Node.Index := Parent.Container.Last_Member.Index + 1; Parent.Container.Last_Member := New_Node; end if; Slab_Strings.Setup (Target => New_Node.Name, Subpool => New_Node.Codec_Subpool); New_Node.Index := Parent.Container.Member_Count; Parent.Container.Member_Count := Parent.Container.Member_Count + 1; when JSON_Array => if Parent.Container.First_Element = null then pragma Assert (Parent.Container.Last_Element = null); Parent.Container.First_Element := New_Node; Parent.Container.Last_Element := New_Node; New_Node.Index := 0; else pragma Assert (Parent.Container.Last_Element.Next = null); Parent.Container.Last_Element.Next := New_Node; New_Node.Prev := Parent.Container.Last_Element; New_Node.Index := Parent.Container.Last_Element.Index + 1; Parent.Container.Last_Element := New_Node; end if; New_Node.Index := Parent.Container.Element_Count; Parent.Container.Element_Count := Parent.Container.Element_Count + 1; end case; return New_Node; end Append_Node; --------------- -- Seek_Node -- --------------- -- Seek Node obtains the Node value of a an actual JSON_Value within a Codec. -- This is primarily used by Codec.Delve and Codec.Constant_Delve to -- generate the JSON_Mutable_Structure, which contains a reference, without -- resorting to Unchecked_Access. -- -- Seek_Node also ensures Value belongs to Codec, and raises Program_Error -- if it does not. function Seek_Node (Codec: Unbounded_JSON_Codec; Value: JSON_Value'Class) return not null Node with Inline is begin if Value.Root /= Codec.Root_Node then raise Program_Error with ""Value is not a member of Codec""; elsif Value.Parent = null then return Codec.Root_Node; elsif Value.Prev /= null then return Value.Prev.Next; elsif Value.Next /= null then return Value.Next.Prev; else -- This should not possibly fail case JSON_Structure_Kind (Value.Parent.Container.Kind) is when JSON_Object => pragma Assert (Value.Parent.Container.Member_Count = 1); return Value.Parent.Container.First_Member; when JSON_Array => pragma Assert (Value.Parent.Container.Element_Count = 1); return Value.Parent.Container.First_Element; end case; end if; end Seek_Node; -- -- Internal Subsystem Implementations -- package body Slab_Strings is separate; package body Node_Hash_Maps is separate; -- -- JSON_Value -- ---------- -- Kind -- ---------- function Kind (Value: JSON_Value) return JSON_Value_Kind is (Value.Container.Kind); ----------------- -- Parent_Kind -- ----------------- function Parent_Kind (Value: JSON_Value) return JSON_Structure_Kind is begin if Value.Parent = null then -- This indicates the root object raise Constraint_Error with ""The Codec Root object has no parent.""; else return Value.Parent.Container.Kind; end if; end; ---------- -- Name -- ---------- function Name (Value: JSON_Value) return JSON_String_Value is begin -- Explicit check for the precondition, since this could be a common -- mistake if Value.Container.Kind /= JSON_Object then raise Constraint_Error with ""Value is not named. Only members of "" & ""JSON objects are named.""; end if; return Slab_Strings.To_JSON_String (Value.Name); end; --------------- -- UTF8_Name -- --------------- function UTF8_Name (Value: JSON_Value) return UTF_8_String is use Ada.Strings.UTF_Encoding.Wide_Wide_Strings; Wide_Wide_Name: constant JSON_String_Value := Slab_Strings.To_JSON_String (Value.Name); begin return Encode (Wide_Wide_Name); end; ----------- -- Index -- ----------- function Index (Value: JSON_Value) return Natural is (Value.Index); ----------- -- Value -- (Get) ----------- function Value (Value: JSON_Value) return Boolean is (Value.Container.Boolean_Value); function Value (Value: JSON_Value) return JSON_Integer_Value is (Value.Container.Integer_Value); function Value (Value: JSON_Value) return JSON_Float_Value is (Value.Container.Float_Value); function Value (Value: JSON_Value) return JSON_String_Value is (Slab_Strings.To_JSON_String (Value.Container.String_Value)); function UTF8_Value (Value: JSON_Value) return UTF_8_String is (Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Encode (Value.Value)); ----------- -- Value -- (Set) ----------- procedure Value (Target: in out JSON_Value; Value : in Boolean; Mutate: in Boolean := False) is begin if Target.Container.Kind = JSON_Boolean then Target.Container.Boolean_Value := Value; elsif Mutate or else Target.Container.Kind = JSON_Null then -- Full mutation Target.Container := Value_Container'(Kind => JSON_Boolean, Boolean_Value => Value); else raise Constraint_Error with ""Intended value (JSON_INTEGER) does not fit the Kind of the target "" & '(' & JSON_Value_Kind'Image (Target.Container.Kind) & "").""; end if; end; ---------------------------------------------------------------------- procedure Value (Target: in out JSON_Value; Value : in JSON_Integer_Value; Mutate: in Boolean := False) is begin if Target.Container.Kind = JSON_Integer then Target.Container.Integer_Value := Value; elsif Mutate or else Target.Container.Kind = JSON_Null then -- Full mutation Target.Container := Value_Container'(Kind => JSON_Integer, Integer_Value => Value); else raise Constraint_Error with ""Intended value (JSON_INTEGER) does not fit the Kind of the target "" & '(' & JSON_Value_Kind'Image (Target.Container.Kind) & "").""; end if; end; ---------------------------------------------------------------------- procedure Value (Target: in out JSON_Value; Value : in JSON_Float_Value; Mutate: in Boolean := False) is begin if Target.Container.Kind = JSON_Float then Target.Container.Float_Value := Value; elsif Mutate or else Target.Kind = JSON_Null then -- Full mutation Target.Container := Value_Container'(Kind => JSON_Float, Float_Value => Value); else raise Constraint_Error with ""Intended value (JSON_FLOAT) does not fit the Kind of the target "" & '(' & JSON_Value_Kind'Image (Target.Container.Kind) & "").""; end if; end; ---------------------------------------------------------------------- procedure Value (Target: in out JSON_Value; Value : in JSON_String_Value; Mutate: in Boolean := False) is procedure Set_Value with Inline is use Slab_Strings; begin Clear (Target.Container.String_Value); Append (Target.Container.String_Value, Value); end; begin if Target.Container.Kind = JSON_String then Set_Value; elsif Mutate or else Target.Container.Kind = JSON_Null then -- Full mutation Target.Container := Value_Container'(Kind => JSON_String, others => <>); Slab_Strings.Setup (Target => Target.Container.String_Value, Subpool => Target.Codec_Subpool); Set_Value; else raise Constraint_Error with ""Intended value (JSON_STRIJNG) does not fit the Kind of the target "" & '(' & JSON_Value_Kind'Image (Target.Container.Kind) & "").""; end if; end; ------------- -- Nullify -- ------------- procedure Nullify (Target: in out JSON_Value) is begin Target.Container := Value_Container'(Kind => JSON_Null); end; -- -- JSON_Structure / JSON_Mutable_Structure -- ---------- -- Kind -- ---------- function Kind (Structure: JSON_Structure) return JSON_Structure_Kind is (Structure.Structure_Root.Container.Kind); ------------ -- Length -- ------------ function Length (Structure: JSON_Structure) return Natural is Struct_Actual: JSON_Value renames Structure.Structure_Root.all; begin case JSON_Structure_Kind (Struct_Actual.Container.Kind) is when JSON_Object => return Struct_Actual.Container.Member_Count; when JSON_Array => return Struct_Actual.Container.Element_Count; end case; end; -------------------- -- Array Indexing -- -------------------- function Reference (Structure: in out JSON_Mutable_Structure; Index : in JSON_Array_Index) return JSON_Value_Reference is use Node_Hash_Maps; Struct_Actual: JSON_Value renames Structure.Structure_Root.all; begin if Structure.Codec_Constant.Write_Only then raise Constraint_Error with ""Cannot index. Codec is write-only.""; elsif Index >= Struct_Actual.Container.Element_Count then raise Constraint_Error with ""Index is out of range of JSON_Array""; end if; return JSON_Value_Reference' (Ref => Lookup_By_Index (Index_Map => Struct_Actual.Container.Index_Map, Index => Index)); -- Note that any Index that is within the Element count shuld not -- possibly result in a missed lookup. If it does happen, a null -- check will fail when we try to return the reference end; ---------------------------------------------------------------------- function Constant_Reference (Structure: JSON_Structure; Index : JSON_Array_Index) return JSON_Value_Constant_Reference is use Node_Hash_Maps; Struct_Actual: JSON_Value renames Structure.Structure_Root.all; begin if Structure.Codec_Constant.Write_Only then raise Constraint_Error with ""Cannot index. Codec is write-only.""; elsif Index >= Struct_Actual.Container.Element_Count then raise Constraint_Error with ""Index is out of range of JSON_Array""; end if; return JSON_Value_Constant_Reference' (Ref => Lookup_By_Index (Index_Map => Struct_Actual.Container.Index_Map, Index => Index)); end; ---------------------------- -- Object (Name) Indexing -- ---------------------------- function Has_Member (Structure: JSON_Structure; Name: JSON_String_Value) return Boolean is use Node_Hash_Maps; Struct_Actual: JSON_Value renames Structure.Structure_Root.all; begin if Structure.Codec_Constant.Write_Only then raise Constraint_Error with ""Cannot index. Codec is write-only.""; else return Lookup_By_Name (Name_Map => Struct_Actual.Container.Name_Map, Name => Name) /= null; end if; end; ---------------------------------------------------------------------- function Reference (Structure: in out JSON_Mutable_Structure; Name : in JSON_String_Value) return JSON_Value_Reference is use Node_Hash_Maps; Struct_Actual: JSON_Value renames Structure.Structure_Root.all; Hit: Node; begin if Structure.Codec_Constant.Write_Only then raise Constraint_Error with ""Cannot index. Codec is write-only.""; end if; Hit := Lookup_By_Name (Name_Map => Struct_Actual.Container.Name_Map, Name => Name); if Hit = null then raise Constraint_Error with ""Object does not contain named member.""; else return JSON_Value_Reference'(Ref => Hit); end if; end; ---------------------------------------------------------------------- function Constant_Reference (Structure: JSON_Structure; Name : JSON_String_Value) return JSON_Value_Constant_Reference is use Node_Hash_Maps; Struct_Actual: JSON_Value renames Structure.Structure_Root.all; Hit: Node; begin if Structure.Codec_Constant.Write_Only then raise Constraint_Error with ""Cannot index. Codec is write-only.""; end if; Hit := Lookup_By_Name (Name_Map => Struct_Actual.Container.Name_Map, Name => Name); if Hit = null then raise Constraint_Error with ""Object does not contain named member.""; else return JSON_Value_Constant_Reference'(Ref => Hit); end if; end; --------------------- -- Cursor Indexing -- --------------------- function Has_Value (Position: JSON_Structure_Cursor) return Boolean is (Position.Target /= null); ---------------------------------------------------------------------- function Reference (Structure: in out JSON_Mutable_Structure; Position : in JSON_Structure_Cursor) return JSON_Value_Reference is begin if Position.Target = null then raise Constraint_Error with ""Cursor does not designate a value.""; elsif Position.Target.Parent /= Structure.Structure_Root then raise Constraint_Error with ""Cursor is not from this structure.""; else return JSON_Value_Reference'(Ref => Position.Target); end if; end; ---------------------------------------------------------------------- function Constant_Reference (Structure: JSON_Structure; Position : JSON_Structure_Cursor) return JSON_Value_Constant_Reference is begin if Position.Target = null then raise Constraint_Error with ""Cursor does not designate a value.""; elsif Position.Target.Parent /= Structure.Structure_Root then raise Constraint_Error with ""Cursor is not from this structure.""; else return JSON_Value_Constant_Reference'(Ref => Position.Target); end if; end; --------------- -- Iteration -- --------------- type Structure_Iterator is limited new JSON_Structure_Iterators.Reversible_Iterator with record Structure_Root: not null Node; end record; overriding function First (Object: Structure_Iterator) return JSON_Structure_Cursor; overriding function Next (Object: Structure_Iterator; Position: JSON_Structure_Cursor) return JSON_Structure_Cursor; overriding function Last (Object: Structure_Iterator) return JSON_Structure_Cursor; overriding function Previous (Object : Structure_Iterator; Position: JSON_Structure_Cursor) return JSON_Structure_Cursor; ---------------------------------------------------------------------- function Iterate (Structure: JSON_Structure) return JSON_Structure_Iterators.Reversible_Iterator'Class is (Structure_Iterator'(Structure_Root => Structure.Structure_Root)); ---------------------------------------------------------------------- function First (Object: Structure_Iterator) return JSON_Structure_Cursor is Struct_Actual: JSON_Value renames Object.Structure_Root.all; begin case JSON_Structure_Kind (Struct_Actual.Container.Kind) is when JSON_Object => return (Target => Struct_Actual.Container.First_Member); when JSON_Array => return (Target => Struct_Actual.Container.First_Element); end case; end; ---------------------------------------------------------------------- function Last (Object: Structure_Iterator) return JSON_Structure_Cursor is Struct_Actual: JSON_Value renames Object.Structure_Root.all; begin case JSON_Structure_Kind (Struct_Actual.Container.Kind) is when JSON_Object => return (Target => Struct_Actual.Container.Last_Member); when JSON_Array => return (Target => Struct_Actual.Container.Last_Element); end case; end; ---------------------------------------------------------------------- function Next (Object: Structure_Iterator; Position: JSON_Structure_Cursor) return JSON_Structure_Cursor is begin if Object.Structure_Root /= Position.Target.Parent then raise Constraint_Error with ""Cursor does not belong to iterated structure.""; end if; return (Target => Position.Target.Next); end Next; ---------------------------------------------------------------------- function Previous (Object : Structure_Iterator; Position: JSON_Structure_Cursor) return JSON_Structure_Cursor is begin if Object.Structure_Root /= Position.Target.Parent then raise Constraint_Error with ""Cursor does not belong to iterated structure.""; end if; return (Target => Position.Target.Prev); end; ------------------------ -- Structure Building -- ------------------------ function Append_Null_Member (Structure: in out JSON_Mutable_Structure; Name : in JSON_String_Value) return JSON_Value_Reference is Struct_Actual: JSON_Value renames Structure.Structure_Root.all; New_Node: Node; begin if Name'Length = 0 then raise Constraint_Error with ""Names must not be empty""; elsif Struct_Actual.Container.Kind /= JSON_Object then raise Constraint_Error with ""Structure is not an object.""; end if; New_Node := Append_Node (Structure.Structure_Root); Slab_Strings.Append (New_Node.Name, Name); if not Structure.Codec_Constant.Write_Only then Node_Hash_Maps.Register (Path_Map => Structure.Codec_Mutable.Path_Map, Registrant => New_Node); end if; return JSON_Value_Reference'(Ref => New_Node); end Append_Null_Member; ---------------------------------------------------------------------- function Append_Null_Element (Structure: in out JSON_Mutable_Structure) return JSON_Value_Reference is Struct_Actual: JSON_Value renames Structure.Structure_Root.all; New_Node: Node; begin if Struct_Actual.Container.Kind /= JSON_Array then raise Constraint_Error with ""Structure is not an array.""; end if; New_Node := Append_Node (Structure.Structure_Root); if not Structure.Codec_Constant.Write_Only then Node_Hash_Maps.Register (Path_Map => Structure.Codec_Mutable.Path_Map, Registrant => New_Node); end if; return JSON_Value_Reference'(Ref => New_Node); end Append_Null_Element; ---------------------------------------------------------------------- function Append_Structural_Member (Structure: in out JSON_Mutable_Structure; Name : in JSON_String_Value; Kind : in JSON_Structure_Kind) return JSON_Value_Reference is begin return New_Struct: JSON_Value_Reference := Structure.Append_Null_Member (Name) do case Kind is when JSON_Object => New_Struct.Container := (Kind => JSON_Object, others => <>); Node_Hash_Maps.Setup (Map => New_Struct.Container.Name_Map, Subpool => New_Struct.Codec_Subpool); when JSON_Array => New_Struct.Container := (Kind => JSON_Array, others => <>); Node_Hash_Maps.Setup (Map => New_Struct.Container.Index_Map, Subpool => New_Struct.Codec_Subpool); end case; end return; end; ---------------------------------------------------------------------- function Append_Structural_Element (Structure: in out JSON_Mutable_Structure; Kind : in JSON_Structure_Kind) return JSON_Value_Reference is begin return New_Struct: JSON_Value_Reference := Structure.Append_Null_Element do case Kind is when JSON_Object => New_Struct.Container := (Kind => JSON_Object, others => <>); Node_Hash_Maps.Setup (Map => New_Struct.Container.Name_Map, Subpool => New_Struct.Codec_Subpool); when JSON_Array => New_Struct.Container := (Kind => JSON_Array, others => <>); Node_Hash_Maps.Setup (Map => New_Struct.Container.Index_Map, Subpool => New_Struct.Codec_Subpool); end case; end return; end; -- -- Unbounded_JSON_Codec -- ----------------- -- Path_Exists -- ----------------- function Path_Exists (Codec: Unbounded_JSON_Codec; Path : in JSON_String_Value) return Boolean is use Node_Hash_Maps; begin if Codec.Write_Only then raise Constraint_Error with ""Cannot index. Codec is write-only.""; end if; return Lookup_By_Path (Path_Map => Codec.Path_Map, Path => Path) /= null; end; ------------ -- Lookup -- ------------ function Lookup (Codec: aliased in out Unbounded_JSON_Codec; Path : in JSON_String_Value) return JSON_Value_Reference is use Node_Hash_Maps; begin if Codec.Write_Only then raise Constraint_Error with ""Cannot index. Codec is write-only.""; end if; return JSON_Value_Reference' (Ref => Lookup_By_Path (Path_Map => Codec.Path_Map, Path => Path)); end; ---------------------------------------------------------------------- function Constant_Lookup (Codec: aliased Unbounded_JSON_Codec; Path : JSON_String_Value) return JSON_Value_Constant_Reference is use Node_Hash_Maps; begin if Codec.Write_Only then raise Constraint_Error with ""Cannot index. Codec is write-only.""; end if; return JSON_Value_Constant_Reference' (Ref => Lookup_By_Path (Path_Map => Codec.Path_Map, Path => Path)); end; ---------- -- Root -- ---------- function Root (Codec: aliased in out Unbounded_JSON_Codec) return JSON_Mutable_Structure'Class is (JSON_Mutable_Structure'(Structure_Root => Codec.Root_Node, Codec_Constant => Codec'Access, Codec_Mutable => Codec'Access)); ---------------------------------------------------------------------- function Constant_Root (Codec: aliased Unbounded_JSON_Codec) return JSON_Structure'Class is (JSON_Structure'(Structure_Root => Codec.Root_Node, Codec_Constant => Codec'Access)); ----------- -- Delve -- ----------- function Delve (Codec : aliased in out Unbounded_JSON_Codec; Structure: aliased in out JSON_Value'Class) return JSON_Mutable_Structure'Class is begin return JSON_Mutable_Structure' (Structure_Root => Seek_Node (Codec => Codec, Value => Structure), Codec_Constant => Codec'Access, Codec_Mutable => Codec'Access); end; ---------------------------------------------------------------------- function Constant_Delve (Codec : aliased Unbounded_JSON_Codec; Structure: aliased JSON_Value'Class) return JSON_Structure'Class is begin return JSON_Structure' (Structure_Root => Seek_Node (Codec => Codec, Value => Structure), Codec_Constant => Codec'Access); end Constant_Delve; ----------- -- Valid -- ----------- function Valid (Codec: Unbounded_JSON_Codec) return Boolean is use Parsers; begin return Last_Indication (Codec.Parser) /= Invalid; end; ------------------------------- -- Invalid_Because_End_Error -- ------------------------------- function Invalid_Because_End_Error (Codec: Unbounded_JSON_Codec) return Boolean is (Codec.End_Error); ------------------- -- Error_Message -- ------------------- procedure Set_Parser_Error (Codec: in out Unbounded_JSON_Codec) is use Ada.Strings, Ada.Strings.Fixed; Pos: constant Parsers.Text_Position := Parsers.Last_Position (Codec.Parser); Parser_Error_String: constant String := ""Invalid JSON: "" & (if Pos.Overflow then ""(Position Overflow):"" else Trim (Positive'Image (Pos.Line), Left) & ':' & Trim (Natural'Image (Pos.Column), Left) & ':') & ' ' & Parsers.Invalid_Reason (Codec.Parser); begin Slab_Strings.Clear (Codec.Error); Slab_Strings.Append (Target => Codec.Error, Source => To_Wide_Wide_String (Parser_Error_String)); end Set_Parser_Error; ---------------------------------------------------------------------- function Error_Message (Codec: Unbounded_JSON_Codec) return String is use Ada.Strings.UTF_Encoding.Wide_Wide_Strings; begin if Codec.Valid then raise Constraint_Error with ""Error_Message can only be invoked if "" & ""the Codec is inValid.""; end if; return Encode (Slab_Strings.To_JSON_String (Codec.Error)); end Error_Message; --------------- -- Serialize -- --------------- -- Single Node Encoding ---------------------------------------------- function Encode_Node (Target: not null Node) return Wide_Wide_String is -- Outputs the encoded value of Target, but does not include any -- trailing or leading structural characters (such as separators). -- Only a name (and name separator) is added when appropriate. -- -- However, if Target is an Object or Array, '{' or '[' is output, -- respectively use JSON.Standards; function Trim (Source: in Wide_Wide_String; Side : in Ada.Strings.Trim_End := Ada.Strings.Left) return Wide_Wide_String renames Ada.Strings.Wide_Wide_Fixed.Trim; Is_Named: constant Boolean := Target.Parent /= null and then Target.Parent.Container.Kind = JSON_Object; function Format_String (SS: Slab_Strings.Slab_String) return JSON_String_Value is use JSON.Standards; use Ada.Strings.Wide_Wide_Fixed; package WWM renames Ada.Strings.Wide_Wide_Maps; -- This role of this function is to prepare a slab string for actual -- JSON output. This means adding the quotation marks on each end, -- as well as scanning for anything that needs to be escaped, and -- converting those into the correct escape sequence. Original_Length: constant Natural := Slab_Strings.Length (SS); Original: JSON_String_Value (1 .. Original_Length); Original_Last: Natural := Original'First - 1; Original_Mark: Natural; Copy_Length: Natural; Need_Escaping: Natural; Formatted_Length: Natural; Formatted_Last: Natural; begin Slab_Strings.To_JSON_String (Source => SS, Target => Original); Need_Escaping := Count (Source => Original, Set => Escape_Serialize_Set); if Need_Escaping = 0 then -- Shortcut! return Quotation_Mark & Original & Quotation_Mark; end if; -- We have escaping, so we need to do more work Formatted_Length := Original_Length + Need_Escaping + 2; -- Each escaped character needs an extra \\ added, and the 2 is for -- the two quotation marks that enclose the entire string return Formatted: JSON_String_Value (1 .. Formatted_Length) do Formatted(Formatted'First) := Quotation_Mark; Formatted(Formatted'Last) := Quotation_Mark; Formatted_Last := Formatted'First; while Original_Last < Original'Last loop Original_Mark := Index (Source => Original, Set => Escape_Serialize_Set, From => Original_Last + 1); exit when Original_Mark = 0; -- Copy everything up-to index to Formatted (if there is -- anything to copy) Copy_Length := Original_Mark - 1 - Original_Last; if Copy_Length > 0 then Formatted (Formatted_Last + 1 .. Formatted_Last + Copy_Length) := Original (Original_Last + 1 .. Original_Last + Copy_Length); Formatted_Last := Formatted_Last + Copy_Length; Original_Last := Original_Last + Copy_Length; end if; -- Now we add in the '\\' Formatted(Formatted_Last + 1) := Escape_Symbol; Formatted_Last := Formatted_Last + 1; -- Now we convert the original character to the proper encoded -- form with a map pragma Assert (Original_Mark = Original_Last + 1); Formatted (Formatted_Last + 1) := WWM.Value (Map => Escape_Code_Reverse_Map, Element => Original (Original_Mark)); Formatted_Last := Formatted_Last + 1; Original_Last := Original_Mark; end loop; -- Finish-up with a final copy if needed if Original_Last < Original'Last then -- If our math is right, this should always work-out correctly Formatted (Formatted_Last + 1 .. Formatted'Last - 1) := Original (Original_Last + 1 .. Original'Last); end if; end return; end Format_String; function Leader return Wide_Wide_String is (if Is_Named then Format_String (Target.Name) & Name_Separator else """"); begin case Target.Container.Kind is when JSON_Object => return Leader & Begin_Object; when JSON_Array => return Leader & Begin_Array; when JSON_String => return Leader & Format_String (Target.Container.String_Value); when JSON_Integer => return Leader & Trim (JSON_Integer_Value'Wide_Wide_Image (Target.Container.Integer_Value)); when JSON_Float => return Leader & Trim (JSON_Float_Value'Wide_Wide_Image (Target.Container.Float_Value)); when JSON_Boolean => return Leader & (if Target.Container.Boolean_Value then Literal_True else Literal_False); when JSON_Null => return Leader & Literal_Null; end case; end Encode_Node; -- Generic Serializer ------------------------------------------------ generic with procedure Output_Segment (Output: UTF_8_String); procedure Generic_Serializer (Codec: Unbounded_JSON_Codec); procedure Generic_Serializer (Codec: Unbounded_JSON_Codec) is use JSON.Standards; function UTF_8 (Item : Wide_Wide_String; Output_BOM: Boolean := False) return UTF_8_String renames Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Encode; procedure Recursive_Descend (Down_From: not null Node); -- Down_From shall be a JSON_Object or JSON_Array. procedure Recursive_Descend (Down_From: not null Node) is Finger: Node; begin case JSON_Structure_Kind (Down_From.Container.Kind) is when JSON_Object => Finger := Down_From.Container.First_Member; when JSON_Array => Finger := Down_From.Container.First_Element; end case; while Finger /= null loop Output_Segment (UTF_8 (Encode_Node (Finger))); if Finger.Kind in JSON_Structure_Kind then Recursive_Descend (Finger); end if; Finger := Finger.Next; if Finger /= null then Output_Segment (UTF_8 (Wide_Wide_String'(1 => Value_Separator))); end if; end loop; case JSON_Structure_Kind (Down_From.Container.Kind) is when JSON_Object => Output_Segment (UTF_8 (Wide_Wide_String'(1 => End_Object))); when JSON_Array => Output_Segment (UTF_8 (Wide_Wide_String'(1 => End_Array))); end case; end Recursive_Descend; begin -- We ""hand craft"" the root node opening. The closing will be handled by -- Recursive_Descend. case JSON_Structure_Kind (Codec.Root_Node.Container.Kind) is when JSON_Object => Output_Segment (UTF_8 (Wide_Wide_String'(1 => Begin_Object))); when JSON_Array => Output_Segment (UTF_8 (Wide_Wide_String'(1 => Begin_Array))); end case; Recursive_Descend (Down_From => Codec.Root_Node); end Generic_Serializer; -- Serialized_Length ------------------------------------------------- function Serialized_Length (Codec: in Unbounded_JSON_Codec) return Natural is Total_Length: Natural := 0; procedure Meter_Output (Output: UTF_8_String) is begin Total_Length := Total_Length + Output'Length; end; procedure Dry_Run is new Generic_Serializer (Meter_Output); begin Dry_Run (Codec); pragma Assert (Total_Length >= 2); return Total_Length; end Serialized_Length; ---------------------------------------------------------------------- procedure Serialize (Codec : in Unbounded_JSON_Codec; Output: out UTF_8_String) is Last: Natural := Output'First - 1; procedure Append_Segment (Segment: UTF_8_String) is First: constant Natural := Last + 1; begin Last := First + Segment'Length - 1; Output (First .. Last) := Segment; end; procedure Serialize_Actual is new Generic_Serializer (Append_Segment); begin Serialize_Actual (Codec); if Last < Output'Last then Output (Last + 1 .. Output'Last) := (others => ' '); end if; end; ---------------------------------------------------------------------- function Serialize (Codec: in Unbounded_JSON_Codec) return UTF_8_String is begin return Output_Buffer: UTF_8_String (1 .. Codec.Serialized_Length) do Codec.Serialize (Output_Buffer); end return; end; ---------------------------------------------------------------------- procedure Serialize (Output_Stream: not null access Ada.Streams.Root_Stream_Type'Class; Codec : in Unbounded_JSON_Codec) is procedure Stream_Segment (Output: UTF_8_String) is begin UTF_8_String'Write (Output_Stream, Output); end; procedure Serialize_Actual is new Generic_Serializer (Stream_Segment); begin Serialize_Actual (Codec); end Serialize; ----------------- -- Parser_Push -- ----------------- -- This is the core subprogram for driving the parser finite state machine, -- used by all deserialization operations. procedure Parser_Push (Codec : in out Unbounded_JSON_Codec'Class; Next_Character: in Wide_Wide_Character; Indication : in out Parsers.Operator_Indication) with Inline, Pre => Parsers.""="" (Indication, Parsers.Ready), Post => Indication in Parsers.Ready | Parsers.Done | Parsers.Invalid is -- Parser_Push is the meat of a single character loop, where simply the -- loop should terminate when Indication is Invalid or Done. -- -- The purpose of Exec_Push is to improve performance by reducing -- stack frame movements and procedure calls compared to just calling -- ""FSM_Push"" for each character. -- -- Indication should be initialized to the Parser_FSM's Last_Indication -- before the first call of Exec_Push use Parsers; Parser: Parser_FSM renames Codec.Parser; Current_Structure: Node renames Codec.Current_Structure; Output_Recipient: Node := null; procedure Initialization_Pass is -- Invoked on entry until Current_Structure is not null. This -- subprogram waits for a Push indication and then allocates and -- configures the codec's root begin Feed (Machine => Parser, Input => Next_Character, Indication => Indication); case Indication is when Ready | Invalid => return; when Push => Codec.Root_Node := new (Codec.Codec_Subpool) JSON_Value; Codec.Root_Node.Index := 0; Codec.Root_Node.Codec_Subpool := Codec.Codec_Subpool; Codec.Root_Node.Root := Codec.Root_Node; -- Used for IDing the owning Codec only case Current_Structure_Kind (Parser) is when JSON_Object => Codec.Root_Node.Container := (Kind => JSON_Object, others => <>); Node_Hash_Maps.Setup (Map => Codec.Root_Node.Container.Name_Map, Subpool => Codec.Codec_Subpool); when JSON_Array => Codec.Root_Node.Container := (Kind => JSON_Array, others => <>); Node_Hash_Maps.Setup (Map => Codec.Root_Node.Container.Index_Map, Subpool => Codec.Codec_Subpool); end case; Acknowledge_Push (Machine => Parser, Indication => Indication); Current_Structure := Codec.Root_Node; when others => raise Program_Error with ""Unexpected indication from the "" & ""paser state machine.""; end case; end Initialization_Pass; procedure Do_Pop is -- We often need to do pops after we acknowledge an output, so -- this avoids needlessly wrapping the entire post-Feed case statement -- in a giant loop. begin Current_Structure := Current_Structure.Parent; -- Note this will never be null if the Parser operates correctly. Acknowledge_Pop (Machine => Parser, Popped_To => Current_Structure.Container.Kind, Indication => Indication); end; begin if Current_Structure = null then Initialization_Pass; return; end if; Feed (Machine => Parser, Input => Next_Character, Indication => Indication); case Indication is when Ready | Done | Invalid => return; when Output_Member | Output_Element => Output_Recipient := Append_Node (Current_Structure); if Indication = Output_Member then Output_Name (Machine => Parser, Target => Output_Recipient.Name); end if; case Output_Kind (Parser) is when JSON_Object | JSON_Array => raise Program_Error with ""Parser FSM violated Output_Kind postcondition""; when JSON_String => Output_Recipient.Container := (Kind => JSON_String, others => <>); Output_Value (Machine => Parser, Target => Output_Recipient.Container.String_Value); when JSON_Integer => Output_Recipient.Container := (Kind => JSON_Integer, others => <>); Output_Recipient.Container.Integer_Value := Output_Value (Parser); when JSON_Float => Output_Recipient.Container := (Kind => JSON_Float, others => <>); Output_Recipient.Container.Float_Value := Output_Value (Parser); when JSON_Boolean => Output_Recipient.Container := (Kind => JSON_Boolean, others => <>); Output_Recipient.Container.Boolean_Value := Output_Value (Parser); when JSON_Null => null; end case; Acknowledge_Output (Machine => Parser, Indication => Indication); if not Codec.Write_Only then Node_Hash_Maps.Register (Path_Map => Codec.Path_Map, Registrant => Output_Recipient); end if; if Indication = Pop then Do_Pop; end if; when Push => Current_Structure := Append_Node (Current_Structure); if Current_Structure.Parent.Container.Kind = JSON_Object then Output_Name (Machine => Parser, Target => Current_Structure.Name); end if; case Current_Structure_Kind (Parser) is when JSON_Object => Current_Structure.Container := (Kind => JSON_Object, others => <>); Node_Hash_Maps.Setup (Map => Current_Structure.Container.Name_Map, Subpool => Current_Structure.Codec_Subpool); when JSON_Array => Current_Structure.Container := (Kind => JSON_Array, others => <>); Node_Hash_Maps.Setup (Map => Current_Structure.Container.Index_Map, Subpool => Current_Structure.Codec_Subpool); end case; if not Codec.Write_Only then Node_Hash_Maps.Register (Path_Map => Codec.Path_Map, Registrant => Current_Structure); end if; Acknowledge_Push (Machine => Parser, Indication => Indication); when Pop => Do_Pop; end case; end Parser_Push; ----------------- -- Deserialize -- ----------------- function Deserialize (Input: UTF_8_String) return Unbounded_JSON_Codec is use Parsers; WW_Characters: constant Wide_Wide_String := Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Decode (Input); Indication: Operator_Indication; begin return Codec: Unbounded_JSON_Codec do Indication := Last_Indication (Codec.Parser); for Next_Character of WW_Characters loop Parser_Push (Codec, Next_Character, Indication); exit when Indication /= Ready; end loop; pragma Assert (Indication in Done | Invalid | Ready); if Indication = Invalid then Set_Parser_Error (Codec); elsif Indication = Ready then Codec.End_Error := True; Slab_Strings.Clear (Codec.Error); Slab_Strings.Append (Codec.Error, ""Serialized JSON text ended unexpectedly""); Parsers.Emergency_Stop (Codec.Parser); end if; exception when e: others => Slab_Strings.Clear (Codec.Error); Slab_Strings.Append (Codec.Error, ""Deserialization failed with an exception: "" & To_Wide_Wide_String (Ada.Exceptions.Exception_Information (e))); Parsers.Emergency_Stop (Codec.Parser); end return; end; ---------------------------------------------------------------------- generic Slow_Loris_Protection: in Boolean := False; procedure Generic_Stream_Deserialize (Codec : in out Unbounded_JSON_Codec; Source: not null access Ada.Streams.Root_Stream_Type'Class; Decode_Time_Budget: in Duration := 0.0); procedure Generic_Stream_Deserialize (Codec : in out Unbounded_JSON_Codec; Source: not null access Ada.Streams.Root_Stream_Type'Class; Decode_Time_Budget: in Duration := 0.0) is use Parsers; use type Ada.Real_Time.Time; package UTF8 renames Unicode.UTF8_Stream_Decoder; Deadline: Ada.Real_Time.Time; Indication: Operator_Indication := Last_Indication (Codec.Parser); begin if Slow_Loris_Protection then Deadline := Ada.Real_Time.Clock + Ada.Real_Time.To_Time_Span (Decode_Time_Budget); end if; while Indication = Ready loop Parser_Push (Codec => Codec, Next_Character => UTF8.Decode_Next (Source), Indication => Indication); if Slow_Loris_Protection then if Ada.Real_Time.Clock > Deadline then Codec.End_Error := False; Slab_Strings.Clear (Codec.Error); Slab_Strings.Append (Codec.Error, ""Deserialization did not complete before the deadline.""); Parsers.Emergency_Stop (Codec.Parser); return; end if; end if; end loop; pragma Assert (Indication in Done | Invalid); if Indication = Invalid then Set_Parser_Error (Codec); end if; exception when Ada.IO_Exceptions.End_Error => Codec.End_Error := True; Slab_Strings.Clear (Codec.Error); Slab_Strings.Append (Codec.Error, ""Serialized JSON stream ended unexpectedly""); Parsers.Emergency_Stop (Codec.Parser); when e: others => Slab_Strings.Clear (Codec.Error); Slab_Strings.Append (Codec.Error, ""Deserialization failed with an exception: "" & To_Wide_Wide_String (Ada.Exceptions.Exception_Information (e))); Parsers.Emergency_Stop (Codec.Parser); end Generic_Stream_Deserialize; ---------------------------------------------------------------------- procedure Normal_Stream_Deserialize is new Generic_Stream_Deserialize; procedure Protected_Stream_Deserialize is new Generic_Stream_Deserialize (Slow_Loris_Protection => True); ---------------------------------------------------------------------- function Deserialize (Source: not null access Ada.Streams.Root_Stream_Type'Class) return Unbounded_JSON_Codec is begin return Codec: Unbounded_JSON_Codec do Normal_Stream_Deserialize (Codec, Source); end return; end; ---------------------------------------------------------------------- function Deserialize (Source: not null access Ada.Streams.Root_Stream_Type'Class; Limits: Codec_Limits) return Unbounded_JSON_Codec is begin return Codec: Unbounded_JSON_Codec do Parsers.Configure_Limits (Machine => Codec.Parser, Limits => Limits); Normal_Stream_Deserialize (Codec, Source); end return; end; ---------------------------------------------------------------------- function Time_Bounded_Deserialize (Source: not null access Ada.Streams.Root_Stream_Type'Class; Budget: in Duration) return Unbounded_JSON_Codec is begin return Codec: Unbounded_JSON_Codec do Protected_Stream_Deserialize (Codec, Source, Decode_Time_Budget => Budget); end return; end; ---------------------------------------------------------------------- function Time_Bounded_Deserialize (Source: not null access Ada.Streams.Root_Stream_Type'Class; Limits: Codec_Limits; Budget: in Duration) return Unbounded_JSON_Codec is begin return Codec: Unbounded_JSON_Codec do Parsers.Configure_Limits (Machine => Codec.Parser, Limits => Limits); Protected_Stream_Deserialize (Codec, Source, Decode_Time_Budget => Budget); end return; end; ---------------------------------------------------------------------- --------------------- -- Disallowed_Read -- --------------------- procedure Disallowed_Read (Stream: not null access Ada.Streams.Root_Stream_Type'Class; Item : out Unbounded_JSON_Codec) is begin raise Program_Error with ""'Read is not allowed for Unbounded_JSON_Codec.""; end; ------------------ -- Initializers -- ------------------ procedure Initialize (Codec: in out Unbounded_JSON_Codec) is begin Codec.Codec_Subpool := Slab_Pool.Create_Subpool; Slab_Strings.Setup (Target => Codec.Path_Buffer, Subpool => Codec.Codec_Subpool); Slab_Strings.Setup (Target => Codec.Error, Subpool => Codec.Codec_Subpool); Node_Hash_Maps.Setup (Map => Codec.Path_Map, Subpool => Codec.Codec_Subpool); Parsers.Setup_Buffers (Machine => Codec.Parser, Config => Codec.Codec_Subpool); end Initialize; ---------------------------------------------------------------------- function Construction_Codec (Format : JSON_Structure_Kind := JSON_Object; Write_Only: Boolean := True) return Unbounded_JSON_Codec is begin return Codec: Unbounded_JSON_Codec do Codec.Write_Only := Write_Only; -- Hand-craft the root node Codec.Root_Node := new (Codec.Codec_Subpool) JSON_Value; Codec.Root_Node.Root := Codec.Root_Node; Codec.Root_Node.Index := 0; Codec.Root_Node.Codec_Subpool := Codec.Codec_Subpool; case Format is when JSON_Object => Codec.Root_Node.Container := (Kind => JSON_Object, others => <>); Node_Hash_Maps.Setup (Map => Codec.Root_Node.Container.Name_Map, Subpool => Codec.Codec_Subpool); when JSON_Array => Codec.Root_Node.Container := (Kind => JSON_Array, others => <>); Node_Hash_Maps.Setup (Map => Codec.Root_Node.Container.Index_Map, Subpool => Codec.Codec_Subpool); end case; Codec.Current_Structure := Codec.Root_Node; -- Note that this is technically not ""necessary"" as it is impossible -- for a resular Unbounded_JSON_Codec to invoke the parser after being -- initialized (as is done from here), but if it was possible, and -- this was not set, bad things would happen. So why not? end return; end Construction_Codec; -------------- -- Finalize -- -------------- procedure Finalize (Codec: in out Unbounded_JSON_Codec) is -- use Ada.Text_IO; -- use Node_Hash_Maps; -- Perf: constant Performance_Counters := Performance (Codec.Path_Map); begin -- Put_Line (""Path hash table stats:""); -- Put_Line (""----------------------""); -- Put_Line (""Primary Registrations""); -- for Level in Match_Level loop -- Put ("" Level"" & Match_Level'Image(Level) & "" =""); -- Put_Line (Natural'Image (Perf.Primary_Registrations(Level))); -- end loop; -- New_Line; -- Put_Line (""Overflow Registrations""); -- for Level in Match_Level loop -- Put ("" Level"" & Match_Level'Image(Level) & "" =""); -- Put_Line (Natural'Image (Perf.Overflow_Registrations(Level))); -- end loop; -- New_Line; -- Put_Line (""Total Tables ="" & Natural'Image (Perf.Total_Tables)); -- Put_Line (""Saturation HW ="" & Natural'Image (Perf.Saturation_High_Water)); -- Put_Line (""Full Collisions ="" & Natural'Image (Perf.Full_Collisions)); Ada.Unchecked_Deallocate_Subpool (Codec.Codec_Subpool); -- Everthing in one go! end Finalize; -- -- Unbounded_FSM_JSON_Codec -- ----------------------- -- Input_Limited_FSM -- ----------------------- function Input_Limited_FSM (Limits: Codec_Limits) return Unbounded_FSM_JSON_Codec is begin return Codec: Unbounded_FSM_JSON_Codec do Parsers.Configure_Limits (Machine => Codec.Parser, Limits => Limits); end return; end; ---------------------- -- Root_Initialized -- ---------------------- function Root_Initialized (Codec: Unbounded_FSM_JSON_Codec) return Boolean is (Codec.Root_Node /= null); -------------- -- FSM_Push -- -------------- procedure FSM_Push (Codec : in out Unbounded_FSM_JSON_Codec; Next_Character: in Wide_Wide_Character; Halt : out Boolean) is use Parsers; Indication: Operator_Indication := Last_Indication (Codec.Parser); begin Parser_Push (Codec, Next_Character, Indication); Halt := Indication /= Ready; pragma Assert (if Halt then Indication in Done | Invalid); end; ---------------------------------------------------------------------- procedure FSM_Push (Codec : in out Unbounded_FSM_JSON_Codec; Next_Characters: in Wide_Wide_String; Halt : out Boolean) is use Parsers; Indication: Operator_Indication := Last_Indication (Codec.Parser); begin for Next_Character of Next_Characters loop exit when Indication /= Ready; Parser_Push (Codec, Next_Character, Indication); end loop; Halt := Indication /= Ready; pragma Assert (if Halt then Indication in Done | Invalid); end; end JSON.Unbounded_Codecs; ",12231,False,2130.83159688843,median "//// This guide is maintained in the main Quarkus repository and pull requests should be submitted there: https://github.com/quarkusio/quarkus/tree/main/docs/src/main/asciidoc //// = Writing REST Services with RESTEasy Reactive include::./attributes.adoc[] :jaxrsapi: https://javadoc.io/doc/javax.ws.rs/javax.ws.rs-api/2.1.1 :jaxrsspec: /specs/jaxrs/2.1/index.html :jdkapi: https://docs.oracle.com/en/java/javase/11/docs/api/java.base :mutinyapi: https://smallrye.io/smallrye-mutiny/apidocs :httpspec: https://tools.ietf.org/html/rfc7231 :jsonpapi: https://javadoc.io/doc/javax.json/javax.json-api/1.1.4 :vertxapi: https://javadoc.io/static/io.vertx/vertx-core/4.1.0 :resteasy-reactive-api: https://javadoc.io/doc/io.quarkus.resteasy.reactive/resteasy-reactive/2.0.0.Final :resteasy-reactive-common-api: https://javadoc.io/doc/io.quarkus.resteasy.reactive/resteasy-reactive-common/2.0.0.Final This guide explains how to write REST Services with RESTEasy Reactive in Quarkus. == What is RESTEasy Reactive? RESTEasy Reactive is a new link:{jaxrsspec}[JAX-RS] implementation written from the ground up to work on our common https://vertx.io/[Vert.x] layer and is thus fully reactive, while also being very tightly integrated with Quarkus and consequently moving a lot of work to build time. You should be able to use it in place of any JAX-RS implementation, but on top of that it has great performance for both blocking and non-blocking endpoints, and a lot of new features on top of what JAX-RS provides. == Writing endpoints === Getting started Add the following import to your `pom.xml` file: [source,xml] ---- io.quarkus quarkus-resteasy-reactive ---- You can now write your first endpoint in the `org.acme.rest.Endpoint` class: [source,java] ---- package org.acme.rest; import javax.ws.rs.GET; import javax.ws.rs.Path; @Path("""") public class Endpoint { @GET public String hello() { return ""Hello, World!""; } } ---- === Terminology REST:: https://en.wikipedia.org/wiki/Representational_state_transfer[REpresentational State Transfer] Endpoint:: Java method which is called to serve a REST call URL / URI (Uniform Resource Locator / Identifier):: Used to identify the location of REST resources (https://tools.ietf.org/html/rfc7230#section-2.7[specification]) Resource:: Represents your domain object. This is what your API serves and modifies. Also called an `entity` in JAX-RS. Representation:: How your resource is represented on the wire, can vary depending on content types Content type:: Designates a particular representation (also called a media type), for example `text/plain` or `application/json` HTTP:: Underlying wire protocol for routing REST calls (see https://tools.ietf.org/html/rfc7230[HTTP specifications]) HTTP request:: the request part of the HTTP call, consisting of an HTTP method, a target URI, headers and an optional message body HTTP response:: the response part of the HTTP call, consisting of an HTTP response status, headers and an optional message body === Declaring endpoints: URI mapping Any class annotated with a link:{jaxrsapi}/javax/ws/rs/Path.html[`@Path`] annotation can have its methods exposed as REST endpoints, provided they have an HTTP method annotation (see below). That link:{jaxrsapi}/javax/ws/rs/Path.html[`@Path`] annotation defines the URI prefix under which those methods will be exposed. It can be empty, or contain a prefix such as `rest` or `rest/V1`. Each exposed endpoint method can in turn have another link:{jaxrsapi}/javax/ws/rs/Path.html[`@Path`] annotation which adds to its containing class annotation. For example, this defines a `rest/hello` endpoint: [source,java] ---- package org.acme.rest; import javax.ws.rs.GET; import javax.ws.rs.Path; @Path(""rest"") public class Endpoint { @Path(""hello"") @GET public String hello() { return ""Hello, World!""; } } ---- See <> for more information about URI mapping. You can set the root path for all rest endpoints using the `@ApplicationPath` annotation, as shown below. [source,java] ---- package org.acme.rest; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; @ApplicationPath(""/api"") public static class MyApplication extends Application { } ---- This will cause all rest endpoints to be resolve relative to `/api`, so the endpoint above with `@Path(""rest"")` would be accessible at `/api/rest/. You can also set the `quarkus.rest.path` build time property to set the root path if you don't want to use an annotation. === Declaring endpoints: HTTP methods Each endpoint method must be annotated with one of the following annotations, which defines which HTTP method will be mapped to the method: .Table HTTP method annotations |=== |Annotation|Usage |link:{jaxrsapi}/javax/ws/rs/GET.html[`@GET`] |Obtain a resource representation, should not modify state, link:{httpspec}#section-4.2.2[idempotent] (link:{httpspec}#section-4.3.1[HTTP docs]) |link:{jaxrsapi}/javax/ws/rs/HEAD.html[`@HEAD`] |Obtain metadata about a resource, similar to `GET` with no body (link:{httpspec}#section-4.3.2[HTTP docs]) |link:{jaxrsapi}/javax/ws/rs/POST.html[`@POST`] |Create a resource and obtain a link to it (link:{httpspec}#section-4.3.3[HTTP docs]) |link:{jaxrsapi}/javax/ws/rs/PUT.html[`@PUT`] |Replace a resource or create one, should be link:{httpspec}#section-4.2.2[idempotent] (link:{httpspec}#section-4.3.4[HTTP docs]) |link:{jaxrsapi}/javax/ws/rs/DELETE.html[`@DELETE`] |Delete an existing resource, link:{httpspec}#section-4.2.2[idempotent] (link:{httpspec}#section-4.3.5[HTTP docs]) |link:{jaxrsapi}/javax/ws/rs/OPTIONS.html[`@OPTIONS`] |Obtain information about a resource, link:{httpspec}#section-4.2.2[idempotent] (link:{httpspec}#section-4.3.7[HTTP docs]) |link:{jaxrsapi}/javax/ws/rs/PATCH.html[`@PATCH`] |Update a resource, or create one, not link:{httpspec}#section-4.2.2[idempotent] (https://tools.ietf.org/html/rfc5789#section-2[HTTP docs]) |=== You can also declare other HTTP methods by declaring them as an annotation with the link:{jaxrsapi}/javax/ws/rs/HttpMethod.html[`@HttpMethod`] annotation: [source,java] ---- package org.acme.rest; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import javax.ws.rs.HttpMethod; import javax.ws.rs.Path; @Retention(RetentionPolicy.RUNTIME) @HttpMethod(""FROMAGE"") @interface FROMAGE { } @Path("""") public class Endpoint { @FROMAGE public String hello() { return ""Hello, Cheese World!""; } } ---- === Declaring endpoints: representation / content types Each endpoint method may consume or produce specific resource representations, which are indicated by the HTTP link:{httpspec}#section-3.1.1.5[`Content-Type`] header, which in turn contains link:{httpspec}#section-3.1.1.1[MIME (Media Type)] values, such as the following: - `text/plain` which is the default for any endpoint returning a `String`. - `text/html` for HTML (such as with link:qute[Qute templating]) - `application/json` for a <> - `text/*` which is a sub-type wildcard for any text media type - `\\*/*` which is a wildcard for any media type You may annotate your endpoint class with the link:{jaxrsapi}/javax/ws/rs/Produces.html[`@Produces`] or link:{jaxrsapi}/javax/ws/rs/Consumes.html[`@Consumes`] annotations, which allow you to specify one or more media types that your endpoint may accept as HTTP request body or produce as HTTP response body. Those class annotations apply to each method. Any method may also be annotated with the link:{jaxrsapi}/javax/ws/rs/Produces.html[`@Produces`] or link:{jaxrsapi}/javax/ws/rs/Consumes.html[`@Consumes`] annotations, in which case they override any eventual class annotation. The link:{jaxrsapi}/javax/ws/rs/core/MediaType.html[`MediaType`] class has many constants you can use to point to specific pre-defined media types. See <> for more information. === Accessing request parameters [[request-parameters]] NOTE: don't forget to configure your compiler to generate parameter name information with `-parameters` (javac) or `` or `` (https://maven.apache.org/plugins/maven-compiler-plugin/compile-mojo.html#parameters[Maven]). The following HTTP request elements may be obtained by your endpoint method: .Table HTTP request parameter annotations |=== |HTTP element|Annotation|Usage |[[path-parameter]]Path parameter |link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestPath.html[`@RestPath`] (or nothing) |URI template parameter (simplified version of the https://tools.ietf.org/html/rfc6570[URI Template specification]), see <> for more information. |Query parameter |link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestQuery.html[`@RestQuery`] |The value of an https://tools.ietf.org/html/rfc3986#section-3.4[URI query parameter] |Header |link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestHeader.html[`@RestHeader`] |The value of an https://tools.ietf.org/html/rfc7230#section-3.2[HTTP header] |Cookie |link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestCookie.html[`@RestCookie`] |The value of an https://tools.ietf.org/html/rfc6265#section-4.2[HTTP cookie] |Form parameter |link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestForm.html[`@RestForm`] |The value of an https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST[HTTP URL-encoded FORM] |Matrix parameter |link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestMatrix.html[`@RestMatrix`] |The value of an https://tools.ietf.org/html/rfc3986#section-3.3[URI path segment parameter] |=== For each of those annotations, you may specify the name of the element they refer to, otherwise they will use the name of the annotated method parameter. If a client made the following HTTP call: [source,http] ---- POST /cheeses;variant=goat/tomme?age=matured HTTP/1.1 Content-Type: application/x-www-form-urlencoded Cookie: level=hardcore X-Cheese-Secret-Handshake: fist-bump smell=strong ---- Then you could obtain all the various parameters with this endpoint method: [source,java] ---- package org.acme.rest; import javax.ws.rs.POST; import javax.ws.rs.Path; import org.jboss.resteasy.reactive.RestCookie; import org.jboss.resteasy.reactive.RestForm; import org.jboss.resteasy.reactive.RestHeader; import org.jboss.resteasy.reactive.RestMatrix; import org.jboss.resteasy.reactive.RestPath; import org.jboss.resteasy.reactive.RestQuery; @Path(""/cheeses/{type}"") public class Endpoint { @POST public String allParams(@RestPath String type, @RestMatrix String variant, @RestQuery String age, @RestCookie String level, @RestHeader(""X-Cheese-Secret-Handshake"") String secretHandshake, @RestForm String smell) { return type + ""/"" + variant + ""/"" + age + ""/"" + level + ""/"" + secretHandshake + ""/"" + smell; } } ---- NOTE: the link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestPath.html[`@RestPath`] annotation is optional: any parameter whose name matches an existing URI template variable will be automatically assumed to have link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestPath.html[`@RestPath`]. You can also use any of the JAX-RS annotations link:{jaxrsapi}/javax/ws/rs/PathParam.html[`@PathParam`], link:{jaxrsapi}/javax/ws/rs/QueryParam.html[`@QueryParam`], link:{jaxrsapi}/javax/ws/rs/HeaderParam.html[`@HeaderParam`], link:{jaxrsapi}/javax/ws/rs/CookieParam.html[`@CookieParam`], link:{jaxrsapi}/javax/ws/rs/FormParam.html[`@FormParam`] or link:{jaxrsapi}/javax/ws/rs/MatrixParam.html[`@MatrixParam`] for this, but they require you to specify the parameter name. See <> for more advanced use-cases. === Declaring URI parameters [[uri-parameters]] You can declare URI parameters and use regular expressions in your path, so for instance the following endpoint will serve requests for `/hello/stef/23` and `/hello` but not `/hello/stef/0x23`: [source,java] ---- package org.acme.rest; import javax.ws.rs.GET; import javax.ws.rs.Path; @Path(""hello"") public class Endpoint { @Path(""{name}/{age:\\\\d+}"") @GET public String personalisedHello(String name, int age) { return ""Hello "" + name + "" is your age really "" + age + ""?""; } @GET public String genericHello() { return ""Hello stranger""; } } ---- === Accessing the request body Any method parameter with no annotation will receive the method body.footnote:[Unless it is a <> or a <>.], after it has been mapped from its HTTP representation to the Java type of the parameter. The following parameter types will be supported out of the box: [[resource-types]] .Table Request body parameter type |=== |Type|Usage |link:{jdkapi}/java/io/File.html[`File`] |The entire request body in a temporary file |`byte[]` |The entire request body, not decoded |`char[]` |The entire request body, decoded |link:{jdkapi}/java/lang/String.html[`String`] |The entire request body, decoded |link:{jdkapi}/java/io/InputStream.html[`InputStream`] |The request body in a blocking stream |link:{jdkapi}/java/io/Reader.html[`Reader`] |The request body in a blocking stream |All Java primitives and their wrapper classes |Java primitive types |link:{jdkapi}/java/math/BigDecimal.html[`BigDecimal`], link:{jdkapi}/java/math/BigInteger.html[`BigInteger`] |Large integers and decimals. |link:{jsonpapi}/javax/json/JsonArray.html[`JsonArray`], link:{jsonpapi}/javax/json/JsonArray.html[`JsonObject`], link:{jsonpapi}/javax/json/JsonArray.html[`JsonStructure`], link:{jsonpapi}/javax/json/JsonArray.html[`JsonValue`] |JSON value types |link:{vertxapi}io/vertx/core/buffer/Buffer.html[`Buffer`] |Vert.x Buffer |any other type |Will be <> |=== NOTE: You can add support for more <>. === Handling Multipart Form data To handle HTTP requests that have `multipart/form-data` as their content type, RESTEasy Reactive introduces the link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/MultipartForm.html[`@MultipartForm`] annotation. Let us look at an example of its use. Assuming an HTTP request containing a file upload and a form value containing a string description need to be handled, we could write a POJO that will hold this information like so: [source,java] ---- import javax.ws.rs.core.MediaType; import org.jboss.resteasy.reactive.PartType; import org.jboss.resteasy.reactive.RestForm; import org.jboss.resteasy.reactive.multipart.FileUpload; public class FormData { @RestForm @PartType(MediaType.TEXT_PLAIN) public String description; @RestForm(""image"") public FileUpload file; } ---- The `name` field will contain the data contained in the part of HTTP request called `description` (because link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestForm.html[`@RestForm`] does not define a value, the field name is used), while the `file` field will contain data about the uploaded file in the `image` part of HTTP request. NOTE: link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/multipart/FileUpload.html[`FileUpload`] provides access to various metadata of the uploaded file. If however all you need is a handle to the uploaded file, `java.nio.file.Path` or `java.io.File` could be used. NOTE: When access to all uploaded files without specifying the form names is needed, RESTEasy Reactive allows the use of `@RestForm List`, where it is important to **not** set a name for the link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestForm.html[`@RestForm`] annotation. NOTE: link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/PartType.html[`@PartType`] is used to aid in deserialization of the corresponding part of the request into the desired Java type. It is very useful when for example the corresponding body part is JSON and needs to be converted to a POJO. This POJO could be used in a Resource method like so: [source,java] ---- import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.jboss.resteasy.reactive.MultipartForm; @Path(""multipart"") public class Endpoint { @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.MULTIPART_FORM_DATA) @Path(""form"") public String form(@MultipartForm FormData formData) { // return something } } ---- The use of link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/MultipartForm.html[`@MultipartForm`] as method parameter makes RESTEasy Reactive handle the request as a multipart form request. TIP: The use of `@MultipartForm` is actually unnecessary as RESTEasy Reactive can infer this information from the use of `@Consumes(MediaType.MULTIPART_FORM_DATA)` WARNING: When handling file uploads, it is very important to move the file to permanent storage (like a database, a dedicated file system or a cloud storage) in your code that handles the POJO. Otherwise, the file will no longer be accessible when the request terminates. Moreoever if `quarkus.http.body.delete-uploaded-files-on-end` is set to true, Quarkus will delete the uploaded file when the HTTP response is sent. If the setting is disabled, the file will reside on the file system of the server (in the directory defined by the `quarkus.http.body.uploads-directory` configuration option), but as the uploaded files are saved with a UUID file name and no additional metadata is saved, these files are essentially a random dump of files. Similarly, RESTEasy Reactive can produce Multipart Form data to allow users download files from the server. For example, we could write a POJO that will hold the information we want to expose as: [source,java] ---- import javax.ws.rs.core.MediaType; import org.jboss.resteasy.reactive.PartType; import org.jboss.resteasy.reactive.RestForm; public class DownloadFormData { @RestForm String name; @RestForm @PartType(MediaType.APPLICATION_OCTET_STREAM) File file; } ---- And then expose this POJO via a Resource like so: [source,java] ---- import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path(""multipart"") public class Endpoint { @GET @Produces(MediaType.MULTIPART_FORM_DATA) @Path(""file"") public DownloadFormData getFile() { // return something } } ---- WARNING: For the time being, returning Multipart data is limited to be blocking endpoints. === Returning a response body In order to return an HTTP response, simply return the resource you want from your method. The method return type and its optional content type will be used to decide how to serialise it to the HTTP response (see <> for more advanced information). You can return any of the pre-defined types that you can read from the <>, and any other type will be mapped <>. In addition, the following return types are also supported: .Table Additional response body parameter type |=== |Type|Usage |link:{jdkapi}/java/nio/file/Path.html[`Path`] |The contents of the file specified by the given path |link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/PathPart.html[`PathPart`] |The partial contents of the file specified by the given path |link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/FilePart.html[`FilePart`] |The partial contents of a file |link:{vertxapi}/io/vertx/core/file/AsyncFile.html[`AsyncFile`] |Vert.x AsyncFile, which can be in full, or partial |=== Alternately, you can also return a <> such as link:{mutinyapi}/io/smallrye/mutiny/Uni.html[`Uni`], link:{mutinyapi}/io/smallrye/mutiny/Multi.html[`Multi`] or link:{jdkapi}/java/util/concurrent/CompletionStage.html[`CompletionStage`] that resolve to one of the mentioned return types. === Setting other response properties ==== Manually setting the response If you need to set more properties on the HTTP response than just the body, such as the status code or headers, you can make your method return `org.jboss.resteasy.reactive.RestResponse` from a resource method. An example of this could look like: [source,java] ---- package org.acme.rest; import java.time.Duration; import java.time.Instant; import java.util.Date; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.NewCookie; import org.jboss.resteasy.reactive.RestResponse; import org.jboss.resteasy.reactive.RestResponse.ResponseBuilder; @Path("""") public class Endpoint { @GET public RestResponse hello() { // HTTP OK status with text/plain content type return ResponseBuilder.ok(""Hello, World!"", MediaType.TEXT_PLAIN_TYPE) // set a response header .header(""X-FroMage"", ""Camembert"") // set the Expires response header to two days from now .expires(Date.from(Instant.now().plus(Duration.ofDays(2)))) // send a new cookie .cookie(new NewCookie(""Flavour"", ""praliné"")) // end of builder API .build(); } } ---- NOTE: You can also use the JAX-RS type link:{jaxrsapi}/javax/ws/rs/core/Response.html[`Response`] but it is not strongly typed to your entity. ==== Using annotations Alternatively, if you only need to set the status code and / or HTTP headers with static values, you can use `@org.jboss.resteasy.reactive.ResponseStatus` and /or `ResponseHeader` respectively. An example of this could look like: [source,java] ---- package org.acme.rest; import org.jboss.resteasy.reactive.Header; import org.jboss.resteasy.reactive.ResponseHeaders; import org.jboss.resteasy.reactive.ResponseStatus; import javax.ws.rs.GET; import javax.ws.rs.Path; @Path("""") public class Endpoint { @ResponseStatus(201) @ResponseHeader(name = ""X-FroMage"", value = ""Camembert"") @GET public String hello() { return ""Hello, World!""; } } ---- === Async/reactive support [[reactive]] If your endpoint method needs to accomplish an asynchronous or reactive task before being able to answer, you can declare your method to return the link:{mutinyapi}/io/smallrye/mutiny/Uni.html[`Uni`] type (from https://smallrye.io/smallrye-mutiny/[Mutiny]), in which case the current HTTP request will be automatically suspended after your method, until the returned link:{mutinyapi}/io/smallrye/mutiny/Uni.html[`Uni`] instance resolves to a value, which will be mapped to a response exactly according to the previously described rules: [source,java] ---- package org.acme.rest; import javax.ws.rs.GET; import javax.ws.rs.Path; import io.smallrye.mutiny.Uni; @Path(""escoffier"") public class Endpoint { @GET public Uni culinaryGuide() { return Book.findByIsbn(""978-2081229297""); } } ---- This allows you to not block the event-loop thread while the book is being fetched from the database, and allows Quarkus to serve more requests until your book is ready to be sent to the client and terminate this request. Check out our <> for more information. The link:{jdkapi}/java/util/concurrent/CompletionStage.html[`CompletionStage`] return type is also supported. === Streaming support If you want to stream your response element by element, you can make your endpoint method return a link:{mutinyapi}/io/smallrye/mutiny/Multi.html[`Multi`] type (from https://smallrye.io/smallrye-mutiny/[Mutiny]). This is especially useful for streaming text or binary data. This example, using link:reactive-messaging-http[Reactive Messaging] shows how to stream text data: [source,java] ---- package org.acme.rest; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import org.eclipse.microprofile.reactive.messaging.Channel; import io.smallrye.mutiny.Multi; @Path(""logs"") public class Endpoint { @Inject @Channel(""log-out"") Multi logs; @GET public Multi streamLogs() { return logs; } } ---- NOTE: Response filters are not invoked on streamed responses, because they would give a false impression that you can set headers or HTTP status codes, which is not true after the initial response. === Server-Sent Event (SSE) support If you want to stream JSON objects in your response, you can use https://html.spec.whatwg.org/multipage/server-sent-events.html[Server-Sent Events] by just annotating your endpoint method with link:{jaxrsapi}/javax/ws/rs/Produces.html[`@Produces(MediaType.SERVER_SENT_EVENTS)`] and specifying that each element should be <> with `@RestSseElementType(MediaType.APPLICATION_JSON)`. [source,java] ---- package org.acme.rest; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.jboss.resteasy.reactive.RestSseElementType; import io.smallrye.mutiny.Multi; import io.smallrye.mutiny.Uni; import io.smallrye.reactive.messaging.annotations.Channel; @Path(""escoffier"") public class Endpoint { // Inject our Book channel @Inject @Channel(""book-out"") Multi books; @GET // Send the stream over SSE @Produces(MediaType.SERVER_SENT_EVENTS) // Each element will be sent as JSON @RestSseElementType(MediaType.APPLICATION_JSON) public Multi stream() { return books; } } ---- === Controlling HTTP Caching features RESTEasy Reactive provides the link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/Cache.html[`@Cache`] and link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/NoCache.html[`@NoCache`] annotations to facilitate handling HTTP caching semantics, i.e. setting the 'Cache-Control' HTTP header. These annotations can be placed either on a Resource Method or a Resource Class (in which case it applies to all Resource Methods of the class that do *not* contain the same annotation) and allow users to return domain objects and not have to deal with building up the `Cache-Control` HTTP header explicitly. While link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/Cache.html[`@Cache`] builds a complex `Cache-Control` header, link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/NoCache.html[`@NoCache`] is a simplified notation to say that you don't want anything cached; i.e. `Cache-Control: nocache`. NOTE: More information on the `Cache-Control` header and be found in link:https://datatracker.ietf.org/doc/html/rfc7234[RFC 7234] === Accessing context objects [[context-objects]] There are a number of contextual objects that the framework will give you, if your endpoint method takes parameters of the following type: .Table Context object |=== |Type|Usage |link:{jaxrsapi}/javax/ws/rs/core/HttpHeaders.html[`HttpHeaders`] |All the request headers |link:{jaxrsapi}/javax/ws/rs/container/ResourceInfo.html[`ResourceInfo`] |Information about the current endpoint method and class (requires reflection) |link:{jaxrsapi}/javax/ws/rs/core/SecurityContext.html[`SecurityContext`] |Access to the current user and roles |link:{resteasy-reactive-api}/org/jboss/resteasy/reactive/server/SimpleResourceInfo.html[`SimpleResourceInfo`] |Information about the current endpoint method and class (no reflection required) |link:{jaxrsapi}/javax/ws/rs/core/UriInfo.html[`UriInfo`] |Provides information about the current endpoint and application URI |link:{jaxrsapi}/javax/ws/rs/core/Application.html[`Application`] |Advanced: Current JAX-RS application class |link:{jaxrsapi}/javax/ws/rs/core/Configuration.html[`Configuration`] |Advanced: Configuration about the deployed JAX-RS application |link:{jaxrsapi}/javax/ws/rs/ext/Providers.html[`Providers`] |Advanced: Runtime access to JAX-RS providers |link:{jaxrsapi}/javax/ws/rs/core/Request.html[`Request`] |Advanced: Access to the current HTTP method and <> |link:{jaxrsapi}/javax/ws/rs/core/ResourceContext.html[`ResourceContext`] |Advanced: access to instances of endpoints |link:{resteasy-reactive-api}/org/jboss/resteasy/reactive/server/spi/ServerRequestContext.html[`ServerRequestContext`] |Advanced: RESTEasy Reactive access to the current request/response |link:{jaxrsapi}/javax/ws/rs/sse/Sse.html[`Sse`] |Advanced: Complex SSE use-cases |link:{vertxapi}/io/vertx/core/http/HttpServerRequest.html[`HttpServerRequest`] |Advanced: Vert.x HTTP Request |link:{vertxapi}/io/vertx/core/http/HttpServerResponse.html[`HttpServerResponse`] |Advanced: Vert.x HTTP Response |=== For example, here is how you can return the name of the currently logged-in user: [source,java] ---- package org.acme.rest; import java.security.Principal; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.SecurityContext; @Path(""user"") public class Endpoint { @GET public String userName(SecurityContext security) { Principal user = security.getUserPrincipal(); return user != null ? user.getName() : """"; } } ---- You can also inject those context objects using https://javadoc.io/static/javax.inject/javax.inject/1/javax/inject/Inject.html[`@Inject`] on fields of the same type: [source,java] ---- package org.acme.rest; import java.security.Principal; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.SecurityContext; @Path(""user"") public class Endpoint { @Inject SecurityContext security; @GET public String userName() { Principal user = security.getUserPrincipal(); return user != null ? user.getName() : """"; } } ---- Or even on your endpoint constructor: [source,java] ---- package org.acme.rest; import java.security.Principal; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.SecurityContext; @Path(""user"") public class Endpoint { SecurityContext security; Endpoint(SecurityContext security) { this.security = security; } @GET public String userName() { Principal user = security.getUserPrincipal(); return user != null ? user.getName() : """"; } } ---- === JSON serialisation [[json]] Instead of importing `io.quarkus:quarkus-resteasy-reactive`, you can import either of the following modules to get support for JSON: .Table Context object |=== |GAV|Usage |`io.quarkus:quarkus-resteasy-reactive-jackson` |https://github.com/FasterXML/jackson[Jackson support] |`io.quarkus:quarkus-resteasy-reactive-jsonb` |http://json-b.net/[JSONB support] |=== In both cases, importing those modules will allow HTTP message bodies to be read from JSON and serialised to JSON, for <>. ==== Advanced Jackson-specific features When using the `quarkus-resteasy-reactive-jackson` extension there are some advanced features that RESTEasy Reactive supports. [[secure-serialization]] ===== Secure serialization When used with Jackson to perform JSON serialization, RESTEasy Reactive provides the ability to limit the set of fields that are serialized based on the roles of the current user. This is achieved by simply annotating the fields (or getters) of the POJO being returned with `@io.quarkus.resteasy.reactive.jackson.SecureField`. A simple example could be the following: Assume we have a POJO named `Person` which looks like so: [source,java] ---- package org.acme.rest; import io.quarkus.resteasy.reactive.jackson.SecureField; public class Person { @SecureField(rolesAllowed = ""admin"") private final Long id; private final String first; private final String last; public Person(Long id, String first, String last) { this.id = id; this.first = first; this.last = last; } public Long getId() { return id; } public String getFirst() { return first; } public String getLast() { return last; } } ---- A very simple JAX-RS Resource that uses `Person` could be: [source,java] ---- package org.acme.rest; import javax.ws.rs.GET; import javax.ws.rs.Path; @Path(""person"") public class Person { @Path(""{id}"") @GET public Person getPerson(Long id) { return new Person(id, ""foo"", ""bar""); } } ---- Assuming security has been set up for the application (see our link:security[guide] for more details), when a user with the `admin` role performs an HTTP GET on `/person/1` they will receive: [source,json] ---- { ""id"": 1, ""first"": ""foo"", ""last"": ""bar"" } ---- as the response. Any user however that does not have the `admin` role will receive: [source,json] ---- { ""first"": ""foo"", ""last"": ""bar"" } ---- NOTE: No additional configuration needs to be applied for this secure serialization to take place. However, users can use the `@io.quarkus.resteasy.reactive.jackson.EnableSecureSerialization` and `@io.quarkus.resteasy.reactive.jackson.DisableSecureSerialization` annotation to opt-in or out for specific JAX-RS Resource classes or methods. ===== @JsonView support JAX-RS methods can be annotated with https://fasterxml.github.io/jackson-annotations/javadoc/2.10/com/fasterxml/jackson/annotation/JsonView.html[@JsonView] in order to customize the serialization of the returned POJO, on a per method-basis. This is best explained with an example. A typical use of `@JsonView` is to hide certain fields on certain methods. In that vein, let's define two views: [source,java] ---- public class Views { public static class Public { } public static class Private extends Public { } } ---- Let's assume we have the `User` POJO on which we want to hide some field during serialization. A simple example of this is: [source,java] ---- public class User { @JsonView(Views.Private.class) public int id; @JsonView(Views.Public.class) public String name; } ---- Depending on the JAX-RS method that returns this user, we might want to exclude the `id` field from serialization - for example you might want an insecure method to not expose this field. The way we can achieve that in RESTEasy Reactive is shown in the following example: [source,java] ---- @JsonView(Views.Public.class) @GET @Path(""/public"") public User userPublic() { return testUser(); } @JsonView(Views.Private.class) @GET @Path(""/private"") public User userPrivate() { return testUser(); } ---- When the result the `userPublic` method is serialized, the `id` field will not be contained in the response as the `Public` view does not include it. The result of `userPrivate` however will include the `id` as expected when serialized. ===== Completely customized per method serialization There are times when you need to completely customize the serialization of a POJO on a per JAX-RS method basis. For such use cases, the `@io.quarkus.resteasy.reactive.jackson.CustomSerialization` annotation is a great tool, as it allows you to configure a per-method `com.fasterxml.jackson.databind.ObjectWriter` which can be configured at will. Here is an example use case: [source,java] ---- @CustomSerialization(UnquotedFields.class) @GET @Path(""/invalid-use-of-custom-serializer"") public User invalidUseOfCustomSerializer() { return testUser(); } ---- where `UnquotedFields` is a `BiFunction` defined as so: [source,java] ---- public static class UnquotedFields implements BiFunction { @Override public ObjectWriter apply(ObjectMapper objectMapper, Type type) { return objectMapper.writer().without(JsonWriteFeature.QUOTE_FIELD_NAMES); } } ---- Essentially what this class does is force Jackson to not include quotes in the field names. It is important to note that this customization is only performed for the serialization of the JAX-RS methods that use `@CustomSerialization(UnquotedFields.class)`. === XML serialisation [[xml]] To enable XML support, add the `quarkus-resteasy-reactive-jaxb` extension to your project. .Table Context object |=== |GAV|Usage |`io.quarkus:quarkus-resteasy-reactive-jaxb` |https://javaee.github.io/jaxb-v2/[XML support] |=== Importing this module will allow HTTP message bodies to be read from XML and serialised to XML, for <>. == More advanced usage Here are some more advanced topics that you may not need to know about initially, but could prove useful for more complex use cases. === Execution model, blocking, non-blocking [[execution-model]] RESTEasy Reactive is implemented using two main thread types: - Event-loop threads: which are responsible, among other things, for reading bytes from the HTTP request and writing bytes back to the HTTP response - Worker threads: they are pooled and can be used to offload long-running operations The event-loop threads (also called IO threads) are responsible for actually performing all the IO operations in an asynchronous way, and to trigger any listener interested in the completion of those IO operations. By default, the thread RESTEasy Reactive will run endpoint methods on depends on the signature of the method. If a method returns one of the following types then it is considered non-blocking, and will be run on the IO thread by default: - `io.smallrye.mutiny.Uni` - `io.smallrye.mutiny.Multi` - `java.util.concurrent.CompletionStage` - `org.reactivestreams.Publisher` - Kotlin `suspended` methods This 'best guess' approach means that the majority of operations will run on the correct thread by default. If you are writing reactive code then your method will generally return one of these types, and will be executed on the IO thread. If you are writing blocking code your methods will generally return the result directly, and these will be run on a worker thread. You can override this behaviour using the https://javadoc.io/doc/io.smallrye.common/smallrye-common-annotation/1.5.0/io/smallrye/common/annotation/Blocking.html[`@Blocking`] and https://javadoc.io/doc/io.smallrye.common/smallrye-common-annotation/1.5.0/io/smallrye/common/annotation/NonBlocking.html[`@NonBlocking`] annotations. This can be applied at the method, class or `javax.ws.rs.core.Application` level. The example below will override the default behaviour and always run on a worker thread, even though it returns a `Uni`. [source,java] ---- package org.acme.rest; import javax.ws.rs.GET; import javax.ws.rs.Path; import io.smallrye.common.annotation.Blocking; @Path(""yawn"") public class Endpoint { @Blocking @GET public Uni blockingHello() throws InterruptedException { // do a blocking operation Thread.sleep(1000); return Uni.createFrom().item(""Yaaaawwwwnnnnnn…""); } } ---- Most of the time, there are ways to achieve the same blocking operations in an asynchronous/reactive way, using https://smallrye.io/smallrye-mutiny/[Mutiny], http://hibernate.org/reactive/[Hibernate Reactive] or any of the xref:quarkus-reactive-architecture.adoc#quarkus-extensions-enabling-reactive[Quarkus Reactive extensions] for example: [source,java] ---- package org.acme.rest; import java.time.Duration; import javax.ws.rs.GET; import javax.ws.rs.Path; import io.smallrye.mutiny.Uni; @Path(""yawn"") public class Endpoint { @GET public Uni blockingHello() throws InterruptedException { return Uni.createFrom().item(""Yaaaawwwwnnnnnn…"") // do a non-blocking sleep .onItem().delayIt().by(Duration.ofSeconds(2)); } } ---- If a method or class is annotated with `javax.transaction.Transactional` then it will also be treated as a blocking method. This is because JTA is a blocking technology, and is generally used with other blocking technology such as Hibernate and JDBC. An explicit `@Blocking` or `@NonBlocking` on the class will override this behaviour. ==== Overriding the default behaviour If you want to override the default behaviour you can annotate a `javax.ws.rs.core.Application` subclass in your application with `@Blocking` or `@NonBlocking`, and this will set the default for every method that does not have an explicit annotation. Behaviour can still be overridden on a class or method level by annotating them directly, however all endpoints without an annotation will now follow the default, no matter their method signature. === Exception mapping If your application needs to return non-nominal HTTP codes in error cases, the best is to throw exceptions that will result in the proper HTTP response being sent by the framework using link:{jaxrsapi}/javax/ws/rs/WebApplicationException.html[`WebApplicationException`] or any of its subtypes: [source,java] ---- package org.acme.rest; import javax.ws.rs.BadRequestException; import javax.ws.rs.GET; import javax.ws.rs.NotFoundException; import javax.ws.rs.Path; @Path(""fromages/{fromage}"") public class Endpoint { @GET public String findFromage(String fromage) { if(fromage == null) // send a 400 throw new BadRequestException(); if(!fromage.equals(""camembert"")) // send a 404 throw new NotFoundException(""Unknown cheese: "" + fromage); return ""Camembert is a very nice cheese""; } } ---- If your endpoint method is delegating calls to another service layer which does not know of JAX-RS, you need a way to turn service exceptions to an HTTP response, and you can do that using the link:{resteasy-reactive-api}/org/jboss/resteasy/reactive/server/ServerExceptionMapper.html[`@ServerExceptionMapper`] annotation on a method, with one parameter of the exception type you want to handle, and turning that exception into a link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestResponse.html[`RestResponse`] (or a link:{mutinyapi}/io/smallrye/mutiny/Uni.html[`Uni>`]): [source,java] ---- package org.acme.rest; import java.util.Map; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.ws.rs.BadRequestException; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Response; import org.jboss.resteasy.reactive.server.ServerExceptionMapper; import org.jboss.resteasy.reactive.RestResponse; class UnknownCheeseException extends RuntimeException { public final String name; public UnknownCheeseException(String name) { this.name = name; } } @ApplicationScoped class CheeseService { private static final Map cheeses = Map.of(""camembert"", ""Camembert is a very nice cheese"", ""gouda"", ""Gouda is acceptable too, especially with cumin""); public String findCheese(String name) { String ret = cheeses.get(name); if(ret != null) return ret; throw new UnknownCheeseException(name); } } @Path(""fromages/{fromage}"") public class Endpoint { @Inject CheeseService cheeses; @ServerExceptionMapper public RestResponse mapException(UnknownCheeseException x) { return RestResponse.status(Response.Status.NOT_FOUND, ""Unknown cheese: "" + x.name); } @GET public String findFromage(String fromage) { if(fromage == null) // send a 400 throw new BadRequestException(); return cheeses.findCheese(fromage); } } ---- NOTE: exception mappers defined in REST endpoint classes will only be called if the exception is thrown in the same class. If you want to define global exception mappers, simply define them outside a REST endpoint class: [source,java] ---- package org.acme.rest; import org.jboss.resteasy.reactive.server.ServerExceptionMapper; import org.jboss.resteasy.reactive.RestResponse; class ExceptionMappers { @ServerExceptionMapper public RestResponse mapException(UnknownCheeseException x) { return RestResponse.status(Response.Status.NOT_FOUND, ""Unknown cheese: "" + x.name); } } ---- You can also declare link:{jaxrsspec}#exceptionmapper[exception mappers in the JAX-RS way]. Your exception mapper may declare any of the following parameter types: .Table Exception mapper parameters |=== |Type|Usage |An exception type |Defines the exception type you want to handle |Any of the <> | |link:{jaxrsapi}/javax/ws/rs/container/ContainerRequestContext.html[`ContainerRequestContext`] |A context object to access the current request |=== It may declare any of the following return types: .Table Exception mapper return types |=== |Type|Usage |link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestResponse.html[`RestResponse`] or link:{jaxrsapi}/javax/ws/rs/core/Response.html[`Response`] |The response to send to the client when the exception occurs |link:{mutinyapi}/io/smallrye/mutiny/Uni.html[`Uni`] or link:{mutinyapi}/io/smallrye/mutiny/Uni.html[`Uni`] |An asynchronous response to send to the client when the exception occurs |=== === Request or response filters You can declare functions which are invoked in the following phases of the request processing: - Before the endpoint method is identified: pre-routing request filter - After routing, but before the endpoint method is called: normal request filter - After the endpoint method is called: response filter These filters allow you to do various things such as examine the request URI, HTTP method, influence routing, look or change request headers, abort the request, or modify the response. Request filters can be declared with the link:{resteasy-reactive-api}/org/jboss/resteasy/reactive/server/ServerRequestFilter.html[`@ServerRequestFilter`] annotation: [source,java] ---- import java.util.Optional; class Filters { @ServerRequestFilter(preMatching = true) public void preMatchingFilter(ContainerRequestContext requestContext) { // make sure we don't lose cheese lovers if(""yes"".equals(requestContext.getHeaderString(""Cheese""))) { requestContext.setRequestUri(URI.create(""/cheese"")); } } @ServerRequestFilter public Optional> getFilter(ContainerRequestContext ctx) { // only allow GET methods for now if(ctx.getMethod().equals(HttpMethod.GET)) { return Optional.of(RestResponse.status(Response.Status.METHOD_NOT_ALLOWED)); } return Optional.empty(); } } ---- [IMPORTANT] ==== Request filters are usually executed on the same thread that the method that handles the request will be executed. That means that if the method servicing the request is annotated with `@Blocking`, then the filters will also be run on the worker thread. If the method is annotated with `@NonBlocking` (or is not annotated at all), then the filters will also be run on the same event-loop thread. If however a filter needs to be run on the event-loop despite the fact that the method servicing the request will be run on a worker thread, then `@ServerRequestFilter(nonBlocking=true)` can be used. Note however, that these filters need to be run before **any** filter that does not use that setting and would run on a worker thread. ==== Similarly, response filters can be declared with the link:{resteasy-reactive-api}/org/jboss/resteasy/reactive/server/ServerResponseFilter.html[`@ServerResponseFilter`] annotation: [source,java] ---- class Filters { @ServerResponseFilter public void getFilter(ContainerResponseContext responseContext) { Object entity = responseContext.getEntity(); if(entity instanceof String) { // make it shout responseContext.setEntity(((String)entity).toUpperCase()); } } } ---- You can also link:{jaxrsspec}#filters[declare request and response filters in the JAX-RS way]. Your filters may declare any of the following parameter types: .Table Filter parameters |=== |Type|Usage |Any of the <> | |link:{jaxrsapi}/javax/ws/rs/container/ContainerRequestContext.html[`ContainerRequestContext`] |A context object to access the current request |link:{jaxrsapi}/javax/ws/rs/container/ContainerResponseContext.html[`ContainerResponseContext`] |A context object to access the current response |link:{jdkapi}/java/lang/Throwable.html[`Throwable`] |Any thrown exception, or `null` (only for response filters) |=== It may declare any of the following return types: .Table Filter return types |=== |Type|Usage |link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestResponse.html[`RestResponse`] or link:{jaxrsapi}/javax/ws/rs/core/Response.html[`Response`] |The response to send to the client instead of continuing the filter chain, or `null` if the filter chain should proceed |link:{jdkapi}/java/util/Optional.html[`Optional>`] or link:{jdkapi}/java/util/Optional.html[`Optional`] |An optional response to send to the client instead of continuing the filter chain, or an empty value if the filter chain should proceed |link:{mutinyapi}/io/smallrye/mutiny/Uni.html[`Uni>`] or link:{mutinyapi}/io/smallrye/mutiny/Uni.html[`Uni`] |An asynchronous response to send to the client instead of continuing the filter chain, or `null` if the filter chain should proceed |=== NOTE: You can restrict the Resource methods for which a filter runs, by using link:{jaxrsapi}/javax/ws/rs/NameBinding.html[`@NameBinding`] meta-annotations. === Readers and Writers: mapping entities and HTTP bodies [[readers-writers]] Whenever your endpoint methods return a object (of when they return a link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestResponse.html[`RestResponse`] or link:{jaxrsapi}/javax/ws/rs/core/Response.html[`Response`] with an entity), RESTEasy Reactive will look for a way to map that into an HTTP response body. Similarly, whenever your endpoint method takes an object as parameter, we will look for a way to map the HTTP request body into that object. This is done via a pluggable system of link:{jaxrsapi}/javax/ws/rs/ext/MessageBodyReader.html[`MessageBodyReader`] and link:{jaxrsapi}/javax/ws/rs/ext/MessageBodyWriter.html[`MessageBodyWriter`] interfaces, which are responsible for defining which Java type they map from/to, for which media types, and how they turn HTTP bodies to/from Java instances of that type. For example, if we have our own `FroMage` type on our endpoint: [source,java] ---- package org.acme.rest; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; class FroMage { public String name; public FroMage(String name) { this.name = name; } } @Path(""cheese"") public class Endpoint { @GET public FroMage sayCheese() { return new FroMage(""Cheeeeeese""); } @PUT public void addCheese(FroMage fromage) { System.err.println(""Received a new cheese: "" + fromage.name); } } ---- Then we can define how to read and write it with our body reader/writers, annotated with link:{jaxrsapi}/javax/ws/rs/ext/Provider.html[`@Provider`]: [source,java] ---- package org.acme.rest; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; @Provider public class FroMageBodyHandler implements MessageBodyReader, MessageBodyWriter { @Override public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return type == FroMage.class; } @Override public void writeTo(FroMage t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { entityStream.write((""[FroMageV1]"" + t.name) .getBytes(StandardCharsets.UTF_8)); } @Override public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return type == FroMage.class; } @Override public FroMage readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { String body = new String(entityStream.readAllBytes(), StandardCharsets.UTF_8); if(body.startsWith(""[FroMageV1]"")) return new FroMage(body.substring(11)); throw new IOException(""Invalid fromage: "" + body); } } ---- If you want to get the most performance our of your writer, you can extend the link:{resteasy-reactive-api}/org/jboss/resteasy/reactive/server/spi/ServerMessageBodyWriter.html[`ServerMessageBodyWriter`] instead of link:{jaxrsapi}/javax/ws/rs/ext/MessageBodyWriter.html[`MessageBodyWriter`] where you will be able to use less reflection and bypass the blocking IO layer: [source,java] ---- package org.acme.rest; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.Provider; import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo; import org.jboss.resteasy.reactive.server.spi.ServerMessageBodyWriter; import org.jboss.resteasy.reactive.server.spi.ServerRequestContext; @Provider public class FroMageBodyHandler implements MessageBodyReader, ServerMessageBodyWriter { // … @Override public boolean isWriteable(Class type, ResteasyReactiveResourceInfo target, MediaType mediaType) { return type == FroMage.class; } @Override public void writeResponse(FroMage t, ServerRequestContext context) throws WebApplicationException, IOException { context.serverResponse().end(""[FroMageV1]"" + t.name); } } ---- NOTE: You can restrict which content-types your reader/writer apply to by adding link:{jaxrsapi}/javax/ws/rs/Consumes.html[`Consumes`]/link:{jaxrsapi}/javax/ws/rs/Produces.html[`Produces`] annotations on your provider class. === Reader and Writer interceptors Just as you can intercept requests and responses, you can also intercept readers and writers, by extending the link:{jaxrsapi}/javax/ws/rs/ext/ReaderInterceptor.html[`ReaderInterceptor`] or link:{jaxrsapi}/javax/ws/rs/ext/WriterInterceptor.html[`WriterInterceptor`] on a class annotated with link:{jaxrsapi}/javax/ws/rs/ext/Provider.html[`@Provider`]. If we look at this endpoint: [source,java] ---- package org.acme.rest; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; @Path(""cheese"") public class Endpoint { @GET public String sayCheese() { return ""Cheeeeeese""; } @PUT public void addCheese(String fromage) { System.err.println(""Received a new cheese: "" + fromage); } } ---- We can add reader and writer interceptors like this: [source,java] ---- package org.acme.rest; import java.io.IOException; import javax.ws.rs.WebApplicationException; import javax.ws.rs.ext.Provider; import javax.ws.rs.ext.ReaderInterceptor; import javax.ws.rs.ext.ReaderInterceptorContext; import javax.ws.rs.ext.WriterInterceptor; import javax.ws.rs.ext.WriterInterceptorContext; @Provider public class FroMageIOInterceptor implements ReaderInterceptor, WriterInterceptor { @Override public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { System.err.println(""Before writing "" + context.getEntity()); context.proceed(); System.err.println(""After writing "" + context.getEntity()); } @Override public Object aroundReadFrom(ReaderInterceptorContext context) throws IOException, WebApplicationException { System.err.println(""Before reading "" + context.getGenericType()); Object entity = context.proceed(); System.err.println(""After reading "" + entity); return entity; } } ---- === Parameter mapping All <> can be declared as link:{jdkapi}/java/lang/String.html[`String`], but also any of the following types: - Types for which a link:{jaxrsapi}/javax/ws/rs/ext/ParamConverter.html[`ParamConverter`] is available via a registered link:{jaxrsapi}/javax/ws/rs/ext/ParamConverterProvider.html[`ParamConverterProvider`]. - Primitive types. - Types that have a constructor that accepts a single link:{jdkapi}/java/lang/String.html[`String`] argument. - Types that have a static method named `valueOf` or `fromString` with a single link:{jdkapi}/java/lang/String.html[`String`] argument that return an instance of the type. If both methods are present then `valueOf` will be used unless the type is an `enum` in which case `fromString` will be used. - link:{jdkapi}/java/util/List.html[`List`], link:{jdkapi}/java/util/Set.html[`Set`], or link:{jdkapi}/java/util/SortedSet.html[`SortedSet`], where `T` satisfies any above criterion. The following example illustrates all those possibilities: [source,java] ---- package org.acme.rest; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.ext.ParamConverter; import javax.ws.rs.ext.ParamConverterProvider; import javax.ws.rs.ext.Provider; import org.jboss.resteasy.reactive.RestQuery; @Provider class MyConverterProvider implements ParamConverterProvider { @Override public ParamConverter getConverter(Class rawType, Type genericType, Annotation[] annotations) { // declare a converter for this type if(rawType == Converter.class) { return (ParamConverter) new MyConverter(); } return null; } } // this is my custom converter class MyConverter implements ParamConverter { @Override public Converter fromString(String value) { return new Converter(value); } @Override public String toString(Converter value) { return value.value; } } // this uses a converter class Converter { String value; Converter(String value) { this.value = value; } } class Constructor { String value; // this will use the constructor public Constructor(String value) { this.value = value; } } class ValueOf { String value; private ValueOf(String value) { this.value = value; } // this will use the valueOf method public static ValueOf valueOf(String value) { return new ValueOf(value); } } @Path(""hello"") public class Endpoint { @Path(""{converter}/{constructor}/{primitive}/{valueOf}"") @GET public String convertions(Converter converter, Constructor constructor, int primitive, ValueOf valueOf, @RestQuery List list) { return converter + ""/"" + constructor + ""/"" + primitive + ""/"" + valueOf + ""/"" + list; } } ---- ==== Handling dates RESTEasy Reactive supports the use of the implementations of `java.time.Temporal` (like `java.time.LocalDateTime`) as query, path or form params. Furthermore it provides the `@org.jboss.resteasy.reactive.DateFormat` annotation which can be used to set a custom expected pattern (otherwise the JDK's default format for each type is used implicitly). === Preconditions https://tools.ietf.org/html/rfc7232[HTTP allows requests to be conditional], based on a number of conditions, such as: - Date of last resource modification - A resource tag, similar to a hash code of the resource to designate its state or version Let's see how you can do conditional request validation using the link:{jaxrsapi}/javax/ws/rs/core/Request.html[`Request`] context object: [source,java] ---- package org.acme.rest; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.time.temporal.TemporalUnit; import java.util.Date; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.core.EntityTag; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; @Path(""conditional"") public class Endpoint { // It's important to keep our date on seconds because that's how it's sent to the // user in the Last-Modified header private Date date = Date.from(Instant.now().truncatedTo(ChronoUnit.SECONDS)); private int version = 1; private EntityTag tag = new EntityTag(""v1""); private String resource = ""Some resource""; @GET public Response get(Request request) { // first evaluate preconditions ResponseBuilder conditionalResponse = request.evaluatePreconditions(date, tag); if(conditionalResponse != null) return conditionalResponse.build(); // preconditions are OK return Response.ok(resource) .lastModified(date) .tag(tag) .build(); } @PUT public Response put(Request request, String body) { // first evaluate preconditions ResponseBuilder conditionalResponse = request.evaluatePreconditions(date, tag); if(conditionalResponse != null) return conditionalResponse.build(); // preconditions are OK, we can update our resource resource = body; date = Date.from(Instant.now().truncatedTo(ChronoUnit.SECONDS)); version++; tag = new EntityTag(""v"" + version); return Response.ok(resource) .lastModified(date) .tag(tag) .build(); } } ---- When we call `GET /conditional` the first time, we will get this response: [source] ---- HTTP/1.1 200 OK Content-Type: text/plain;charset=UTF-8 ETag: ""v1"" Last-Modified: Wed, 09 Dec 2020 16:10:19 GMT Content-Length: 13 Some resource ---- So now if we want to check if we need to fetch a new version, we can make the following request: [source] ---- GET /conditional HTTP/1.1 Host: localhost:8080 If-Modified-Since: Wed, 09 Dec 2020 16:10:19 GMT ---- And we would get the following response: [source] ---- HTTP/1.1 304 Not Modified ---- Because the resource has not been modified since that date. This saves on sending the resource, but can also help your users detect concurrent modification, for example, let's suppose that one client wants to update the resource, but another user has modified it since. You can follow the previous `GET` request with this update: [source] ---- PUT /conditional HTTP/1.1 Host: localhost:8080 If-Unmodified-Since: Wed, 09 Dec 2020 16:25:43 GMT If-Match: v1 Content-Length: 8 Content-Type: text/plain newstuff ---- And if some other user has modified the resource between your `GET` and your `PUT` you would get this answer back: [source] ---- HTTP/1.1 412 Precondition Failed ETag: ""v2"" Content-Length: 0 ---- === Negotiation One of the main ideas of REST (https://tools.ietf.org/html/rfc7231#section-3.4[and HTTP]) is that your resource is independent from its representation, and that both the client and server are free to represent their resources in as many media types as they want. This allows the server to declare support for multiple representations and let the client declare which ones it supports and get served something appropriate. The following endpoint supports serving cheese in plain text or JSON: [source,java] ---- package org.acme.rest; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import com.fasterxml.jackson.annotation.JsonCreator; class FroMage { public String name; @JsonCreator public FroMage(String name) { this.name = name; } @Override public String toString() { return ""Cheese: "" + name; } } @Path(""negotiated"") public class Endpoint { @Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN}) @GET public FroMage get() { return new FroMage(""Morbier""); } @Consumes(MediaType.TEXT_PLAIN) @PUT public FroMage putString(String cheese) { return new FroMage(cheese); } @Consumes(MediaType.APPLICATION_JSON) @PUT public FroMage putJson(FroMage fromage) { return fromage; } } ---- The user will be able to select which representation it gets with the link:{httpspec}#section-5.3.2[`Accept`] header, in the case of JSON: [source,sh] ---- > GET /negotiated HTTP/1.1 > Host: localhost:8080 > Accept: application/json < HTTP/1.1 200 OK < Content-Type: application/json < Content-Length: 18 < < {""name"":""Morbier""} ---- And for text: [source,sh] ---- > GET /negotiated HTTP/1.1 > Host: localhost:8080 > Accept: text/plain > < HTTP/1.1 200 OK < Content-Type: text/plain < Content-Length: 15 < < Cheese: Morbier ---- Similarly, you can `PUT` two different representations. JSON: [source,sh] ---- > PUT /negotiated HTTP/1.1 > Host: localhost:8080 > Content-Type: application/json > Content-Length: 16 > > {""name"": ""brie""} < HTTP/1.1 200 OK < Content-Type: application/json;charset=UTF-8 < Content-Length: 15 < < {""name"":""brie""} ---- Or plain text: [source,sh] ---- > PUT /negotiated HTTP/1.1 > Host: localhost:8080 > Content-Type: text/plain > Content-Length: 9 > > roquefort < HTTP/1.1 200 OK < Content-Type: application/json;charset=UTF-8 < Content-Length: 20 < < {""name"":""roquefort""} ---- == Include/Exclude JAX-RS classes with build time conditions Quarkus enables the inclusion or exclusion of JAX-RS Resources, Providers and Features directly thanks to build time conditions in the same that it does for CDI beans. Thus, the various JAX-RS classes can be annotated with profile conditions (`@io.quarkus.arc.profile.IfBuildProfile` or `@io.quarkus.arc.profile.UnlessBuildProfile`) and/or with property conditions (`io.quarkus.arc.properties.IfBuildProperty` or `io.quarkus.arc.properties.UnlessBuildProperty`) to indicate to Quarkus at build time under which conditions these JAX-RS classes should be included. In the following example, Quarkus includes the endpoint `sayHello` if and only if the build profile `app1` has been enabled. [source,java] ---- @IfBuildProfile(""app1"") public class ResourceForApp1Only { @GET @Path(""sayHello"") public String sayHello() { return ""hello""; } } ---- Please note that if a JAX-RS Application has been detected and the method `getClasses()` and/or `getSingletons()` has/have been overridden, Quarkus will ignore the build time conditions and consider only what has been defined in the JAX-RS Application. == RESTEasy Reactive client In addition to the Server side, RESTEasy Reactive comes with a new MicroProfile Rest Client implementation that is non-blocking at its core. Please note that the `quarkus-rest-client` extension may not work properly with RESTEasy Reactive. See link:rest-client-reactive[REST Client Reactive Guide] for more information about the reactive client. ",16130,True,2838.9811060695415,median "----------------------------------------------------------------------- -- AWA.Questions.Models -- AWA.Questions.Models ----------------------------------------------------------------------- -- File generated by ada-gen DO NOT MODIFY -- Template used: templates/model/package-body.xhtml -- Ada Generator: https://ada-gen.googlecode.com/svn/trunk Revision 1095 ----------------------------------------------------------------------- -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- 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. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Beans.Objects.Time; with ASF.Events.Faces.Actions; package body AWA.Questions.Models is use type ADO.Objects.Object_Record_Access; use type ADO.Objects.Object_Ref; use type ADO.Objects.Object_Record; function Question_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => QUESTION_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Question_Key; function Question_Key (Id : in String) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => QUESTION_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Question_Key; function ""="" (Left, Right : Question_Ref'Class) return Boolean is begin return ADO.Objects.Object_Ref'Class (Left) = ADO.Objects.Object_Ref'Class (Right); end ""=""; procedure Set_Field (Object : in out Question_Ref'Class; Impl : out Question_Access) is Result : ADO.Objects.Object_Record_Access; begin Object.Prepare_Modify (Result); Impl := Question_Impl (Result.all)'Access; end Set_Field; -- Internal method to allocate the Object_Record instance procedure Allocate (Object : in out Question_Ref) is Impl : Question_Access; begin Impl := new Question_Impl; Impl.Create_Date := ADO.DEFAULT_TIME; Impl.Edit_Date := ADO.DEFAULT_TIME; Impl.Rating := 0; Impl.Version := 0; ADO.Objects.Set_Object (Object, Impl.all'Access); end Allocate; -- ---------------------------------------- -- Data object: Question -- ---------------------------------------- procedure Set_Create_Date (Object : in out Question_Ref; Value : in Ada.Calendar.Time) is Impl : Question_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Time (Impl.all, 1, Impl.Create_Date, Value); end Set_Create_Date; function Get_Create_Date (Object : in Question_Ref) return Ada.Calendar.Time is Impl : constant Question_Access := Question_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Create_Date; end Get_Create_Date; procedure Set_Title (Object : in out Question_Ref; Value : in String) is Impl : Question_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_String (Impl.all, 2, Impl.Title, Value); end Set_Title; procedure Set_Title (Object : in out Question_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String) is Impl : Question_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Unbounded_String (Impl.all, 2, Impl.Title, Value); end Set_Title; function Get_Title (Object : in Question_Ref) return String is begin return Ada.Strings.Unbounded.To_String (Object.Get_Title); end Get_Title; function Get_Title (Object : in Question_Ref) return Ada.Strings.Unbounded.Unbounded_String is Impl : constant Question_Access := Question_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Title; end Get_Title; procedure Set_Description (Object : in out Question_Ref; Value : in String) is Impl : Question_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_String (Impl.all, 3, Impl.Description, Value); end Set_Description; procedure Set_Description (Object : in out Question_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String) is Impl : Question_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Unbounded_String (Impl.all, 3, Impl.Description, Value); end Set_Description; function Get_Description (Object : in Question_Ref) return String is begin return Ada.Strings.Unbounded.To_String (Object.Get_Description); end Get_Description; function Get_Description (Object : in Question_Ref) return Ada.Strings.Unbounded.Unbounded_String is Impl : constant Question_Access := Question_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Description; end Get_Description; procedure Set_Edit_Date (Object : in out Question_Ref; Value : in Ada.Calendar.Time) is Impl : Question_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Time (Impl.all, 4, Impl.Edit_Date, Value); end Set_Edit_Date; function Get_Edit_Date (Object : in Question_Ref) return Ada.Calendar.Time is Impl : constant Question_Access := Question_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Edit_Date; end Get_Edit_Date; procedure Set_Short_Description (Object : in out Question_Ref; Value : in String) is Impl : Question_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_String (Impl.all, 5, Impl.Short_Description, Value); end Set_Short_Description; procedure Set_Short_Description (Object : in out Question_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String) is Impl : Question_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Unbounded_String (Impl.all, 5, Impl.Short_Description, Value); end Set_Short_Description; function Get_Short_Description (Object : in Question_Ref) return String is begin return Ada.Strings.Unbounded.To_String (Object.Get_Short_Description); end Get_Short_Description; function Get_Short_Description (Object : in Question_Ref) return Ada.Strings.Unbounded.Unbounded_String is Impl : constant Question_Access := Question_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Short_Description; end Get_Short_Description; procedure Set_Rating (Object : in out Question_Ref; Value : in Integer) is Impl : Question_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Integer (Impl.all, 6, Impl.Rating, Value); end Set_Rating; function Get_Rating (Object : in Question_Ref) return Integer is Impl : constant Question_Access := Question_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Rating; end Get_Rating; procedure Set_Id (Object : in out Question_Ref; Value : in ADO.Identifier) is Impl : Question_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Key_Value (Impl.all, 7, Value); end Set_Id; function Get_Id (Object : in Question_Ref) return ADO.Identifier is Impl : constant Question_Access := Question_Impl (Object.Get_Object.all)'Access; begin return Impl.Get_Key_Value; end Get_Id; function Get_Version (Object : in Question_Ref) return Integer is Impl : constant Question_Access := Question_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Version; end Get_Version; procedure Set_Author (Object : in out Question_Ref; Value : in AWA.Users.Models.User_Ref'Class) is Impl : Question_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Object (Impl.all, 9, Impl.Author, Value); end Set_Author; function Get_Author (Object : in Question_Ref) return AWA.Users.Models.User_Ref'Class is Impl : constant Question_Access := Question_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Author; end Get_Author; procedure Set_Workspace (Object : in out Question_Ref; Value : in AWA.Workspaces.Models.Workspace_Ref'Class) is Impl : Question_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Object (Impl.all, 10, Impl.Workspace, Value); end Set_Workspace; function Get_Workspace (Object : in Question_Ref) return AWA.Workspaces.Models.Workspace_Ref'Class is Impl : constant Question_Access := Question_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Workspace; end Get_Workspace; procedure Set_Accepted_Answer (Object : in out Question_Ref; Value : in AWA.Questions.Models.Answer_Ref'Class) is Impl : Question_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Object (Impl.all, 11, Impl.Accepted_Answer, Value); end Set_Accepted_Answer; function Get_Accepted_Answer (Object : in Question_Ref) return AWA.Questions.Models.Answer_Ref'Class is Impl : constant Question_Access := Question_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Accepted_Answer; end Get_Accepted_Answer; -- Copy of the object. procedure Copy (Object : in Question_Ref; Into : in out Question_Ref) is Result : Question_Ref; begin if not Object.Is_Null then declare Impl : constant Question_Access := Question_Impl (Object.Get_Load_Object.all)'Access; Copy : constant Question_Access := new Question_Impl; begin ADO.Objects.Set_Object (Result, Copy.all'Access); Copy.Copy (Impl.all); Copy.Create_Date := Impl.Create_Date; Copy.Title := Impl.Title; Copy.Description := Impl.Description; Copy.Edit_Date := Impl.Edit_Date; Copy.Short_Description := Impl.Short_Description; Copy.Rating := Impl.Rating; Copy.Version := Impl.Version; Copy.Author := Impl.Author; Copy.Workspace := Impl.Workspace; Copy.Accepted_Answer := Impl.Accepted_Answer; end; end if; Into := Result; end Copy; procedure Find (Object : in out Question_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Impl : constant Question_Access := new Question_Impl; begin Impl.Find (Session, Query, Found); if Found then ADO.Objects.Set_Object (Object, Impl.all'Access); else ADO.Objects.Set_Object (Object, null); Destroy (Impl); end if; end Find; procedure Load (Object : in out Question_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier) is Impl : constant Question_Access := new Question_Impl; Found : Boolean; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter (""id = ?""); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); raise ADO.Objects.NOT_FOUND; end if; ADO.Objects.Set_Object (Object, Impl.all'Access); end Load; procedure Load (Object : in out Question_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean) is Impl : constant Question_Access := new Question_Impl; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter (""id = ?""); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); else ADO.Objects.Set_Object (Object, Impl.all'Access); end if; end Load; procedure Save (Object : in out Question_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl = null then Impl := new Question_Impl; ADO.Objects.Set_Object (Object, Impl); end if; if not ADO.Objects.Is_Created (Impl.all) then Impl.Create (Session); else Impl.Save (Session); end if; end Save; procedure Delete (Object : in out Question_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : constant ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl /= null then Impl.Delete (Session); end if; end Delete; -- -------------------- -- Free the object -- -------------------- procedure Destroy (Object : access Question_Impl) is type Question_Impl_Ptr is access all Question_Impl; procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Question_Impl, Question_Impl_Ptr); pragma Warnings (Off, ""*redundant conversion*""); Ptr : Question_Impl_Ptr := Question_Impl (Object.all)'Access; pragma Warnings (On, ""*redundant conversion*""); begin Unchecked_Free (Ptr); end Destroy; procedure Find (Object : in out Question_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query, QUESTION_DEF'Access); begin Stmt.Execute; if Stmt.Has_Elements then Object.Load (Stmt, Session); Stmt.Next; Found := not Stmt.Has_Elements; else Found := False; end if; end Find; overriding procedure Load (Object : in out Question_Impl; Session : in out ADO.Sessions.Session'Class) is Found : Boolean; Query : ADO.SQL.Query; Id : constant ADO.Identifier := Object.Get_Key_Value; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter (""id = ?""); Object.Find (Session, Query, Found); if not Found then raise ADO.Objects.NOT_FOUND; end if; end Load; procedure Save (Object : in out Question_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Update_Statement := Session.Create_Statement (QUESTION_DEF'Access); begin if Object.Is_Modified (1) then Stmt.Save_Field (Name => COL_0_1_NAME, -- create_date Value => Object.Create_Date); Object.Clear_Modified (1); end if; if Object.Is_Modified (2) then Stmt.Save_Field (Name => COL_1_1_NAME, -- title Value => Object.Title); Object.Clear_Modified (2); end if; if Object.Is_Modified (3) then Stmt.Save_Field (Name => COL_2_1_NAME, -- description Value => Object.Description); Object.Clear_Modified (3); end if; if Object.Is_Modified (4) then Stmt.Save_Field (Name => COL_3_1_NAME, -- edit_date Value => Object.Edit_Date); Object.Clear_Modified (4); end if; if Object.Is_Modified (5) then Stmt.Save_Field (Name => COL_4_1_NAME, -- short_description Value => Object.Short_Description); Object.Clear_Modified (5); end if; if Object.Is_Modified (6) then Stmt.Save_Field (Name => COL_5_1_NAME, -- rating Value => Object.Rating); Object.Clear_Modified (6); end if; if Object.Is_Modified (7) then Stmt.Save_Field (Name => COL_6_1_NAME, -- id Value => Object.Get_Key); Object.Clear_Modified (7); end if; if Object.Is_Modified (9) then Stmt.Save_Field (Name => COL_8_1_NAME, -- author_id Value => Object.Author); Object.Clear_Modified (9); end if; if Object.Is_Modified (10) then Stmt.Save_Field (Name => COL_9_1_NAME, -- workspace_id Value => Object.Workspace); Object.Clear_Modified (10); end if; if Object.Is_Modified (11) then Stmt.Save_Field (Name => COL_10_1_NAME, -- accepted_answer_id Value => Object.Accepted_Answer); Object.Clear_Modified (11); end if; if Stmt.Has_Save_Fields then Object.Version := Object.Version + 1; Stmt.Save_Field (Name => ""version"", Value => Object.Version); Stmt.Set_Filter (Filter => ""id = ? and version = ?""); Stmt.Add_Param (Value => Object.Get_Key); Stmt.Add_Param (Value => Object.Version - 1); declare Result : Integer; begin Stmt.Execute (Result); if Result /= 1 then if Result /= 0 then raise ADO.Objects.UPDATE_ERROR; else raise ADO.Objects.LAZY_LOCK; end if; end if; end; end if; end Save; procedure Create (Object : in out Question_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Query : ADO.Statements.Insert_Statement := Session.Create_Statement (QUESTION_DEF'Access); Result : Integer; begin Object.Version := 1; Query.Save_Field (Name => COL_0_1_NAME, -- create_date Value => Object.Create_Date); Query.Save_Field (Name => COL_1_1_NAME, -- title Value => Object.Title); Query.Save_Field (Name => COL_2_1_NAME, -- description Value => Object.Description); Query.Save_Field (Name => COL_3_1_NAME, -- edit_date Value => Object.Edit_Date); Query.Save_Field (Name => COL_4_1_NAME, -- short_description Value => Object.Short_Description); Query.Save_Field (Name => COL_5_1_NAME, -- rating Value => Object.Rating); Session.Allocate (Id => Object); Query.Save_Field (Name => COL_6_1_NAME, -- id Value => Object.Get_Key); Query.Save_Field (Name => COL_7_1_NAME, -- version Value => Object.Version); Query.Save_Field (Name => COL_8_1_NAME, -- author_id Value => Object.Author); Query.Save_Field (Name => COL_9_1_NAME, -- workspace_id Value => Object.Workspace); Query.Save_Field (Name => COL_10_1_NAME, -- accepted_answer_id Value => Object.Accepted_Answer); Query.Execute (Result); if Result /= 1 then raise ADO.Objects.INSERT_ERROR; end if; ADO.Objects.Set_Created (Object); end Create; procedure Delete (Object : in out Question_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Delete_Statement := Session.Create_Statement (QUESTION_DEF'Access); begin Stmt.Set_Filter (Filter => ""id = ?""); Stmt.Add_Param (Value => Object.Get_Key); Stmt.Execute; end Delete; function Get_Value (From : in Question_Ref; Name : in String) return Util.Beans.Objects.Object is Obj : constant ADO.Objects.Object_Record_Access := From.Get_Load_Object; Impl : access Question_Impl; begin if Obj = null then return Util.Beans.Objects.Null_Object; end if; Impl := Question_Impl (Obj.all)'Access; if Name = ""create_date"" then return Util.Beans.Objects.Time.To_Object (Impl.Create_Date); elsif Name = ""title"" then return Util.Beans.Objects.To_Object (Impl.Title); elsif Name = ""description"" then return Util.Beans.Objects.To_Object (Impl.Description); elsif Name = ""edit_date"" then return Util.Beans.Objects.Time.To_Object (Impl.Edit_Date); elsif Name = ""short_description"" then return Util.Beans.Objects.To_Object (Impl.Short_Description); elsif Name = ""rating"" then return Util.Beans.Objects.To_Object (Long_Long_Integer (Impl.Rating)); elsif Name = ""id"" then return ADO.Objects.To_Object (Impl.Get_Key); end if; return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- Load the object from current iterator position -- ------------------------------ procedure Load (Object : in out Question_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class) is begin Object.Create_Date := Stmt.Get_Time (0); Object.Title := Stmt.Get_Unbounded_String (1); Object.Description := Stmt.Get_Unbounded_String (2); Object.Edit_Date := Stmt.Get_Time (3); Object.Short_Description := Stmt.Get_Unbounded_String (4); Object.Rating := Stmt.Get_Integer (5); Object.Set_Key_Value (Stmt.Get_Identifier (6)); if not Stmt.Is_Null (8) then Object.Author.Set_Key_Value (Stmt.Get_Identifier (8), Session); end if; if not Stmt.Is_Null (9) then Object.Workspace.Set_Key_Value (Stmt.Get_Identifier (9), Session); end if; if not Stmt.Is_Null (10) then Object.Accepted_Answer.Set_Key_Value (Stmt.Get_Identifier (10), Session); end if; Object.Version := Stmt.Get_Integer (7); ADO.Objects.Set_Created (Object); end Load; function Answer_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => ANSWER_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Answer_Key; function Answer_Key (Id : in String) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => ANSWER_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Answer_Key; function ""="" (Left, Right : Answer_Ref'Class) return Boolean is begin return ADO.Objects.Object_Ref'Class (Left) = ADO.Objects.Object_Ref'Class (Right); end ""=""; procedure Set_Field (Object : in out Answer_Ref'Class; Impl : out Answer_Access) is Result : ADO.Objects.Object_Record_Access; begin Object.Prepare_Modify (Result); Impl := Answer_Impl (Result.all)'Access; end Set_Field; -- Internal method to allocate the Object_Record instance procedure Allocate (Object : in out Answer_Ref) is Impl : Answer_Access; begin Impl := new Answer_Impl; Impl.Create_Date := ADO.DEFAULT_TIME; Impl.Edit_Date.Is_Null := True; Impl.Rank := 0; Impl.Version := 0; ADO.Objects.Set_Object (Object, Impl.all'Access); end Allocate; -- ---------------------------------------- -- Data object: Answer -- ---------------------------------------- procedure Set_Create_Date (Object : in out Answer_Ref; Value : in Ada.Calendar.Time) is Impl : Answer_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Time (Impl.all, 1, Impl.Create_Date, Value); end Set_Create_Date; function Get_Create_Date (Object : in Answer_Ref) return Ada.Calendar.Time is Impl : constant Answer_Access := Answer_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Create_Date; end Get_Create_Date; procedure Set_Edit_Date (Object : in out Answer_Ref; Value : in ADO.Nullable_Time) is Impl : Answer_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Time (Impl.all, 2, Impl.Edit_Date, Value); end Set_Edit_Date; function Get_Edit_Date (Object : in Answer_Ref) return ADO.Nullable_Time is Impl : constant Answer_Access := Answer_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Edit_Date; end Get_Edit_Date; procedure Set_Answer (Object : in out Answer_Ref; Value : in String) is Impl : Answer_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_String (Impl.all, 3, Impl.Answer, Value); end Set_Answer; procedure Set_Answer (Object : in out Answer_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String) is Impl : Answer_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Unbounded_String (Impl.all, 3, Impl.Answer, Value); end Set_Answer; function Get_Answer (Object : in Answer_Ref) return String is begin return Ada.Strings.Unbounded.To_String (Object.Get_Answer); end Get_Answer; function Get_Answer (Object : in Answer_Ref) return Ada.Strings.Unbounded.Unbounded_String is Impl : constant Answer_Access := Answer_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Answer; end Get_Answer; procedure Set_Rank (Object : in out Answer_Ref; Value : in Integer) is Impl : Answer_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Integer (Impl.all, 4, Impl.Rank, Value); end Set_Rank; function Get_Rank (Object : in Answer_Ref) return Integer is Impl : constant Answer_Access := Answer_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Rank; end Get_Rank; procedure Set_Id (Object : in out Answer_Ref; Value : in ADO.Identifier) is Impl : Answer_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Key_Value (Impl.all, 5, Value); end Set_Id; function Get_Id (Object : in Answer_Ref) return ADO.Identifier is Impl : constant Answer_Access := Answer_Impl (Object.Get_Object.all)'Access; begin return Impl.Get_Key_Value; end Get_Id; function Get_Version (Object : in Answer_Ref) return Integer is Impl : constant Answer_Access := Answer_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Version; end Get_Version; procedure Set_Author (Object : in out Answer_Ref; Value : in AWA.Users.Models.User_Ref'Class) is Impl : Answer_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Object (Impl.all, 7, Impl.Author, Value); end Set_Author; function Get_Author (Object : in Answer_Ref) return AWA.Users.Models.User_Ref'Class is Impl : constant Answer_Access := Answer_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Author; end Get_Author; procedure Set_Question (Object : in out Answer_Ref; Value : in AWA.Questions.Models.Question_Ref'Class) is Impl : Answer_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Object (Impl.all, 8, Impl.Question, Value); end Set_Question; function Get_Question (Object : in Answer_Ref) return AWA.Questions.Models.Question_Ref'Class is Impl : constant Answer_Access := Answer_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Question; end Get_Question; -- Copy of the object. procedure Copy (Object : in Answer_Ref; Into : in out Answer_Ref) is Result : Answer_Ref; begin if not Object.Is_Null then declare Impl : constant Answer_Access := Answer_Impl (Object.Get_Load_Object.all)'Access; Copy : constant Answer_Access := new Answer_Impl; begin ADO.Objects.Set_Object (Result, Copy.all'Access); Copy.Copy (Impl.all); Copy.Create_Date := Impl.Create_Date; Copy.Edit_Date := Impl.Edit_Date; Copy.Answer := Impl.Answer; Copy.Rank := Impl.Rank; Copy.Version := Impl.Version; Copy.Author := Impl.Author; Copy.Question := Impl.Question; end; end if; Into := Result; end Copy; procedure Find (Object : in out Answer_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Impl : constant Answer_Access := new Answer_Impl; begin Impl.Find (Session, Query, Found); if Found then ADO.Objects.Set_Object (Object, Impl.all'Access); else ADO.Objects.Set_Object (Object, null); Destroy (Impl); end if; end Find; procedure Load (Object : in out Answer_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier) is Impl : constant Answer_Access := new Answer_Impl; Found : Boolean; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter (""id = ?""); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); raise ADO.Objects.NOT_FOUND; end if; ADO.Objects.Set_Object (Object, Impl.all'Access); end Load; procedure Load (Object : in out Answer_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean) is Impl : constant Answer_Access := new Answer_Impl; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter (""id = ?""); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); else ADO.Objects.Set_Object (Object, Impl.all'Access); end if; end Load; procedure Save (Object : in out Answer_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl = null then Impl := new Answer_Impl; ADO.Objects.Set_Object (Object, Impl); end if; if not ADO.Objects.Is_Created (Impl.all) then Impl.Create (Session); else Impl.Save (Session); end if; end Save; procedure Delete (Object : in out Answer_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : constant ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl /= null then Impl.Delete (Session); end if; end Delete; -- -------------------- -- Free the object -- -------------------- procedure Destroy (Object : access Answer_Impl) is type Answer_Impl_Ptr is access all Answer_Impl; procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Answer_Impl, Answer_Impl_Ptr); pragma Warnings (Off, ""*redundant conversion*""); Ptr : Answer_Impl_Ptr := Answer_Impl (Object.all)'Access; pragma Warnings (On, ""*redundant conversion*""); begin Unchecked_Free (Ptr); end Destroy; procedure Find (Object : in out Answer_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query, ANSWER_DEF'Access); begin Stmt.Execute; if Stmt.Has_Elements then Object.Load (Stmt, Session); Stmt.Next; Found := not Stmt.Has_Elements; else Found := False; end if; end Find; overriding procedure Load (Object : in out Answer_Impl; Session : in out ADO.Sessions.Session'Class) is Found : Boolean; Query : ADO.SQL.Query; Id : constant ADO.Identifier := Object.Get_Key_Value; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter (""id = ?""); Object.Find (Session, Query, Found); if not Found then raise ADO.Objects.NOT_FOUND; end if; end Load; procedure Save (Object : in out Answer_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Update_Statement := Session.Create_Statement (ANSWER_DEF'Access); begin if Object.Is_Modified (1) then Stmt.Save_Field (Name => COL_0_2_NAME, -- create_date Value => Object.Create_Date); Object.Clear_Modified (1); end if; if Object.Is_Modified (2) then Stmt.Save_Field (Name => COL_1_2_NAME, -- edit_date Value => Object.Edit_Date); Object.Clear_Modified (2); end if; if Object.Is_Modified (3) then Stmt.Save_Field (Name => COL_2_2_NAME, -- answer Value => Object.Answer); Object.Clear_Modified (3); end if; if Object.Is_Modified (4) then Stmt.Save_Field (Name => COL_3_2_NAME, -- rank Value => Object.Rank); Object.Clear_Modified (4); end if; if Object.Is_Modified (5) then Stmt.Save_Field (Name => COL_4_2_NAME, -- id Value => Object.Get_Key); Object.Clear_Modified (5); end if; if Object.Is_Modified (7) then Stmt.Save_Field (Name => COL_6_2_NAME, -- author_id Value => Object.Author); Object.Clear_Modified (7); end if; if Object.Is_Modified (8) then Stmt.Save_Field (Name => COL_7_2_NAME, -- question_id Value => Object.Question); Object.Clear_Modified (8); end if; if Stmt.Has_Save_Fields then Object.Version := Object.Version + 1; Stmt.Save_Field (Name => ""version"", Value => Object.Version); Stmt.Set_Filter (Filter => ""id = ? and version = ?""); Stmt.Add_Param (Value => Object.Get_Key); Stmt.Add_Param (Value => Object.Version - 1); declare Result : Integer; begin Stmt.Execute (Result); if Result /= 1 then if Result /= 0 then raise ADO.Objects.UPDATE_ERROR; else raise ADO.Objects.LAZY_LOCK; end if; end if; end; end if; end Save; procedure Create (Object : in out Answer_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Query : ADO.Statements.Insert_Statement := Session.Create_Statement (ANSWER_DEF'Access); Result : Integer; begin Object.Version := 1; Query.Save_Field (Name => COL_0_2_NAME, -- create_date Value => Object.Create_Date); Query.Save_Field (Name => COL_1_2_NAME, -- edit_date Value => Object.Edit_Date); Query.Save_Field (Name => COL_2_2_NAME, -- answer Value => Object.Answer); Query.Save_Field (Name => COL_3_2_NAME, -- rank Value => Object.Rank); Session.Allocate (Id => Object); Query.Save_Field (Name => COL_4_2_NAME, -- id Value => Object.Get_Key); Query.Save_Field (Name => COL_5_2_NAME, -- version Value => Object.Version); Query.Save_Field (Name => COL_6_2_NAME, -- author_id Value => Object.Author); Query.Save_Field (Name => COL_7_2_NAME, -- question_id Value => Object.Question); Query.Execute (Result); if Result /= 1 then raise ADO.Objects.INSERT_ERROR; end if; ADO.Objects.Set_Created (Object); end Create; procedure Delete (Object : in out Answer_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Delete_Statement := Session.Create_Statement (ANSWER_DEF'Access); begin Stmt.Set_Filter (Filter => ""id = ?""); Stmt.Add_Param (Value => Object.Get_Key); Stmt.Execute; end Delete; function Get_Value (From : in Answer_Ref; Name : in String) return Util.Beans.Objects.Object is Obj : constant ADO.Objects.Object_Record_Access := From.Get_Load_Object; Impl : access Answer_Impl; begin if Obj = null then return Util.Beans.Objects.Null_Object; end if; Impl := Answer_Impl (Obj.all)'Access; if Name = ""create_date"" then return Util.Beans.Objects.Time.To_Object (Impl.Create_Date); elsif Name = ""edit_date"" then if Impl.Edit_Date.Is_Null then return Util.Beans.Objects.Null_Object; else return Util.Beans.Objects.Time.To_Object (Impl.Edit_Date.Value); end if; elsif Name = ""answer"" then return Util.Beans.Objects.To_Object (Impl.Answer); elsif Name = ""rank"" then return Util.Beans.Objects.To_Object (Long_Long_Integer (Impl.Rank)); elsif Name = ""id"" then return ADO.Objects.To_Object (Impl.Get_Key); end if; return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- Load the object from current iterator position -- ------------------------------ procedure Load (Object : in out Answer_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class) is begin Object.Create_Date := Stmt.Get_Time (0); Object.Edit_Date := Stmt.Get_Time (1); Object.Answer := Stmt.Get_Unbounded_String (2); Object.Rank := Stmt.Get_Integer (3); Object.Set_Key_Value (Stmt.Get_Identifier (4)); if not Stmt.Is_Null (6) then Object.Author.Set_Key_Value (Stmt.Get_Identifier (6), Session); end if; if not Stmt.Is_Null (7) then Object.Question.Set_Key_Value (Stmt.Get_Identifier (7), Session); end if; Object.Version := Stmt.Get_Integer (5); ADO.Objects.Set_Created (Object); end Load; -- -------------------- -- Get the bean attribute identified by the given name. -- -------------------- overriding function Get_Value (From : in Answer_Info; Name : in String) return Util.Beans.Objects.Object is begin if Name = ""id"" then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Id)); end if; if Name = ""create_date"" then return Util.Beans.Objects.Time.To_Object (From.Create_Date); end if; if Name = ""edit_date"" then return Util.Beans.Objects.Time.To_Object (From.Edit_Date); end if; if Name = ""answer"" then return Util.Beans.Objects.To_Object (From.Answer); end if; if Name = ""rank"" then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Rank)); end if; if Name = ""user_rating"" then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.User_Rating)); end if; if Name = ""author_id"" then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Author_Id)); end if; if Name = ""author_name"" then return Util.Beans.Objects.To_Object (From.Author_Name); end if; if Name = ""author_email"" then return Util.Beans.Objects.To_Object (From.Author_Email); end if; return Util.Beans.Objects.Null_Object; end Get_Value; -- -------------------- -- Run the query controlled by Context and append the list in Object. -- -------------------- procedure List (Object : in out Answer_Info_List_Bean'Class; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class) is begin List (Object.List, Session, Context); end List; -- -------------------- -- The list of answers. -- -------------------- procedure List (Object : in out Answer_Info_Vector; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class) is procedure Read (Into : in out Answer_Info); Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Context); Pos : Natural := 0; procedure Read (Into : in out Answer_Info) is begin Into.Id := Stmt.Get_Identifier (0); Into.Create_Date := Stmt.Get_Time (1); Into.Edit_Date := Stmt.Get_Time (2); Into.Answer := Stmt.Get_Unbounded_String (3); Into.Rank := Stmt.Get_Integer (4); Into.User_Rating := Stmt.Get_Integer (5); Into.Author_Id := Stmt.Get_Identifier (6); Into.Author_Name := Stmt.Get_Unbounded_String (7); Into.Author_Email := Stmt.Get_Unbounded_String (8); end Read; begin Stmt.Execute; Answer_Info_Vectors.Clear (Object); while Stmt.Has_Elements loop Object.Insert_Space (Before => Pos); Object.Update_Element (Index => Pos, Process => Read'Access); Pos := Pos + 1; Stmt.Next; end loop; end List; -- -------------------- -- Get the bean attribute identified by the given name. -- -------------------- overriding function Get_Value (From : in Question_Display_Info; Name : in String) return Util.Beans.Objects.Object is begin if Name = ""id"" then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Id)); end if; if Name = ""title"" then return Util.Beans.Objects.To_Object (From.Title); end if; if Name = ""create_date"" then return Util.Beans.Objects.Time.To_Object (From.Create_Date); end if; if Name = ""edit_date"" then return Util.Beans.Objects.Time.To_Object (From.Edit_Date); end if; if Name = ""description"" then return Util.Beans.Objects.To_Object (From.Description); end if; if Name = ""rating"" then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Rating)); end if; if Name = ""user_rating"" then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.User_Rating)); end if; if Name = ""author_id"" then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Author_Id)); end if; if Name = ""author_name"" then return Util.Beans.Objects.To_Object (From.Author_Name); end if; if Name = ""author_email"" then return Util.Beans.Objects.To_Object (From.Author_Email); end if; return Util.Beans.Objects.Null_Object; end Get_Value; -- -------------------- -- Run the query controlled by Context and append the list in Object. -- -------------------- procedure List (Object : in out Question_Display_Info_List_Bean'Class; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class) is begin List (Object.List, Session, Context); end List; -- -------------------- -- The list of questions. -- -------------------- procedure List (Object : in out Question_Display_Info_Vector; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class) is procedure Read (Into : in out Question_Display_Info); Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Context); Pos : Natural := 0; procedure Read (Into : in out Question_Display_Info) is begin Into.Id := Stmt.Get_Identifier (0); Into.Title := Stmt.Get_Unbounded_String (1); Into.Create_Date := Stmt.Get_Time (2); Into.Edit_Date := Stmt.Get_Time (3); Into.Description := Stmt.Get_Unbounded_String (4); Into.Rating := Stmt.Get_Integer (5); Into.User_Rating := Stmt.Get_Integer (6); Into.Author_Id := Stmt.Get_Identifier (7); Into.Author_Name := Stmt.Get_Unbounded_String (8); Into.Author_Email := Stmt.Get_Unbounded_String (9); end Read; begin Stmt.Execute; Question_Display_Info_Vectors.Clear (Object); while Stmt.Has_Elements loop Object.Insert_Space (Before => Pos); Object.Update_Element (Index => Pos, Process => Read'Access); Pos := Pos + 1; Stmt.Next; end loop; end List; -- -------------------- -- Get the bean attribute identified by the given name. -- -------------------- overriding function Get_Value (From : in Question_Info; Name : in String) return Util.Beans.Objects.Object is begin if Name = ""id"" then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Id)); end if; if Name = ""title"" then return Util.Beans.Objects.To_Object (From.Title); end if; if Name = ""create_date"" then return Util.Beans.Objects.Time.To_Object (From.Create_Date); end if; if Name = ""description"" then return Util.Beans.Objects.To_Object (From.Description); end if; if Name = ""rating"" then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Rating)); end if; if Name = ""answer_count"" then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Answer_Count)); end if; if Name = ""author_id"" then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Author_Id)); end if; if Name = ""author_name"" then return Util.Beans.Objects.To_Object (From.Author_Name); end if; if Name = ""author_email"" then return Util.Beans.Objects.To_Object (From.Author_Email); end if; return Util.Beans.Objects.Null_Object; end Get_Value; -- -------------------- -- Run the query controlled by Context and append the list in Object. -- -------------------- procedure List (Object : in out Question_Info_List_Bean'Class; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class) is begin List (Object.List, Session, Context); end List; -- -------------------- -- The list of questions. -- -------------------- procedure List (Object : in out Question_Info_Vector; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class) is procedure Read (Into : in out Question_Info); Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Context); Pos : Natural := 0; procedure Read (Into : in out Question_Info) is begin Into.Id := Stmt.Get_Identifier (0); Into.Title := Stmt.Get_Unbounded_String (1); Into.Create_Date := Stmt.Get_Time (2); Into.Description := Stmt.Get_Unbounded_String (3); Into.Rating := Stmt.Get_Integer (4); Into.Answer_Count := Stmt.Get_Integer (5); Into.Author_Id := Stmt.Get_Identifier (6); Into.Author_Name := Stmt.Get_Unbounded_String (7); Into.Author_Email := Stmt.Get_Unbounded_String (8); end Read; begin Stmt.Execute; Question_Info_Vectors.Clear (Object); while Stmt.Has_Elements loop Object.Insert_Space (Before => Pos); Object.Update_Element (Index => Pos, Process => Read'Access); Pos := Pos + 1; Stmt.Next; end loop; end List; procedure Op_Save (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); procedure Op_Save (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Question_Bean'Class (Bean).Save (Outcome); end Op_Save; package Binding_Question_Bean_1 is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Question_Bean, Method => Op_Save, Name => ""save""); procedure Op_Delete (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); procedure Op_Delete (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Question_Bean'Class (Bean).Delete (Outcome); end Op_Delete; package Binding_Question_Bean_2 is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Question_Bean, Method => Op_Delete, Name => ""delete""); Binding_Question_Bean_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Binding_Question_Bean_1.Proxy'Access, 2 => Binding_Question_Bean_2.Proxy'Access ); -- This bean provides some methods that can be used in a Method_Expression. overriding function Get_Method_Bindings (From : in Question_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is begin return Binding_Question_Bean_Array'Access; end Get_Method_Bindings; -- Set the value identified by the name overriding procedure Set_Value (Item : in out Question_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin null; end Set_Value; procedure Op_Save (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); procedure Op_Save (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Answer_Bean'Class (Bean).Save (Outcome); end Op_Save; package Binding_Answer_Bean_1 is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Answer_Bean, Method => Op_Save, Name => ""save""); procedure Op_Delete (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); procedure Op_Delete (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Answer_Bean'Class (Bean).Delete (Outcome); end Op_Delete; package Binding_Answer_Bean_2 is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Answer_Bean, Method => Op_Delete, Name => ""delete""); Binding_Answer_Bean_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Binding_Answer_Bean_1.Proxy'Access, 2 => Binding_Answer_Bean_2.Proxy'Access ); -- This bean provides some methods that can be used in a Method_Expression. overriding function Get_Method_Bindings (From : in Answer_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is begin return Binding_Answer_Bean_Array'Access; end Get_Method_Bindings; -- Set the value identified by the name overriding procedure Set_Value (Item : in out Answer_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin null; end Set_Value; end AWA.Questions.Models; ",12151,True,2771.801275524795,median ":toc: :toclevels: 4 :sectnums: = MLPerf Training Rules Version 1.0 March 25, 2021 == Overview This document describes how to implement the MLPerf Training Suite using an ML framework and how to use that implementation to measure the performance of an ML software framework or hardware. There are seperate rules for the submission, review, and publication process for all MLPerf benchmarks https://github.com/mlperf/policies/blob/master/submission_rules.adoc[here]. The MLPerf name and logo are trademarks. In order to refer to a result using the MLPerf name, the result must conform to the letter and spirit of the rules specified in this document. The MLPerf organization reserves the right to solely determine if a use of its name or logo is acceptable. === Definitions (read this section carefully) The following definitions are used throughout this document: _Performance_ always refers to execution speed. _Quality_ always refers to a model’s ability to produce “correct” outputs. A _system_ consists of a defined set of hardware resources such as processors, memories, disks, and interconnect. It also includes specific versions of all software such as operating system, compilers, libraries, and drivers that significantly influences the running time of a benchmark, excluding the ML framework. A _framework_ is a specific version of a software library or set of related libraries, possibly with associated offline compiler, for training ML models using a system. Examples include specific versions of Caffe2, MXNet, PaddlePaddle, pyTorch, or TensorFlow. A _benchmark_ is an abstract problem that can be solved using ML by training a model based on a specific dataset or simulation environment to a target quality level. A _suite_ is a specific set of benchmarks. A _division_ is a set of rules for implementing benchmarks from a suite to produce a class of comparable results. A _reference implementation_ is a specific implementation of a benchmark provided by the MLPerf organization. A _benchmark implementation_ is an implementation of a benchmark in a particular framework by a user under the rules of a specific division. A _submission implementation set_ is a set of benchmark implementations for one or more benchmarks from a suite under the rules of a specific division using the same framework. A _run_ is a complete execution of an implementation on a system, training a model from initialization to the quality target. A _run result_ is the wallclock time required for a run. A _reference result_ is the result provided by the MLPerf organization for each reference implementation A _benchmark result_ is the mean of a benchmark-specific number of run results, dropping the highest and lowest results. The result is then normalized to the reference result for that benchmark. Normalization is of the form (reference result / benchmark result) such that a better benchmark result produces a higher number. A _submission result set_ is a one benchmark result for each benchmark implementation in a submission implementation set. A _submission_ is a submission implementation set and a corresponding submission result set. A _custom summary result_ is the weighted geometric mean of an arbitrary set of results from a specific submission. MLPerf endorses this methodology for computing custom summary results but does not endorse any official summary result. == General rules The following rules apply to all benchmark implementations. === Strive to be fair Benchmarking should be conducted to measure the framework and system performance as fairly as possible. Ethics and reputation matter. === System and framework must be consistent The same system and framework must be used for a submission result set. Note that the reference implementations do not all use the same framework. === Benchmark detection is not allowed The framework and system should not detect and behave differently for benchmarks. === Pre-training is not allowed Unless part of the definition of a benchmark, the implementation should not encode any information about the content of the dataset or a successful model’s state in any form. High-level statistical information about the dataset, such as distribution of sizes, may be used. For benchmarks which are defined as starting from a fixed set of weights, such as a checkpoint or backbone, the implementation should start from the weights provided in the benchmark reference definition, or if that is not posssible, provide information and code sufficient for reproducing how those starting weights were obtained. For v0.7, sets of weights used in v0.6 are allowed. == Benchmarks The benchmark suite consists of the benchmarks shown in the following table. |=== |Area|Problem |Dataset |Vision |Image classification |ImageNet | |Image segmentation (medical) |KiTS19 | |Object detection (light weight) |COCO | |Object detection (heavy weight) |COCO |Language |Speech recognition |LibriSpeech | |NLP |Wikipedia 2020/01/01 |Commerce |Recommendation |1TB Click Logs |Research |Reinforcement learning |Go |=== The MLPerf organization provides a reference implementation of each benchmark, which includes the following elements: Code that implements the model in a framework. A plain text “README.md” file that describes: * Problem ** Dataset/Environment ** Publication/Attribution ** Data preprocessing ** Training and test data separation ** Training data order ** Test data order ** Simulation environment (RL models only) ** Steps necessary for reproducing the initial set of weights, if an initial set of non-standard weights is used. For v0.7, weights from v0.6 may be used without this information. ** Publication/Attribution ** List of layers ** Weight and bias initialization ** Loss function ** Optimizer * Quality ** Quality metric ** Quality target ** Evaluation frequency (training items between quality evaluations) ** Evaluation thoroughness (test items per quality evaluation) * Directions ** Steps to configure machine ** Steps to download and verify data ** Steps to run and time A “download_dataset” script that downloads the dataset. A “verify_dataset” script that verifies the dataset against the checksum. A “run_and_time” script that executes the benchmark and reports the wall-clock time. == Divisions There are two divisions of the benchmark suite, the Closed division and the Open division. === Closed Division The Closed division requires using the same preprocessing, model, training method, and quality target as the reference implementation. The closed division models and quality targets are: |=== |Area |Problem |Model |Target |Vision |Image classification |ResNet-50 v1.5 |75.90% classification | |Image segmentation (medical) |U-Net3D |0.908 Mean DICE score | |Object detection (light weight) |SSD |23.0% mAP | |Object detection (heavy weight) |Mask R-CNN |0.377 Box min AP and 0.339 Mask min AP |Language | Speech recognition | RNN-T | 0.058 Word Error Rate | |NLP |BERT |0.720 Mask-LM accuracy |Commerce |Recommendation |DLRM |0.8025 AUC |Research |Reinforcement learning |Mini Go (based on Alpha Go paper) |50% win rate vs. checkpoint |=== Closed division benchmarks must be referred to using the benchmark name plus the term Closed, e.g. “for the Image Classification Closed benchmark, the system achieved a result of 7.2.” === Open Division The Open division allows using arbitrary training data, preprocessing, model, and/or training method. However, the Open division still requires using supervised or reinforcement machine learning in which a model is iteratively improved based on training data, simulation, or self-play. Open division benchmarks must be referred to using the benchmark name plus the term Open, e.g. “for the Image Classification Open benchmark, the system achieved a result of 7.2.” == Basics === Random numbers CLOSED: Random numbers must be generated using stock random number generators. Random number generators may be seeded from the following sources: * Clock * System source of randomness, e.g. /dev/random or /dev/urandom * Another random number generator initialized with an allowed seed Random number generators may be initialized repeatedly in multiple processes or threads. For a single run, the same seed may be shared across multiple processes or threads. OPEN: Any random number generation may be used. === Numerical formats CLOSED: The numerical formats fp64, fp32, tf32, fp16, bfloat16, Graphcore FLOAT 16.16, int8, uint8, int4, and uint4 are pre-approved for use. Additional formats require explicit approval. Scaling may be added where required to compensate for different precision. Reference Convergence Points must be obtained using FP32 precision, or FP32 emulation with explanation of the methodology for emulation. OPEN: Any format and scaling may be used. === Epoch numbering Epochs should always be numbered from 1. === Result rounding Public results should be rounded normally. == Data Set === Data State at Start of Run CLOSED: Each reference implementation includes a script to download the input dataset and script to verify the dataset using a checksum. The data must then be preprocessed in a manner consistent with the reference implementation, excepting any transformations that must be done for each run (e.g. random transformations). The data may also be reformatted for the target system provided that the reformatting does not introduce new information or introduce duplicate copies of data. OPEN: Any public dataset may be used for training the model, however the evaluation data must be drawn from the benchmark dataset in a manner consistent with the reference. You must flush the cache or restart the system prior to benchmarking. Data can start on any durable storage system such as local disks and cloud storage systems. This explicitly excludes RAM. === Preprocessing During the Run Only preprocessing that must be done for each run (e.g. random transformations) must be timed. CLOSED: The same preprocessing steps as the reference implementation must be used. OPEN: Any preprocessing steps are allowed for training data. However, each datum must be preprocessed individually in a manner that is not influenced by any other data. The evaluation data must be preprocessed in a manner consistent with reference. === Data Representation CLOSED: Images must have the same size as in the reference implementation. Mathematically equivalent padding of images is allowed. CLOSED: For benchmarks with sequence inputs, you may choose a length N and either truncate all examples to length N or throw out all examples which exceed length N. This must be done uniformly for all examples. This may only be done on the training set and not the evaluation set. CLOSED: Two ways to represent the Mask R-CNN mask are permitted. One is a polygon and the other is a scalable bitmask. OPEN: The closed division data representations restrictions only apply at the start of the run. Data may be represented in an arbitrary fashion during the run. === Other Uses of Data Input encoding data, such as language vocabulary, or the set of possible labels may used during pre-processing or execution without counting as ""touching the training data"" for timing purposes. === Training and Test Sets CLOSED: If applicable, the dataset must be separated into training and test sets in the same manner as the reference implementation. OPEN: If applicable, the test dataset must be extracted in the same manner as the reference implementation. The training data set may not contain data that appears in the test set. === Training Data Order CLOSED: the training and test data must be traversed in the same conceptual order as the reference implementation. For instance, the data might be traversed sequentially or randomly with uniform distribution. Batch size, shard size, and the random number generator will affect order. Where data pipelines randomly order data, arbitrary sharding, batching, and packing are allowed provided that (1) the data is still overall randomly ordered and not ordered to improve convergence and (2) each datum still appears exactly once. OPEN: The training data may be traversed in any order. The test data must be traversed in the same order as the reference implementation. == RL Environment CLOSED: The implementation must use the same RL algorithm and simulator or game as the reference implementation, with the same parameters. OPEN: The implementation may use a different RL algorithm but must use the same simulator or game with the same parameters. If the reference implementation generates all data online, the Open division implementation must also generate all data online. It is allowed and encouraged to parallelize and otherwise optimize (e.g. by implementing in a compiled language) the RL environment provided that the semantics are preserved. == Model CLOSED: The benchmark implementation must use the same model as the reference implementation, as defined by the remainder of this section. OPEN: The benchmark implementation may use a different model. === Graph Definition CLOSED: Each of the current frameworks has a graph that describes the operations performed during the forward propagation of training. The frameworks automatically infer and execute the corresponding back-propagation computations from this graph. Benchmark implementations must use the same graph as the reference implementation. === Weight and Bias Initialization CLOSED: Weights and biases must be initialized using the same constant or random value distribution as the reference implementation, unless a pre-trained set of weights, such as a checkpoint or backbone, is used by the reference. OPEN: Weights and biases must be initialized using a consistent constant or random value distribution. === Graph Execution CLOSED: Frameworks are free to optimize the non-weight parts of the computation graph provided that the changes are mathematically equivalent. So optimizations and graph / code transformations of the flavor of dead code elimination, common subexpression elimination, loop-invariant code motion, and recomputation of node state are entirely allowed. OPEN: Frameworks are free to alter the graph. == Training Loop === Hyperparameters CLOSED: By default, the hyperparameters must be the same as the reference. Hyperparameters include the optimizer used and values like the regularization norms and weight decays. The implementation of the optimizer must match the optimizer specified in the Appendex: Allowed Optimizer. The Appendex lists which optimizers in the popular deep learning frameworks are compliant by default. If a submission uses an alternate implementation, the submitter must describe the optimizer's equation and demonstrate equivalence with the approved optimizers on that list. The following table lists the tunable hyperparameters for each allowed model,optimizer combination. The value of each tunable hyperparameter must meet the listed constraint. The MLPerf verifier scripts checks all hyperparameters except those with names marked with asterisks. If a hyperparameter is marked with one asterisk, it must be checked manually. If a hyperparameter is marked with two asterisks, it is also not logged and it must be checked manually in the code. If the verifier and the constraints in this table differ, the verifier (specifically, the version on the date of submission unless otherwise decided by the review committee) is the source of truth. |=== |Model |Optimizer |Name |Constraint |Definition |Reference Code |bert |lamb |global_batch_size |unconstrained |The glboal batch size for training. |--train_batch_size |bert |lamb |opt_base_learning_rate |unconstrained |The base learning rate. |--learning_rate |bert |lamb |opt_epsilon |unconstrained |adam epsilon |link:https://github.com/mlperf/training/blob/fb058e3849c25f6c718434e60906ea3b0cb0f67d/language_model/tensorflow/bert/optimization.py#L75[reference code] |bert |lamb |opt_learning_rate_training_steps |unconstrained |Step at which your reach the lowest learning late |link:https://github.com/mlperf/training/blob/master/language_model/tensorflow/bert/run_pretraining.py#L64[reference code] |bert |lamb |opt_learning_rate_warmup_steps |unconstrained |""num_warmup_steps"" |link:https://github.com/mlperf/training/blob/master/language_model/tensorflow/bert/optimization.py#L34[reference code] |bert |lamb |num_warmup_steps |unconstrained |Number of steps for linear warmup. |--num_warmup_steps |bert |lamb |start_warmup_step |unconstrained |--start_warmup_step |--start_warmup_step |bert |lamb |opt_lamb_beta_1 |unconstrained |adam beta1 |link:https://github.com/mlperf/training/blob/fb058e3849c25f6c718434e60906ea3b0cb0f67d/language_model/tensorflow/bert/optimization.py#L73[reference code] |bert |lamb |opt_lamb_beta_2 |unconstrained |adam beta2 |link:https://github.com/mlperf/training/blob/fb058e3849c25f6c718434e60906ea3b0cb0f67d/language_model/tensorflow/bert/optimization.py#L74[reference code] |bert |lamb |opt_lamb_weight_decay_rate |unconstrained |Weight decay |link:https://github.com/mlperf/training/blob/fb058e3849c25f6c718434e60906ea3b0cb0f67d/language_model/tensorflow/bert/optimization.py#L72[reference code] |dlrm |sgd |global_batch_size |unconstrained |global batch size | |dlrm |sgd |opt_base_learning_rate |unconstrained |base learning rate, this should be the learning rate after warm up and before decay |link:https://github.com/facebookresearch/dlrm/blob/master/dlrm_s_pytorch.py#L492[reference code] |dlrm |sgd |opt_learning_rate_warmup_steps |unconstrained |Number to steps go from 0 to sgd_opt_base_learning_rate with a linear warmup |See PR (From Intel and NV, TODO Link) |dlrm |sgd |lr_decay_start_steps |unconstrained |step at which you start poly decay |See PR (From Intel and NV, TODO Link) |dlrm |sgd |sgd_opt_base_learning_rate |unconstrained |learning rate at the start of poly decay |See PR (From Intel and NV, TODO Link) |dlrm |sgd |sgd_opt_learning_rate_decay_poly_power |2 |power of the poly decay |See PR (From Intel and NV, TODO Link) |dlrm |sgd |sgd_opt_learning_rate_decay_steps |unconstrained |the step at which you reach the end learning rate |See PR (From Intel and NV, TODO Link) |maskrcnn |sgd |global_batch_size |arbitrary constant |global version of reference SOLVER.IMS_PER_BATCH |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/object_detection/pytorch/maskrcnn_benchmark/data/build.py#L112[reference code] |maskrcnn |sgd |opt_learning_rate_decay_factor$$*$$ |fixed to reference (0.1) |learning rate decay factor |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/object_detection/pytorch/maskrcnn_benchmark/solver/build.py#L13[reference code] |maskrcnn |sgd |opt_learning_rate_decay_steps$$*$$ |(60000, 80000) * (1 + K / 10) * 16 / global_batch_size where K is integer |Steps at which learning rate is decayed |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/object_detection/pytorch/maskrcnn_benchmark/solver/build.py#L26[reference code] |maskrcnn |sgd |opt_base_learning_rate |0.02 * K for any integer K |base learning rate, this should be the learning rate after warm up and before decay |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/object_detection/pytorch/maskrcnn_benchmark/solver/build.py#L12[reference code] |maskrcnn |sgd |max_image_size$$*$$ |fixed to reference |Maximum size of the longer side |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/object_detection/pytorch/maskrcnn_benchmark/data/transforms/build.py#L8[reference code] |maskrcnn |sgd |min_image_size$$*$$ |fixed to reference |Maximum size of the shorter side |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/object_detection/pytorch/maskrcnn_benchmark/data/transforms/build.py#L7[reference code] |maskrcnn |sgd |num_image_candidates$$*$$ |1000 or 1000 * batches per chip |tunable number of region proposals for given batch size |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/object_detection/pytorch/maskrcnn_benchmark/modeling/rpn/inference.py#L183[reference code] |maskrcnn |sgd |opt_learning_rate_warmup_factor |unconstrained |the constant factor applied at learning rate warm up |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/object_detection/pytorch/maskrcnn_benchmark/solver/build.py#L28[reference code] |maskrcnn |sgd |opt_learning_rate_warmup_steps |unconstrained |number of steps for learning rate to warm up |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/object_detection/pytorch/maskrcnn_benchmark/solver/build.py#L29[reference code] |maskrcnn |sgd |num_image_candidates$$*$$ |(1000 or 2000) or (1000 * batches per chip) |tunable number of region proposals for given batch size |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/object_detection/pytorch/maskrcnn_benchmark/modeling/rpn/inference.py#L183[reference code] |minigo |sgd |train_batch_size |integer > 0 |Batch size to use for training |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/reinforcement/tensorflow/minigo/dual_net.py#L47[reference code] |minigo |sgd |lr_boundaries |unconstrained |The number of steps at which the learning rate will decay |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/reinforcement/tensorflow/minigo/dual_net.py#L67[reference code] |minigo |sgd |lr_rates |unconstrained |The different learning rates |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/reinforcement/tensorflow/minigo/dual_net.py#L70[reference code] |minigo |sgd |actual_selfplay_games_per_generation |integer >= 8192 (min_selfplay_games_per_generation) |""NOT A HYPERPARAMETER, CANNOT BE 'BORROWED' during review"" Implicit (LOG ONLY) - total number of games played per epoch; many parameters can impact this, varies per iteration |N/A |minigo |sgd |min_selfplay_games_per_generation$$*$$ |fixed to reference (8192) |Minimum number of games to play for each training iteration |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/reinforcement/tensorflow/minigo/ml_perf/train_loop.py#L51[reference code] |resnet |lars |lars_opt_base_learning_rate |arbitrary constant |Base ""plr"" in the PR linked. |link:https://github.com/mlperf/training/pull/342/files#[reference code] |resnet |lars |lars_opt_end_learning_rate$$*$$ |fixed to reference |end learning rate for polynomial decay, implied mathemetically from other HPs |N/A |resnet |lars |lars_opt_learning_rate_decay_poly_power$$*$$ |fixed to reference |power of polynomial decay, no link needed since not tunable |N/A |resnet |lars |lars_epsilon$$*$$ |Fixed to reference |epsilon in reference |link:https://github.com/mlperf/training/pull/342/files#diff-b7db7d58acb8134acb65b4d1d60b8e90R49[reference code] |resnet |lars |lars_opt_learning_rate_warmup_epochs |arbitrary constant |w_epochs in PR |link:https://github.com/mlperf/training/pull/342/files#[reference code] |resnet |lars |lars_opt_momentum | 0.9 for batch<32k, otherwise arbitrary constant |momentum in reference |link:https://github.com/mlperf/training/pull/342/files#diff-b7db7d58acb8134acb65b4d1d60b8e90R49[reference code] |resnet |lars |lars_opt_weight_decay |(0.0001 * 2 ^ N) where N is any integer |weight_decay in reference |link:https://github.com/mlperf/training/pull/342/files#diff-b7db7d58acb8134acb65b4d1d60b8e90R49[reference code] |resnet |lars |lars_opt_learning_rate_decay_steps |unconstrained |num_epochs in reference |link:https://github.com/mlperf/training/blob/master/image_classification/tensorflow/official/resnet/resnet_run_loop.py[reference code] |resnet |lars |global_batch_size |unconstrained |global batch size in reference |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/image_classification/tensorflow/official/utils/arg_parsers/parsers.py#L158[reference code] |resnet |lars |label smoothing$$*$$$$*$$ |0 or 0.1 | TODO |TODO |resnet |lars |truncated norm initialization$$*$$$$*$$ |boolean | TODO |TODO |resnet |sgd |global_batch_size |arbitrary constant |reference --batch_size |See LARS |resnet |sgd |sgd_opt_base_learning_rate |0.001 * k where is an integer |the learning rate |See LARS |resnet |sgd |sgd_opt_end_learning_rate |10^-4 |end learning rate for polynomial decay, implied mathemetically from other HPs |See LARS |resnet |sgd |sgd_opt_learning_rate_decay_poly_power |2 |power of polynomial decay, no link needed since not tunable |See LARS |resnet |sgd |sgd_opt_learning_rate_decay_steps |integer >= 0 |num_epochs in reference |See LARS |resnet |sgd |sgd_opt_weight_decay |(0.0001 * 2 ^ N) where N is any integer |Weight decay, same as LARS. |See LARS |resnet |sgd |sgd_opt_momentum |0.9 |Momentum for SGD. |See LARS |resnet |sgd |model_bn_span |arbitrary constant |number of samples whose statistics a given BN layer uses to normalize a training minibatch (may be just the portion of global_batch_size per device, but also may be aggregated over several devices) |See LARS |resnet |sgd |opt_learning_rate_warmup_epochs |integer >= 0 |number of epochs needed for learning rate warmup |See LARS |resnet |sgd |label smoothing$$*$$$$*$$ |0 or 0.1 | TODO |TODO |resnet |sgd |truncated norm initialization$$*$$$$*$$ |boolean | TODO |TODO |resnet |lars/sgd |opt_name |""lars"" or ""sgd"" |The optimizer that was used. | |rnnt |lamb |global_batch_size |unconstrained |reference --batch_size |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L270-L271[reference code] |rnnt |lamb |opt_name |""lamb"" |The optimizer that was used. |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L357[reference code] |rnnt |lamb |opt_base_learning_rate |unconstrained |base learning rate, this should be the learning rate after warm up and before decay |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L358[reference code] |rnnt |lamb |opt_lamb_epsilon |1e-9 |LAMB epsilon |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L359[reference code] |rnnt |lamb |opt_lamb_learning_rate_decay_poly_power |unconstrained |Exponential decay rate |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L360[reference code] |rnnt |lamb |opt_lamb_learning_rate_hold_epochs |unconstrained |Number of epochs when LR schedule keeps the base learning rate value |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L362[reference code] |rnnt |lamb |opt_learning_rate_warmup_epochs |unconstrained |Number of epochs when LR linearly increases from 0 to base learning rate |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L361[reference code] |rnnt |lamb |opt_weight_decay |1e-3 |L2 weight decay |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L372[reference code] |rnnt |lamb |opt_lamb_beta_1 |unconstrained |LAMB beta 1 |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L363[reference code] |rnnt |lamb |opt_lamb_beta_2 |unconstrained |LAMB beta 2 |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L364[reference code] |rnnt |lamb |opt_gradient_clip_norm |1 or inf |Gradients are clipped above this norm threshold. |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L365[reference code] |rnnt |lamb |opt_gradient_accumulation_steps |unconstrained |Numer of fwd/bwd steps between optimizer step. |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L222[reference code] |rnnt |lamb |opt_learning_rate_alt_decay_func |True |whether to use alternative learning rate decay function |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/common/optimizers.py#L20-L49[reference code] |rnnt |lamb |opt_learning_rate_alt_warmup_func |True |whether to use alternative learning rate warmup function |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L367[reference code] |rnnt |lamb |opt_lamb_learning_rate_min |1e-5 |LR schedule doesn't set LR values below this threshold |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L368[reference code] |rnnt |lamb |train_samples |unconstrained |Number of training samples after filtering out samples longer than data_train_max_duration |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L337[reference code] |rnnt |lamb |eval_samples |2703 |Number of evaluation samples |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L338[reference code] |rnnt |lamb |data_train_max_duration |unconstrained |Samples longer than this number of seconds are not included to training dataset |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L252-L253[reference code] |rnnt |lamb |data_train_num_buckets |unconstrained |Training dataset is split to this number of buckets |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L293[reference code] |rnnt |lamb |data_train_speed_perturbation_min |0.85 |Input audio is resampled to a random rample rate not less than this fraction of original sample rate. |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L256-L257[reference code] |rnnt |lamb |data_train_speed_perturbation_max |1.15 |Input audio is resampled to a random rample rate not greater than this fraction of original sample rate. |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L254-L255[reference code] |rnnt |lamb |data_spec_augment_freq_n |2 |Number of masks for frequency bands |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L258-L259[reference code] |rnnt |lamb |data_spec_augment_freq_min |0 |Minimum number of frequencies in a single mask |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L260-L261[reference code] |rnnt |lamb |data_spec_augment_freq_max |20 |Maximum number of frequencies in a single mask |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L262-L263[reference code] |rnnt |lamb |data_spec_augment_time_n |10 |Number of masks for time band |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L264-L265[reference code] |rnnt |lamb |data_spec_augment_time_min |0 |Minimum number of masked time steps as a fraction of all steps |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L266-L267[reference code] |rnnt |lamb |data_spec_augment_time_max |0.03 |Maximum number of masked time steps as a fraction of all steps |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L268-L269[reference code] |rnnt |lamb |model_eval_ema_factor |unconstrained |Smoothing factor for Exponential Moving Average |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L395[reference code] |rnnt |lamb |model_weights_initialization_scale |unconstrained |After random initialization of weight and bias tensors, all are scaled with this factorAfter random initialization of weight and bias tensors, all are scaled with this factor |See link:https://github.com/mwawrzos/training/blob/2126999a1ffff542064bb3208650a1e673920dcf/rnn_speech_recognition/pytorch/train.py#L342[reference code] |ssd |sgd |global_batch_size |arbitrary constant |reference --batch-size |link:https://github.com/mlperf/training/blob/master/single_stage_detector/ssd/train.py#L23[reference code] |ssd |sgd |model_bn_span |integer >= 1 |number of samples whose statistics a given BN layer uses to normalize a training minibatch (may be just the portion of global_batch_size per device, but also may be aggregated over several devices) |link:https://github.com/mlperf/training/blob/master/single_stage_detector/ssd/train.py#L335[reference code] |ssd |sgd |opt_learning_rate_warmup_factor |Integer >= 0 |the constant factor applied at learning rate warm up |link:https://github.com/mlperf/training/blob/master/single_stage_detector/ssd/train.py#L45[reference code] |ssd |sgd |opt_learning_rate_warmup_steps |integer >= 1 |number of steps for learning rate to warm up |link:https://github.com/mlperf/training/blob/master/single_stage_detector/ssd/train.py#L43[reference code] |ssd |sgd |opt_weight_decay |arbitrary constant |L2 weight decay |link:https://github.com/mlperf/training/blob/master/single_stage_detector/ssd/train.py#L40[reference code] |ssd |sgd |opt_base_learning_rate |unconstrained |base learning rate, this should be the learning rate after warm up and before decay |link:https://github.com/mlperf/training/blob/master/single_stage_detector/ssd/train.py#L47[reference code] |ssd |sgd |max_samples |1 or 50 |maximum number of samples attempted when generating a training patch for a given IoU choice |link:https://github.com/mlperf/training/pull/367/commits/e6fbbb323adb7d1521cc5b7d7371f2e4461ece59#diff-591431110d6b55f5afe595b96253fddbR111[reference code] |ssd |sgd |opt_learning_rate_decay_boundary_epochs |[40, 50] * (1 + k/10) for some integer k |Epochs at which the learning rate decays |link:https://github.com/mlperf/training/blob/e6fbbb323adb7d1521cc5b7d7371f2e4461ece59/single_stage_detector/ssd/train.py#L48[reference code] |unet3d |sgd |global_batch_size |unconstrained |global batch size |reference --batch_size |unet3d |sgd |opt_base_learning_rate |unconstrained |base learning rate |reference --learning_rate |unet3d |sgd |opt_momentum |unconstrained |SGD momentum |reference --momentum |unet3d |sgd |opt_learning_rate_warmup_steps |unconstrained |number of epochs needed for learning rate warmup|reference --lr_warmup_epochs |unet3d |sgd |opt_initial_learning_rate |unconstrained |initial learning rate (for LR warm up) |reference --init_learning_rate |unet3d |sgd |opt_learning_rate_decay_steps |unconstrained |epochs at which the learning rate decays |reference --lr_decay_epochs |unet3d |sgd |opt_learning_rate_decay_factor |unconstrained |factor used for learning rate decay |reference --lr_decay_factor |unet3d |sgd |opt_weight_decay |unconstrained |L2 weight decay |reference --weight_decay |unet3d |sgd |training_oversampling |fixed to reference |training oversampling |reference --oversampling |unet3d |sgd |training_input_shape |fixed to reference |training input shape |reference --input_shape |unet3d |sgd |evaluation_overlap |fixed to reference |evaluation sliding window overlap |reference --overlap |unet3d |sgd |evaluation_input_shape |fixed to reference |evaluation input shape |reference --val_input_shape |unet3d |sgd |data_train_samples |fixed to reference |number of training samples | N/A |unet3d |sgd |data_eval_samples |fixed to reference |number of evaluation samples | N/A |=== OPEN: Hyperparameters and optimizer may be freely changed. === Hyperparameter Borrowing Submitters are expected to use their best efforts to submit with optimal hyperparameters for their system. The intent of Hyperparameter Borrowing is to allow a submitter to update their submission to reflect what they would have submitted had they known about more optimal hyperparameters before submitting, without knowing any other info (ie the performance of other submissions). During the review period as described in the Submission Rules, a submitter may replace the hyperparameters, once per benchmark entry, in their implementation of a benchmark with hyperparameters from another submitter's implementation of the same benchmark. By default, they may change batch size (local batch size, global batch size, batchnorm span), but must replace all other hyperparameters as a group. With evidence that the resulting model, using the same batch size as the other submitter's implementation, converges worse in terms of epochs required, the submitter may make a minimum number of additional hyperparameter changes for the purpose of improving convergence and achieving comparable, but not better, convergence in epochs compared to the other submitter's implementation, but preserving any difference in convergence that may exist due to precision choices. In this situation, the other submitter's implementation is considered the reference, and the new submitter must match the convergence behavior of the other submitter in a similar way as we compare any submission to the reference. A resubmission of a benchmark with borrowed hyperparameters must use the same software (with the exceptions listed in the Software Adoption section of this document), system and system configuration (accelerators, NICs etc) as the original submission. The largest scale submission for a benchmark from a given system may be resubmitted with borrowed hyperparameters using a change of scale on that system, but only if the new scale is either larger, or enables the resubmission to achieve a faster run result. In addition, the new scale must not be larger than the largest scale used in an original submission of at least one of the benchmarks on that system in this round. === Loss function CLOSED: The same loss function used in the reference implementation must be used. OPEN: Any loss function may be used. Do not confuse the loss function with target quality measure. === Quality measure Each run must reach a target quality level on the reference implementation quality measure. By default, the time to evaluate the quality is included in the wallclock time. However, if the reference implementation generates timestamped checkpoints and evaluates the quality after the clock has been stopped, then an implementation may either perform evaluation on-the-clock or generate timestamped checkpoints, evaluate them after the clock has been stopped, and update the clock stopped time to the timestamp of the first passing checkpoint. The checkpoint timestamp may be any time after the last weight value included in the checkpoint is updated. CLOSED: The same quality measure as the reference implementation must be used. The quality measure must be evaluated at the same frequency (in terms of number of training items between test sets) and at least as thoroughly (in terms of number of tests per set) as in the reference implementation. Where applicable, the required evaluation point may be rounded up to the nearest batch size. Typically, a test consists of comparing the output of one forward pass through the network with the desired output from the test set. |=== |Area |Problem |Model|Evaluation frequency |Vision |Image classification |Resnet-50 v1.5|Every 4 epochs with offset 0 or 1 or 2 or 3 | |Image segmentation (medical) |U-Net3D | Starting at `CEILING(1000*168/samples_per_epoch)` epochs, then every `CEILING(20*168/samples_per_epoch)` epochs. Where `samples_per_epoch` is the number of samples processed in a given epoch assuming that in the case of uneven batches the last batch is padded, e.g. `CEILING(168/global_batch_size) * global_batch_size`. | |Object detection (light weight) |SSD|Fixed at epochs=40, 50, 55, 60, 65, 70, 75, 80 | |Object detection (heavy weight) |Mask R-CNN|Every 1 epoch |Language|Speech recognition |RNN-T|Every 1 epoch | |NLP |BERT| eval_interval_samples=FLOOR(0.05*(230.23*GBS+3000000), 25000), skipping 0 |Commerce|Recommendation |DLRM|Every 102400 samples |Research|Reinforcement learning |Mini Go|Every 1 epoch |=== OPEN: An arbitrary stopping criteria may be used, including but not limited to the closed quality measure, a different quality measure, the number of epochs, or a fixed time. However, the reported results must include the geometric mean of the final quality as measured by the closed quality measure. Check points can be created at the discretion of submitter. No check points are required to be produced or retained. === Equivalence exceptions The CLOSED division allows limited exemptions to mathematical equivalence between implementations for pragmatic purposes, including: * Different methods can be used to add color jitter as long as the methods are of a similar distribution and magnitude to the reference. * If data set size is not evenly divisible by batch size, one of several techniques may be used. The last batch in an epoch may be composed of the remaining samples in the epoch, may be padded, or may be a mixed batch composed of samples from the end of one epoch and the start of the next. If the mixed batch technique is used, quality for the ending epoch must be evaluated after the mixed batch. If the padding technique is used, the first batch may be padded instead of the last batch. * Values introduced for padding purposes may be reflected in batch norm computations. * Adam optimizer implementations may use the very small value epsilon to maintain mathematical stability in slightly different ways, provided that methods are reviewed and approved in advance. One such method involves squaring the value of epsilon and moving epsilon inside the square root in the parameter update equation. * Distributed batch normalization is allowed. Additional exemptions need to be explicitly requested and approved in advance. In general, exemptions may be approved for techniques that are common industry practice, introduce small differences that would be difficult to engineer around relative to their significance, and do not substantially decrease the required computation. Over time, MLPerf should seek to help the industry converge on standards and remove exemptions. The OPEN division does not restrict mathematical equivalence. == Software Adoption == For a given round of MLPerf, the ""canonical version"" of a software component shall be defined as the public version as of 14 days before submission. If the software is open source, the canonical version shall be the one compiled with the default compilation options. If a system software provider submits with a component whose version is other than the canonical version, then other submitters using the same component are allowed to update their submission to use that version. Those other submitters must resubmit with the updated system software before the resubmission deadline during the review period. Software adoption applies only to system software, only to the version used by the software provider’s submission, and explicitly does not cover benchmark implementations. Benchmark implementations should be borrowed as a whole only if the software provider’s submission introduces new APIs. [#section-run-results] == Run Results A run result consists of a wall-clock timing measurement for a contiguous period that includes model initialization in excess of a maximum initialization time, any data preprocessing required to be on the clock, using the dataset to train the model, and quality evaluation unless specified otherwise for the benchmark. Prior to starting the clock, a system may use a maximum of 20 minutes of model initialization time. Model initialization time begins when the system first begins to construct or execute the model. This maximum initialization time is intended to ensure that model initialization is not disproportionate on large systems intended to run much larger models, and may be adjusted in the future with sufficient evidence. The clock must start before any part of the system touches the dataset or when the maximum model initialization time is exceeded. The clock may be stopped as soon as any part of the system determines target accuracy has been reached. The clock may not be paused during the run. == Benchmark Results Each benchmark result is based on a set of run results. The number of results for each benchmark is based on a combination of the variance of the benchmark result, the cost of each run, and the likelihood of convergence. |=== |Area|Problem |Minimum Number of Runs |Vision |Image classification |5 | |Image segmentation (medical) | 40 | |Object detection (light weight) |5 | |Object detection (heavy weight) |5 |Language |NLP |10 | |Speech recognition |10 |Commerce |Recommendation |5 |Research |Reinforcement learning |10 |=== Each benchmark result is computed by dropping the fastest and slowest runs, then taking the mean of the remaining times. For this purpose, a single non-converging run may be treated as the slowest run and dropped. A benchmark result is invalid if there is more than one non-converging run. In the case of UNET3D, due to large variance, 40 runs are required. Out of the 40 runs, the 4 fastest and 4 slowest are dropped. There can be maximum of 4 non-converging runs. A run is classified as non-converged if the target quality metric is not reached within `CEILING(10000*168/samples_in_epoch)` epochs. Each benchmark result should be normalized by dividing the reference result for the corresponding reference implementation by the benchmark result. This normalization produces higher numbers for better results, which better aligns with human intuition. === Scoring An MLPerf submission score is intended to represent the median expected result across a large number of runs. To reduce statistical variance and the potential to cherry pick results, each benchmark submission is composed of a set of N independent runs, with N chosen based on the observed variation of the benchmark, as described in the table above. Running multiple iterations of N independent runs with the goal of validating that the submission is close to a median result is encouraged but not required. Running multiple iterations of N runs to try find the lowest one is against the spirit of MLPerf and is prohibited – see Section 2.1, “Strive to be fair”. Results that appear to be too far away from a median result may be rejected. As a more computationally efficient method of validating that a submission is close to the median result, it is also allowed to run M>N independent runs as a group and to designate N consecutive runs from the group as the runs to be used for scoring, provided that the submitter chooses the N consecutive runs that are closest to the median result. For the purposes of calculating the median, sets of N consecutive runs that would create an invalid benchmark result should be included in the median calculation as ""infinite"" scores. If the median set would be an invalid benchmark result, the entire result is invalid. Submitting the full run set (vs just the N runs used for scoring) as a reference is optional, but may be required in the future. For purposes of this scoring, ""consecutive"" is defined as an objective and deterministic method, such as submission timestamps. Submitters are not allowed to pick different orderings to improve their score. Runs may go in parallel on the submitter's compute resources, as long as there is a way to objectively and deterministically sort the runs, for example by timestamp. An example could be for a benchmark with N=5 runs, a submitter could ahead of time pick M=10, launch 10 runs on their compute resources, sort the 10 runs by their launch time stamp, then take a sliding window of 5 consecutive runs over those 10 runs. That sliding window would create 6 possible sets of 5 runs. Each of those 6 sets would be olympically scored, and the set with the median runtime would be submitted as that submitter's score. Any failed runs within those 10 runs would count as infinity time and need to be included in the olympic scoring (could be thrown away as the slowest score). It is recommended that a submitter keep the logs for all M runs, because the review committee may ask for the submitter to share the M logs during the review period. == Reference Convergence Points (RCPs) Reference Convergence Points are used to ensure that the convergence of the submission does not deviate from the convergence of the reference. We are interested in avoiding cases where the submission convergence is faster than the reference. Reference implementation convergence sets a lower bound on epoch convergence that a valid submission should not beat. From a statistical standpoint if the submission mean epochs to converge is significantly lower than the reference mean epochs to converge, then submission convergence points belong to a different population than the reference convergence points, and thus the submission should not be accepted. Compliance to reference convergence points is validated as follows * Reference implementations provide at least 2N epoch convergence numbers, where N is the number of submission runs needed for each benchmark. Since convergence is affected by batch size (larger batch size means slower convergence), reference implementations provide convergence data for a few different batch sizes. * Using the mean and standard deviation of the reference convergence we apply a 1-sided independent two-sample Student's t-test with unequal sample sizes, similar variances with p-value=0.05 (explained link:https://en.wikipedia.org/wiki/Student%27s_t-test#Equal_or_unequal_sample_sizes,_similar_variances_(1/2_%3C_sX1/sX2_%3C_2)[here]) to find the maximum acceptable speedup for submission convergence. * At submission time, the submission is matched to an RCP based on the submission batch size. ** If there is an RCP for that batch size then mean epochs to converge of the submission is extracted from submission logs. If this does not violate the maximum acceptable speedup condition when compared to the reference then the submission is accepted, otherwise it may be rejected. ** If there is no RCP for that batch size but there are RCPs for smaller and larger batch sizes an interpolated RCP is created, and the mean epochs to converge is compared against the interpolated RCP just like in the previous case ** If the submission batch size is larger than the batch size of any RCP the submitter must provide the missing RCPs by running the reference implementation with their batch size. ** If the submission batch size is smaller that the batch size of any RCP AND the convergence test against the RCP with the minimum batch size fails, then again the submitter must provide the missing RCPs by running the reference implementation with their batch size. Please refer to the related Appendix for examples that shed light to the RCP process. === RCP Rules and Guidelines Submitters are encouraged to run the RCP checker script prior to their submission to make sure they do not violate RCP limits. If a submission fails the RCP test, such as S2 in the Appendix, they have the option to submit with the --rcp_bypass parameter. This will allow the submission to upload, but the submitter must notify the results chair, and prepare for the audit process described in the link:https://github.com/mlcommons/policies/blob/master/submission_rules.adoc#auditing[policies document] but at review time the submitter should be able to justify why their submission is valid while it failed the RCP test. If a submission is missing the RCP for the batch size they are submitting, such as S4 and S6 in the Appendix they must provide the missing convergence points by making a PR in the logger. If not, the submission will not be accepted. All missing RCPs are due at submission time. RCPs are added by making a pull request into the RCP library in the logging repository. During hyperparameter borrowing, borrowers can use hyperparameters from submissions that passed or failed the RCP test. If their submission fails to pass the RCP test they can have it upload by using --rcp-bypass and then prepare for the audit decribed in the link:https://github.com/mlcommons/policies/blob/master/submission_rules.adoc#auditing[policies document] To extract submission convergence points, logs should report epochs as follows. For this round no RCP checks will be made for Minigo. |=== | Benchmark | Epoch reporting | RN50 | Epoch | BERT | Training sample (integer) | DLRM | 1 + Epoch / 20.0 (1.05, 1.1, 1.15...) | SSD | Epoch | Mask-RCNN | Epoch | RNN-T | Epoch | UNET3D | Epoch | Minigo | N/A |=== == Appendix: Benchmark Specific Rules * Image Classification ** The model may have 1000 or 1001 classes, where the 1001st is ""I don't know"" == Appendix: Allowed Closed Division Optimizers Analysis to support this can be found in the document ""MLPerf Optimizer Review"" in the MLPerf Training document area. TODO: locate the document and provide working link |=== | Benchmark | Algorithm | Framework | Allowed Optimizer | Image classification | LARS | PyTorch | [No compliant implementation] | | | TensorFlow | MLPERF_LARSOptimizer | | | MxNet | SGDwFASTLARS | Image classification | SGD with Momentum | PyTorch | apex.optimizers.FusedSGD | | | PyTorch | torch.optim.SGD | | | TensorFlow | tf.train.MomentumOptimizer | | | MxNet | [No compliant implementation] | Reinforcement learning| SGD with Momentum | PyTorch | apex.optimizers.FusedSGD | | | PyTorch | torch.optim.SGD | | | TensorFlow | tf.train.MomentumOptimizer | Object detection (heavy weight) | SGD with Momentum | PyTorch | apex.optimizers.FusedSGD | | | PyTorch | torch.optim.SGD | | | TensorFlow | tf.train.MomentumOptimizer | Object detection (light weight) | SGD with Momentum | PyTorch | apex.optimizers.FusedSGD | | | PyTorch | torch.optim.SGD | | | TensorFlow | tf.train.MomentumOptimizer | NLP | LAMB | PyTorch | apex.optimizers.FusedLAMB | | | TensorFlow | tf.optimizers.LAMB | Speech recognition | LAMB | PyTorch | apex.optimizers.FusedLAMB | | | TensorFlow | tf.optimizers.LAMB | Recommendation | SGD | PyTorch | torch.optim.SGD | | | TensorFlow | tf.train.MomentumOptimizer | Image segmentation (medical) | SGD with Momentum | PyTorch | torch.optim.SGD | | | TensorFlow | tf.train.MomentumOptimizer | | | MXNet | mx.optimizer.NAG |=== == Appendix: v1.0 Specific Rules This section contains rules specific to the v1.0 round of MLPerf Training. These do not apply to future rounds, unless explicitly ratified as rules for those rounds, or unless these rules are promoted to official rules in previous sections of this document. === MaskRCNN backbone For v1.0 only, Mask-RCNN submitters may use the non-reference backbone located https://drive.google.com/drive/folders/1lGU_pP2Pr2k578DslciwE4AlOKm6dKCK?usp=sharing[here] with the understanding that it converges similarly to the reference backbone. If the non-reference backbone is shown to converge faster than the reference backbone at any scale on any submitted hyperparameter set, all uses of that backbone for any submitter are to be re-run with the reference backbone to have their submission published. For future rounds, the expectation is that all submitters will use the reference backbone, which will fixed at reference code freeze time. === BERT clip-normalization order For v1.0 only, BERT submissions may implement clip-norm either before or after inter-accelerator all-reduce. For future rounds, the expectation is that submissions must use clip-norm-after-reduce, to be consistent with most commonly used public BERT model repos. For performance consistency of at scale BERT submissions for v1.0, submitters are disallowed from using clip-norm-after-reduce to enable additional overlap of communication and math. If a submitter plans to use clip-norm-after-reduce for v1.0, they must notify the committee before the submission deadline, and be prepared to show code in their submission proving that they do not do overlap as a result of clip-norm-after-reduce. Furthermore, for simplicity, the RCPs for this round will use clip-norm-before-reduce. In theory, this could allow clip-norm-after-reduce submissions that converge faster than they should, but still not faster than clip-norm-before-reduce, but the Training Working Group feels that this is ok risk for v1.0, in interest of simplifying the RCPs for v1.0. === Compile time For v1.0 only, the allowed untimed compile time is increased from 20 minutes to 30 minutes. This is to enable new submitters to submit who were close to the 20 minute limit. The 20 minute number was chosen empirically for rounds prior to v1.0. For v1.1 and beyond, the training working group should make a data driven decision on what compile time is reasonable for real user applications. == Appendix: v1.1 Specific Rules This section contains rules specific to the v1.1 round of MLPerf Training. These do not apply to future rounds, unless explicitly ratified as rules for those rounds, or unless these rules are promoted to official rules in previous sections of this document. === BERT clip-normalization order For v1.0 only, BERT submissions may implement clip-norm either before or after inter-accelerator all-reduce. For future rounds, the expectation is that submissions must use clip-norm-after-reduce, to be consistent with most commonly used public BERT model repos. This exception from v1.0 was extended to v1.1 because of the tight schedule between rounds. === Preview Category For v1.1, we changed the policy documentation to say that a Preview submission needs to be available at the next submission after 140 days, not 180 days like it was before. However, this does not apply to Preview submissions from v1.0, which will still follow the 180 day policy. For v1.1 Preview submissions and beyond, the 140 day rule will apply. This is not necessarily an ""exception,"" but we are listing it here as a special case for the record. == Appendix: RCP Examples The RCP checking process is best illustrated with the following examples: Benchmark A requires 5 submission runs. The reference implementation provides (at least) 10 convergence points, let's say [16, 14, 16, 17, 16, 16, 15, 16, 15, 16] for batch size 128. The top and bottom run are excluded from the mean and standard deviation computation. So in this case the Mean = 15.75 epochs and Stdev = 0.43. Based on the t-test the maximum allowed speedup for p-value=0.05 is 3.53%. In other words the minimum mean epochs to converge for each submission with batch size 128 is 15.21. The reference also provides convergence points for batch size 256: [20, 21, 21, 20, 22, 22, 21, 21, 20, 20]. In this case Mean = 20.75, Stdev = 0.66 and based on the t-test the maximum allowed speedup for p-value=0.05 is 4.12%. In other words the minimum mean epochs to converge for batch-256 is 19.93. Let's consider now the following submission scenarios: * Submitter S1 makes a submission for A with batch size 128, and from the logs the epochs to converge are [15, 15, 15, 16, 16]. Excluding the top and bottom runs the mean epochs to converge is 15.33 (> 15.21), so S1 passes the RCP test for benchmark A, batch size 128. * Submitter S2 makes a submission for A with batch size 256, and from the logs the epochs to converge are [19, 19, 19, 20, 21]. Excluding the top and bottom runs the mean epochs to converge is 19.33 (< 19.93), so S2 fails the RCP test for benchmark A, batch size 256. * Submitter S3 makes a submission for A with batch size 192, and from the logs the epochs to converge are [17, 18, 18, 18, 20]. There are no RCPs for 192, but there are for larger and lower batch sizes. In this situation we find an interpolation of the mean and standard deviations for the RCPs at batch size 192. Mean = 18.25 and Stdev=0.547. Based on the t-test with p-value=0.05 the maximum allowed speedup is 3.68%. Exclusing the top and botton submission runs, the submission mean epochs to converge is 18, which is more than 18.25 / 1.0368, so the submission is accepted for batch size 192. * Submitter S4 makes a submission for A with batch size 512. Since there is neither RCP for that batch size, nor RCPs for larger batch sizes, S2 needs to provide convergence points by running the reference with that batch size. * Submitter S5 makes a submission for A with batch size 64 that meets the (stricter) convergence criteria for the RCP with the smallest batch size (128). In this case the submission is accepted. * Submitter S6 makes a submission for A with batch size 64 that does not meet the convergence criteria for the RCP with the smallest batch size (128). In this case S1 needs to provide convergence points by running the reference with batch size = 64. ",16269,True,2871.4184454678025,median " -1 dilate_0_0_2160_3840_0_3_3_1_1_s 0 4 0 1 1 imgHelper2_4102 0 0 0 FIFO_SRL 49 8 0 3 0 0 0 1 2 imgHelper3_4103 0 0 0 FIFO_SRL 49 8 1 3 0 0 0 1 3 p_src_rows 0 0 0 FIFO_SRL 49 32 0 3 0 0 0 1 4 p_src_cols 0 0 0 FIFO_SRL 49 32 0 3 0 0 0 6 0 0 11 p_src_rows_read /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp .. 340 dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; dilate_0_0_2160_3840_0_3_3_1_1_s 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; 340 auto fifo srl FIFO_SRL 81 32 2 0 19 20 read 0 0 0 0 3.28 1 -1 0 12 p_src_cols_read /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp .. 341 dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; dilate_0_0_2160_3840_0_3_3_1_1_s 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; 341 auto fifo srl FIFO_SRL 81 32 2 0 21 22 read 0 0 0 0 3.28 2 -1 0 13 trunc_ln340 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp .. 340 dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; dilate_0_0_2160_3840_0_3_3_1_1_s 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; 340 trunc_ln340_fu_52_p1 1702127986 16 1 0 23 trunc 0 0 0 0 0.00 3 -1 0 14 trunc_ln341 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp .. 341 dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; dilate_0_0_2160_3840_0_3_3_1_1_s 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; 341 trunc_ln341_fu_57_p1 145 16 1 0 24 trunc 0 0 0 0 0.00 4 -1 0 15 _ln376 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp .. 376 dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; dilate_0_0_2160_3840_0_3_3_1_1_s 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; 376 grp_xfdilate_2160_3840_1_0_1_0_3841_3_3_s_fu_42 161 0 5 0 26 27 28 29 30 call 0 0 0 0 0.00 5 -1 0 16 _ln0 0 0 0 161 0 0 0 ret 0 0 0 0 0.00 6 -1 1 0 2 25 xfdilate_2160_3840_1_0_1_0_3841_3_3_s 0 0 0 49 0 6 <constant:xfdilate<2160, 3840, 1, 0, 1, 0, 3841, 3, 3>> 1 0 3 17 dilate<0, 0, 2160, 3840, 0, 3, 3, 1, 1> 0 0 0 1768189039 6 0 11 12 13 14 15 16 9 0 20 1 3 11 0 22 1 4 12 0 23 1 11 13 0 24 1 12 14 0 26 1 25 15 0 27 1 1 15 0 28 1 2 15 0 29 1 13 15 0 30 1 14 15 0 1 0 1 dilate<0, 0, 2160, 3840, 0, 3, 3, 1, 1> dilate_0_0_2160_3840_0_3_3_1_1_s 0 0 0 1 0 17 -1 -1 -1 -1 13 8319373 0 2 0 1 5 0 11 1 1 12 1 1 13 1 1 14 1 1 15 2 2 2 8 0 5 1 1 6 1 1 7 1 1 8 1 1 9 1 1 10 1 1 15 1 2 16 1 1 1 0 1 2 -1 1 0 0 0 1 0 grp_xfdilate_2160_3840_1_0_1_0_3841_3_3_s_fu_42 (xfdilate_2160_3840_1_0_1_0_3841_3_3_s) 3 0 BRAM 6 FF 611 LUT 819 1 0 ap_block_state1 ( or ) 4 0 (0P0) 1 (1P1) 1 FF 0 LUT 1 0 0 0 0 6 0 ap_NS_fsm 4 0 (0Size) 3 (1Bits) 1 (2Count) 3 LUT 13 ap_done 4 0 (0Size) 2 (1Bits) 1 (2Count) 2 LUT 9 imgHelper2_4102_read 4 0 (0Size) 2 (1Bits) 1 (2Count) 2 LUT 9 imgHelper3_4103_write 4 0 (0Size) 2 (1Bits) 1 (2Count) 2 LUT 9 p_src_cols_blk_n 4 0 (0Size) 2 (1Bits) 1 (2Count) 2 LUT 9 p_src_rows_blk_n 4 0 (0Size) 2 (1Bits) 1 (2Count) 2 LUT 9 5 0 ap_CS_fsm 3 0 (Bits) 2 (Consts) 0 FF 2 ap_done_reg 3 0 (Bits) 1 (Consts) 0 FF 1 grp_xfdilate_2160_3840_1_0_1_0_3841_3_3_s_fu_42_ap_start_reg 3 0 (Bits) 1 (Consts) 0 FF 1 trunc_ln340_reg_62 3 0 (Bits) 16 (Consts) 0 FF 16 trunc_ln341_reg_67 3 0 (Bits) 16 (Consts) 0 FF 16 1 0 grp_xfdilate_2160_3840_1_0_1_0_3841_3_3_s_fu_42 0 0 1 0 grp_xfdilate_2160_3840_1_0_1_0_3841_3_3_s_fu_42 (xfdilate_2160_3840_1_0_1_0_3841_3_3_s) 1 0 15 0 0 0 0 0 0 6 0 11 0 0 12 0 0 13 0 0 14 0 0 15 0 1 16 1 0 1 0 17 0 1 0 0 5 0 30 1 0 11 36 1 0 12 42 2 0 15 15 52 1 0 13 57 1 0 14 2 0 trunc_ln340_fu_52 1 0 13 trunc_ln341_fu_57 1 0 14 1 0 grp_xfdilate_2160_3840_1_0_1_0_3841_3_3_s_fu_42 2 0 15 15 2 0 p_src_cols_read_read_fu_36 1 0 12 p_src_rows_read_read_fu_30 1 0 11 0 0 0 0 2 0 62 1 0 13 67 1 0 14 2 0 trunc_ln340_reg_62 1 0 13 trunc_ln341_reg_67 1 0 14 0 0 0 0 4 0 imgHelper2_4102 1 0 call 1 0 15 imgHelper3_4103 1 0 call 1 0 15 p_src_cols 1 0 read 1 0 12 p_src_rows 1 0 read 1 0 11 4 0 1 1150 10 2 1151 10 3 1150 10 4 1150 10 3 0 11 1150 10 12 1150 10 15 -1 -1 ",12494,False,2233.4692645454134,median "Components ^^^^^^^^^^ // components: START Number of Components: 219 [width=""100%"",cols=""4,1,5"",options=""header""] |======================================================================= | Component | Available From | Description | link:camel-ahc/src/main/docs/ahc-component.adoc[AHC] (camel-ahc) + `ahc:httpUri` | 2.8 | To call external HTTP services using Async Http Client. | link:camel-ahc-ws/src/main/docs/ahc-ws-component.adoc[AHC Websocket] (camel-ahc-ws) + `ahc-ws:httpUri` | 2.14 | To exchange data with external Websocket servers using Async Http Client. | link:camel-amqp/src/main/docs/amqp-component.adoc[AMQP] (camel-amqp) + `amqp:destinationType:destinationName` | 1.2 | Messaging with AMQP protocol using Apache QPid Client. | link:camel-flink/src/main/docs/flink-component.adoc[Apache Flink] (camel-flink) + `flink:endpointType` | 2.18 | The flink component can be used to send DataSet jobs to Apache Flink cluster. | link:camel-spark/src/main/docs/spark-component.adoc[Apache Spark] (camel-spark) + `spark:endpointType` | 2.17 | The spark component can be used to send RDD or DataFrame jobs to Apache Spark cluster. | link:camel-apns/src/main/docs/apns-component.adoc[APNS] (camel-apns) + `apns:name` | 2.8 | For sending notifications to Apple iOS devices. | link:camel-asterisk/src/main/docs/asterisk-component.adoc[Asterisk] (camel-asterisk) + `asterisk:name` | 2.18 | The asterisk component is used to interact with Asterisk PBX Server Asterisk PBX Server. | link:camel-atmos/src/main/docs/atmos-component.adoc[Atmos] (camel-atmos) + `atmos:name/operation` | 2.15 | The atmos component is used for integrating with EMC's Atomos Storage. | link:camel-atmosphere-websocket/src/main/docs/atmosphere-websocket-component.adoc[Atmosphere Websocket] (camel-atmosphere-websocket) + `atmosphere-websocket:servicePath` | 2.14 | To exchange data with external Websocket clients using Atmosphere. | link:camel-atom/src/main/docs/atom-component.adoc[Atom] (camel-atom) + `atom:feedUri` | 1.2 | The atom component is used for consuming Atom RSS feeds. | link:camel-avro/src/main/docs/avro-component.adoc[Avro] (camel-avro) + `avro:transport:host:port/messageName` | 2.10 | Working with Apache Avro for data serialization. | link:camel-aws/src/main/docs/aws-cw-component.adoc[AWS CloudWatch] (camel-aws) + `aws-cw:namespace` | 2.11 | The aws-cw component is used for sending metrics to an Amazon CloudWatch. | link:camel-aws/src/main/docs/aws-ddb-component.adoc[AWS DynamoDB] (camel-aws) + `aws-ddb:tableName` | 2.10 | The aws-ddb component is used for storing and retrieving data from Amazon's DynamoDB service. | link:camel-aws/src/main/docs/aws-ddbstream-component.adoc[AWS DynamoDB Streams] (camel-aws) + `aws-ddbstream:tableName` | 2.17 | The aws-ddbstream component is used for working with Amazon DynamoDB Streams. | link:camel-aws/src/main/docs/aws-ec2-component.adoc[AWS EC2] (camel-aws) + `aws-ec2:label` | 2.16 | The aws-ec2 is used for managing Amazon EC2 instances. | link:camel-aws/src/main/docs/aws-kinesis-component.adoc[AWS Kinesis] (camel-aws) + `aws-kinesis:streamName` | 2.17 | The aws-kinesis component is for consuming records from Amazon Kinesis Streams. | link:camel-aws/src/main/docs/aws-s3-component.adoc[AWS S3 Storage Service] (camel-aws) + `aws-s3:bucketNameOrArn` | 2.8 | The aws-s3 component is used for storing and retrieving objecct from Amazon S3 Storage Service. | link:camel-aws/src/main/docs/aws-ses-component.adoc[AWS Simple Email Service] (camel-aws) + `aws-ses:from` | 2.9 | The aws-ses component is used for sending emails with Amazon's SES service. | link:camel-aws/src/main/docs/aws-sns-component.adoc[AWS Simple Notification System] (camel-aws) + `aws-sns:topicNameOrArn` | 2.8 | The aws-sns component is used for sending messages to an Amazon Simple Notification Topic. | link:camel-aws/src/main/docs/aws-sqs-component.adoc[AWS Simple Queue Service] (camel-aws) + `aws-sqs:queueNameOrArn` | 2.6 | The aws-sqs component is used for sending and receiving messages to Amazon's SQS service. | link:camel-aws/src/main/docs/aws-swf-component.adoc[AWS Simple Workflow] (camel-aws) + `aws-swf:type` | 2.13 | The aws-swf component is used for managing workflows from Amazon Simple Workflow. | link:camel-aws/src/main/docs/aws-sdb-component.adoc[AWS SimpleDB] (camel-aws) + `aws-sdb:domainName` | 2.9 | The aws-sdb component is for storing and retrieving data from/to Amazon's SDB service. | link:camel-azure/src/main/docs/azure-blob-component.adoc[Azure Storage Blob Service] (camel-azure) + `azure-blob:containerOrBlobUri` | | The azure-blob component is used for storing and retrieving blobs from Azure Storage Blob Service. | link:../camel-core/src/main/docs/bean-component.adoc[Bean] (camel-core) + `bean:beanName` | 1.0 | The bean component is for invoking Java beans from Camel. | link:camel-bean-validator/src/main/docs/bean-validator-component.adoc[Bean Validator] (camel-bean-validator) + `bean-validator:label` | 2.3 | The Validator component performs bean validation of the message body using the Java Bean Validation API. | link:camel-beanstalk/src/main/docs/beanstalk-component.adoc[Beanstalk] (camel-beanstalk) + `beanstalk:connectionSettings` | 2.15 | The beanstalk component is used for job retrieval and post-processing of Beanstalk jobs. | link:../camel-core/src/main/docs/binding-component.adoc[Binding] (camel-core) + `binding:bindingName:delegateUri` | 2.11 | The binding component is used for as a of wrapping an Endpoint in a contract with a data format. | link:camel-bonita/src/main/docs/bonita-component.adoc[Bonita] (camel-bonita) + `bonita:operation` | 2.19 | Camel Bonita support | link:camel-box/src/main/docs/box-component.adoc[Box] (camel-box) + `box:apiName/methodName` | 2.14 | For uploading downloading and managing files folders groups collaborations etc on box DOT com. | link:camel-braintree/src/main/docs/braintree-component.adoc[Braintree] (camel-braintree) + `braintree:apiName/methodName` | 2.17 | The braintree component is used for integrating with the Braintree Payment System. | link:../camel-core/src/main/docs/browse-component.adoc[Browse] (camel-core) + `browse:name` | 1.3 | The browse component is used for viewing the messages received on endpoints that supports BrowsableEndpoint. | link:camel-context/src/main/docs/context-component.adoc[Camel Context] (camel-context) + `context:contextId:localEndpointUrl` | 2.7 | *deprecated* The context component allows to send/receive messages between Camel routes in a black box way. | link:camel-cassandraql/src/main/docs/cql-component.adoc[Cassandra CQL] (camel-cassandraql) + `cql:beanRef:hosts:port/keyspace` | 2.15 | The cql component aims at integrating Cassandra 2.0 using the CQL3 API (not the Thrift API). | link:camel-chronicle/src/main/docs/chronicle-engine-component.adoc[Chronicle Engine] (camel-chronicle) + `chronicle-engine:addresses/path` | 2.18 | The camel chronicle-engine component let you leverage the power of OpenHFT's Chronicle-Engine. | link:camel-chunk/src/main/docs/chunk-component.adoc[Chunk] (camel-chunk) + `chunk:resourceUri` | 2.15 | Transforms the message using a Chunk template. | link:../camel-core/src/main/docs/class-component.adoc[Class] (camel-core) + `class:beanName` | 2.4 | The Class Component is for invoking Java Classes (Java beans) from Camel. | link:camel-cm-sms/src/main/docs/cm-sms-component.adoc[CM SMS Gateway] (camel-cm-sms) + `cm-sms:host` | 2.18 | The influxdb component allows to integrate with CM SMS Gateway. | link:camel-cmis/src/main/docs/cmis-component.adoc[CMIS] (camel-cmis) + `cmis:cmsUrl` | 2.11 | The cmis component uses the Apache Chemistry client API and allows you to add/read nodes to/from a CMIS compliant content repositories. | link:camel-coap/src/main/docs/coap-component.adoc[CoAP] (camel-coap) + `coap:uri` | 2.16 | The coap component is used for sending and receiving messages from COAP capable devices. | link:camel-cometd/src/main/docs/cometd-component.adoc[CometD] (camel-cometd) + `cometd:host:port/channelName` | 2.0 | The cometd component is a transport for working with the Jetty implementation of the cometd/bayeux protocol. | link:camel-consul/src/main/docs/consul-component.adoc[Consul] (camel-consul) + `consul:apiEndpoint` | 2.18 | The camel consul component allows you to work with Consul a distributed highly available datacenter-aware service discovery and configuration system. | link:../camel-core/src/main/docs/controlbus-component.adoc[Control Bus] (camel-core) + `controlbus:command:language` | 2.11 | The controlbus component provides easy management of Camel applications based on the Control Bus EIP pattern. | link:camel-couchbase/src/main/docs/couchbase-component.adoc[Couchbase] (camel-couchbase) + `couchbase:url` | 2.19 | Represents a Couchbase endpoint that can query Views with a Poll strategy and/or produce various type of operations. | link:camel-couchdb/src/main/docs/couchdb-component.adoc[CouchDB] (camel-couchdb) + `couchdb:protocol:hostname:port/database` | 2.11 | The couchdb component is used for integrate with CouchDB databases. | link:camel-crypto/src/main/docs/crypto-component.adoc[Crypto (JCE)] (camel-crypto) + `crypto:cryptoOperation:name` | 2.3 | The crypto component is used for signing and verifying exchanges using the Signature Service of the Java Cryptographic Extension (JCE). | link:camel-cxf/src/main/docs/cxf-component.adoc[CXF] (camel-cxf) + `cxf:beanId:address` | 1.0 | The cxf component is used for SOAP WebServices using Apache CXF. | link:camel-cxf/src/main/docs/cxfrs-component.adoc[CXF-RS] (camel-cxf) + `cxfrs:beanId:address` | 2.0 | The cxfrs component is used for JAX-RS REST services using Apache CXF. | link:../camel-core/src/main/docs/dataformat-component.adoc[Data Format] (camel-core) + `dataformat:name:operation` | 2.12 | The dataformat component is used for working with Data Formats as if it was a regular Component supporting Endpoints and URIs. | link:../camel-core/src/main/docs/dataset-component.adoc[Dataset] (camel-core) + `dataset:name` | 1.3 | The dataset component provides a mechanism to easily perform load & soak testing of your system. | link:../camel-core/src/main/docs/direct-component.adoc[Direct] (camel-core) + `direct:name` | 1.0 | The direct component provides direct synchronous call to another endpoint from the same CamelContext. | link:../camel-core/src/main/docs/direct-vm-component.adoc[Direct VM] (camel-core) + `direct-vm:name` | 2.10 | The direct-vm component provides direct synchronous call to another endpoint from any CamelContext in the same JVM. | link:camel-disruptor/src/main/docs/disruptor-component.adoc[Disruptor] (camel-disruptor) + `disruptor:name` | 2.12 | The disruptor component provides asynchronous SEDA behavior using LMAX Disruptor. | link:camel-dns/src/main/docs/dns-component.adoc[DNS] (camel-dns) + `dns:dnsType` | 2.7 | To lookup domain information and run DNS queries using DNSJava. | link:camel-docker/src/main/docs/docker-component.adoc[Docker] (camel-docker) + `docker:operation` | 2.15 | The docker component is used for managing Docker containers. | link:camel-dozer/src/main/docs/dozer-component.adoc[Dozer] (camel-dozer) + `dozer:name` | 2.15 | The dozer component provides the ability to map between Java beans using the Dozer mapping library. | link:camel-drill/src/main/docs/drill-component.adoc[Drill] (camel-drill) + `drill:host` | 2.19 | The drill component gives you the ability to quering into apache drill cluster. | link:camel-dropbox/src/main/docs/dropbox-component.adoc[Dropbox] (camel-dropbox) + `dropbox:operation` | 2.14 | For uploading downloading and managing files folders groups collaborations etc on dropbox DOT com. | link:camel-cache/src/main/docs/cache-component.adoc[EHCache] (camel-cache) + `cache:cacheName` | 2.1 | *deprecated* The cache component enables you to perform caching operations using EHCache as the Cache Implementation. | link:camel-ehcache/src/main/docs/ehcache-component.adoc[Ehcache] (camel-ehcache) + `ehcache:cacheName` | 2.18 | The ehcache component enables you to perform caching operations using Ehcache as cache implementation. | link:camel-ejb/src/main/docs/ejb-component.adoc[EJB] (camel-ejb) + `ejb:beanName` | 2.4 | The ejb component is for invoking EJB Java beans from Camel. | link:camel-elasticsearch/src/main/docs/elasticsearch-component.adoc[Elasticsearch] (camel-elasticsearch) + `elasticsearch:clusterName` | 2.11 | The elasticsearch component is used for interfacing with ElasticSearch server. | link:camel-elasticsearch5/src/main/docs/elasticsearch5-component.adoc[Elasticsearch5] (camel-elasticsearch5) + `elasticsearch5:clusterName` | 2.19 | The elasticsearch component is used for interfacing with ElasticSearch server using 5.x API. | link:camel-elsql/src/main/docs/elsql-component.adoc[ElSQL] (camel-elsql) + `elsql:elsqlName:resourceUri` | 2.16 | The elsql component is an extension to the existing SQL Component that uses ElSql to define the SQL queries. | link:camel-etcd/src/main/docs/etcd-component.adoc[etcd] (camel-etcd) + `etcd:namespace/path` | 2.18 | The camel etcd component allows you to work with Etcd a distributed reliable key-value store. | link:camel-exec/src/main/docs/exec-component.adoc[Exec] (camel-exec) + `exec:executable` | 2.3 | The exec component can be used to execute OS system commands. | link:camel-facebook/src/main/docs/facebook-component.adoc[Facebook] (camel-facebook) + `facebook:methodName` | 2.14 | The Facebook component provides access to all of the Facebook APIs accessible using Facebook4J. | link:../camel-core/src/main/docs/file-component.adoc[File] (camel-core) + `file:directoryName` | 1.0 | The file component is used for reading or writing files. | link:camel-flatpack/src/main/docs/flatpack-component.adoc[Flatpack] (camel-flatpack) + `flatpack:type:resourceUri` | 1.4 | The flatpack component supports fixed width and delimited file parsing via the FlatPack library. | link:camel-fop/src/main/docs/fop-component.adoc[FOP] (camel-fop) + `fop:outputType` | 2.10 | The fop component allows you to render a message into different output formats using Apache FOP. | link:camel-freemarker/src/main/docs/freemarker-component.adoc[Freemarker] (camel-freemarker) + `freemarker:resourceUri` | 2.10 | Transforms the message using a FreeMarker template. | link:camel-ftp/src/main/docs/ftp-component.adoc[FTP] (camel-ftp) + `ftp:host:port/directoryName` | 1.1 | The ftp component is used for uploading or downloading files from FTP servers. | link:camel-ftp/src/main/docs/ftps-component.adoc[FTPS] (camel-ftp) + `ftps:host:port/directoryName` | 2.2 | The ftps (FTP secure SSL/TLS) component is used for uploading or downloading files from FTP servers. | link:camel-ganglia/src/main/docs/ganglia-component.adoc[Ganglia] (camel-ganglia) + `ganglia:host:port` | 2.15 | The ganglia component is used for sending metrics to the Ganglia monitoring system. | link:camel-geocoder/src/main/docs/geocoder-component.adoc[Geocoder] (camel-geocoder) + `geocoder:address:latlng` | 2.12 | The geocoder component is used for looking up geocodes (latitude and longitude) for a given address or reverse lookup. | link:camel-git/src/main/docs/git-component.adoc[Git] (camel-git) + `git:localPath` | 2.16 | The git component is used for working with git repositories. | link:camel-github/src/main/docs/github-component.adoc[GitHub] (camel-github) + `github:type/branchName` | 2.15 | The github component is used for integrating Camel with github. | link:camel-google-calendar/src/main/docs/google-calendar-component.adoc[Google Calendar] (camel-google-calendar) + `google-calendar:apiName/methodName` | 2.15 | The google-calendar component provides access to Google Calendar. | link:camel-google-drive/src/main/docs/google-drive-component.adoc[Google Drive] (camel-google-drive) + `google-drive:apiName/methodName` | 2.14 | The google-drive component provides access to Google Drive file storage service. | link:camel-google-mail/src/main/docs/google-mail-component.adoc[Google Mail] (camel-google-mail) + `google-mail:apiName/methodName` | 2.15 | The google-mail component provides access to Google Mail. | link:camel-google-pubsub/src/main/docs/google-pubsub-component.adoc[Google Pubsub] (camel-google-pubsub) + `google-pubsub:projectId:destinationName` | 2.19 | Messaging client for Google Cloud Platform PubSub Service: https://cloud.google.com/pubsub/ | link:camel-gora/src/main/docs/gora-component.adoc[Gora] (camel-gora) + `gora:name` | 2.14 | The gora component allows you to work with NoSQL databases using the Apache Gora framework. | link:camel-grape/src/main/docs/grape-component.adoc[Grape] (camel-grape) + `grape:defaultCoordinates` | 2.16 | Grape component allows you to fetch, load and manage additional jars when CamelContext is running. | link:camel-guava-eventbus/src/main/docs/guava-eventbus-component.adoc[Guava EventBus] (camel-guava-eventbus) + `guava-eventbus:eventBusRef` | 2.10 | The guava-eventbus component provides integration bridge between Camel and Google Guava EventBus. | link:camel-hazelcast/src/main/docs/hazelcast-component.adoc[Hazelcast] (camel-hazelcast) + `hazelcast:command:cacheName` | 2.7 | The hazelcast component allows you to work with the Hazelcast distributed data grid / cache. | link:camel-hbase/src/main/docs/hbase-component.adoc[HBase] (camel-hbase) + `hbase:tableName` | 2.10 | For reading/writing from/to an HBase store (Hadoop database). | link:camel-hdfs/src/main/docs/hdfs-component.adoc[HDFS] (camel-hdfs) + `hdfs:hostName:port/path` | 2.8 | *deprecated* For reading/writing from/to an HDFS filesystem using Hadoop 1.x. | link:camel-hdfs2/src/main/docs/hdfs2-component.adoc[HDFS2] (camel-hdfs2) + `hdfs2:hostName:port/path` | 2.14 | For reading/writing from/to an HDFS filesystem using Hadoop 2.x. | link:camel-hipchat/src/main/docs/hipchat-component.adoc[Hipchat] (camel-hipchat) + `hipchat:protocol:host:port` | 2.15 | The hipchat component supports producing and consuming messages from/to Hipchat service. | link:camel-http/src/main/docs/http-component.adoc[HTTP] (camel-http) + `http:httpUri` | 1.0 | For calling out to external HTTP servers using Apache HTTP Client 3.x. | link:camel-http4/src/main/docs/http4-component.adoc[HTTP4] (camel-http4) + `http4:httpUri` | 2.3 | For calling out to external HTTP servers using Apache HTTP Client 4.x. | link:camel-ibatis/src/main/docs/ibatis-component.adoc[iBatis] (camel-ibatis) + `ibatis:statement` | 1.2 | *deprecated* Performs a query poll insert update or delete in a relational database using Apache iBATIS. | link:camel-mail/src/main/docs/imap-component.adoc[IMAP] (camel-mail) + `imap:host:port` | 1.0 | To send or receive emails using imap/pop3 or stmp protocols. | link:camel-infinispan/src/main/docs/infinispan-component.adoc[Infinispan] (camel-infinispan) + `infinispan:host` | 2.13 | For reading/writing from/to Infinispan distributed key/value store and data grid. | link:camel-influxdb/src/main/docs/influxdb-component.adoc[InfluxDB] (camel-influxdb) + `influxdb:connectionBean` | 2.18 | The influxdb component allows you to interact with InfluxDB a time series database. | link:camel-irc/src/main/docs/irc-component.adoc[IRC] (camel-irc) + `irc:hostname:port` | 1.1 | The irc component implements an IRC (Internet Relay Chat) transport. | link:camel-ironmq/src/main/docs/ironmq-component.adoc[IronMQ] (camel-ironmq) + `ironmq:queueName` | 2.17 | The ironmq provides integration with IronMQ an elastic and durable hosted message queue as a service. | link:camel-javaspace/src/main/docs/javaspace-component.adoc[JavaSpace] (camel-javaspace) + `javaspace:url` | 2.1 | *deprecated* Sending and receiving messages through JavaSpace. | link:camel-jbpm/src/main/docs/jbpm-component.adoc[JBPM] (camel-jbpm) + `jbpm:connectionURL` | 2.6 | The jbpm component provides integration with jBPM (Business Process Management). | link:camel-jcache/src/main/docs/jcache-component.adoc[JCache] (camel-jcache) + `jcache:cacheName` | 2.17 | The jcache component enables you to perform caching operations using JSR107/JCache as cache implementation. | link:camel-jclouds/src/main/docs/jclouds-component.adoc[JClouds] (camel-jclouds) + `jclouds:command:providerId` | 2.9 | For interacting with cloud compute & blobstore service via jclouds. | link:camel-jcr/src/main/docs/jcr-component.adoc[JCR] (camel-jcr) + `jcr:host/base` | 1.3 | The jcr component allows you to add/read nodes to/from a JCR compliant content repository. | link:camel-jdbc/src/main/docs/jdbc-component.adoc[JDBC] (camel-jdbc) + `jdbc:dataSourceName` | 1.2 | The jdbc component enables you to access databases through JDBC where SQL queries are sent in the message body. | link:camel-jetty9/src/main/docs/jetty-component.adoc[Jetty 9] (camel-jetty9) + `jetty:httpUri` | 1.2 | The jetty component provides HTTP-based endpoints for consuming and producing HTTP requests. | link:camel-websocket/src/main/docs/websocket-component.adoc[Jetty Websocket] (camel-websocket) + `websocket:host:port/resourceUri` | 2.10 | The websocket component provides websocket endpoints for communicating with clients using websocket. | link:camel-jgroups/src/main/docs/jgroups-component.adoc[JGroups] (camel-jgroups) + `jgroups:clusterName` | 2.13 | The jgroups component provides exchange of messages between Camel and JGroups clusters. | link:camel-jing/src/main/docs/jing-component.adoc[Jing] (camel-jing) + `jing:resourceUri` | 1.1 | Validates the payload of a message using RelaxNG Syntax using Jing library. | link:camel-jira/src/main/docs/jira-component.adoc[JIRA] (camel-jira) + `jira:type` | 2.15 | The jira component interacts with the JIRA issue tracker. | link:camel-jms/src/main/docs/jms-component.adoc[JMS] (camel-jms) + `jms:destinationType:destinationName` | 1.0 | The jms component allows messages to be sent to (or consumed from) a JMS Queue or Topic. | link:camel-jmx/src/main/docs/jmx-component.adoc[JMX] (camel-jmx) + `jmx:serverURL` | 2.6 | The jmx component allows to receive JMX notifications. | link:camel-jolt/src/main/docs/jolt-component.adoc[JOLT] (camel-jolt) + `jolt:resourceUri` | 2.16 | The jolt component allows you to process a JSON messages using an JOLT specification (such as JSON-JSON transformation). | link:camel-jpa/src/main/docs/jpa-component.adoc[JPA] (camel-jpa) + `jpa:entityType` | 1.0 | The jpa component enables you to store and retrieve Java objects from databases using JPA. | link:camel-jt400/src/main/docs/jt400-component.adoc[JT400] (camel-jt400) + `jt400:userID:password/systemName/objectPath.type` | 1.5 | The jt400 component allows you to exchanges messages with an AS/400 system using data queues or program call. | link:camel-kafka/src/main/docs/kafka-component.adoc[Kafka] (camel-kafka) + `kafka:topic` | 2.13 | The kafka component allows messages to be sent to (or consumed from) Apache Kafka brokers. | link:camel-kestrel/src/main/docs/kestrel-component.adoc[Kestrel] (camel-kestrel) + `kestrel:addresses/queue` | 2.6 | *deprecated* The kestrel component allows messages to be sent to (or consumed from) Kestrel brokers. | link:camel-krati/src/main/docs/krati-component.adoc[Krati] (camel-krati) + `krati:path` | 2.9 | The krati allows the use krati datastores and datasets inside Camel. | link:camel-kubernetes/src/main/docs/kubernetes-component.adoc[Kubernetes] (camel-kubernetes) + `kubernetes:masterUrl` | 2.17 | The kubernetes component allows to work with Kubernetes PaaS. | link:../camel-core/src/main/docs/language-component.adoc[Language] (camel-core) + `language:languageName:resourceUri` | 2.5 | The language component allows you to send a message to an endpoint which executes a script by any of the supported Languages in Camel. | link:camel-ldap/src/main/docs/ldap-component.adoc[LDAP] (camel-ldap) + `ldap:dirContextName` | 1.5 | The ldap component allows you to perform searches in LDAP servers using filters as the message payload. | link:camel-linkedin/src/main/docs/linkedin-component.adoc[Linkedin] (camel-linkedin) + `linkedin:apiName/methodName` | 2.14 | The linkedin component is uses for retrieving LinkedIn user profiles connections companies groups posts etc. | link:../camel-core/src/main/docs/log-component.adoc[Log] (camel-core) + `log:loggerName` | 1.1 | The log component logs message exchanges to the underlying logging mechanism. | link:camel-lucene/src/main/docs/lucene-component.adoc[Lucene] (camel-lucene) + `lucene:host:operation` | 2.2 | To insert or query from Apache Lucene databases. | link:camel-lumberjack/src/main/docs/lumberjack-component.adoc[Lumberjack] (camel-lumberjack) + `lumberjack:host:port` | 2.18 | The lumberjack retrieves logs sent over the network using the Lumberjack protocol. | link:camel-metrics/src/main/docs/metrics-component.adoc[Metrics] (camel-metrics) + `metrics:metricsType:metricsName` | 2.14 | To collect various metrics directly from Camel routes using the DropWizard metrics library. | link:camel-mina/src/main/docs/mina-component.adoc[Mina] (camel-mina) + `mina:protocol:host:port` | 1.0 | *deprecated* Socket level networking using TCP or UDP with the Apache Mina 1.x library. | link:camel-mina2/src/main/docs/mina2-component.adoc[Mina2] (camel-mina2) + `mina2:protocol:host:port` | 2.10 | Socket level networking using TCP or UDP with the Apache Mina 2.x library. | link:camel-mllp/src/main/docs/mllp-component.adoc[MLLP] (camel-mllp) + `mllp:hostname:port` | 2.17 | Provides functionality required by Healthcare providers to communicate with other systems using the MLLP protocol. | link:../camel-core/src/main/docs/mock-component.adoc[Mock] (camel-core) + `mock:name` | 1.0 | The mock component is used for testing routes and mediation rules using mocks. | link:camel-mongodb/src/main/docs/mongodb-component.adoc[MongoDB] (camel-mongodb) + `mongodb:connectionBean` | 2.10 | Component for working with documents stored in MongoDB database. | link:camel-mongodb3/src/main/docs/mongodb3-component.adoc[MongoDB] (camel-mongodb3) + `mongodb3:connectionBean` | 2.19 | Component for working with documents stored in MongoDB database. | link:camel-mongodb-gridfs/src/main/docs/mongodb-gridfs-component.adoc[MongoDB GridFS] (camel-mongodb-gridfs) + `mongodb-gridfs:connectionBean` | 2.18 | Component for working with MongoDB GridFS. | link:camel-mqtt/src/main/docs/mqtt-component.adoc[MQTT] (camel-mqtt) + `mqtt:name` | 2.10 | Component for communicating with MQTT M2M message brokers using FuseSource MQTT Client. | link:camel-msv/src/main/docs/msv-component.adoc[MSV] (camel-msv) + `msv:resourceUri` | 1.1 | Validates the payload of a message using the MSV Library. | link:camel-mustache/src/main/docs/mustache-component.adoc[Mustache] (camel-mustache) + `mustache:resourceUri` | 2.12 | Transforms the message using a Mustache template. | link:camel-mvel/src/main/docs/mvel-component.adoc[MVEL] (camel-mvel) + `mvel:resourceUri` | 2.12 | Transforms the message using a MVEL template. | link:camel-mybatis/src/main/docs/mybatis-component.adoc[MyBatis] (camel-mybatis) + `mybatis:statement` | 2.7 | Performs a query poll insert update or delete in a relational database using MyBatis. | link:camel-nagios/src/main/docs/nagios-component.adoc[Nagios] (camel-nagios) + `nagios:host:port` | 2.3 | To send passive checks to Nagios using JSendNSCA. | link:camel-nats/src/main/docs/nats-component.adoc[Nats] (camel-nats) + `nats:servers` | 2.17 | The nats component allows you produce and consume messages from NATS. | link:camel-netty/src/main/docs/netty-component.adoc[Netty] (camel-netty) + `netty:protocol:host:port` | 2.3 | *deprecated* Socket level networking using TCP or UDP with the Netty 3.x library. | link:camel-netty-http/src/main/docs/netty-http-component.adoc[Netty HTTP] (camel-netty-http) + `netty-http:protocol:host:port/path` | 2.12 | *deprecated* Netty HTTP server and client using the Netty 3.x library. | link:camel-netty4/src/main/docs/netty4-component.adoc[Netty4] (camel-netty4) + `netty4:protocol:host:port` | 2.14 | Socket level networking using TCP or UDP with the Netty 4.x library. | link:camel-netty4-http/src/main/docs/netty4-http-component.adoc[Netty4 HTTP] (camel-netty4-http) + `netty4-http:protocol:host:port/path` | 2.14 | Netty HTTP server and client using the Netty 4.x library. | link:camel-olingo2/src/main/docs/olingo2-component.adoc[Olingo2] (camel-olingo2) + `olingo2:apiName/methodName` | 2.14 | Communicates with OData 2.0 and 3.0 services using Apache Olingo. | link:camel-openshift/src/main/docs/openshift-component.adoc[OpenShift] (camel-openshift) + `openshift:clientId` | 2.14 | *deprecated* To manage your Openshift 2.x applications. | link:camel-openstack/src/main/docs/openstack-cinder-component.adoc[OpenStack Cinder] (camel-openstack) + `openstack-cinder:host` | 2.19 | The openstack-cinder component allows messages to be sent to an OpenStack block storage services. | link:camel-openstack/src/main/docs/openstack-glance-component.adoc[OpenStack Glance] (camel-openstack) + `openstack-glance:host` | 2.19 | The openstack-glance component allows messages to be sent to an OpenStack image services. | link:camel-openstack/src/main/docs/openstack-keystone-component.adoc[OpenStack Keystone] (camel-openstack) + `openstack-keystone:host` | 2.19 | The openstack-keystone component allows messages to be sent to an OpenStack identity services. | link:camel-openstack/src/main/docs/openstack-neutron-component.adoc[OpenStack Neutron] (camel-openstack) + `openstack-neutron:host` | 2.19 | The openstack-neutron component allows messages to be sent to an OpenStack network services. | link:camel-openstack/src/main/docs/openstack-nova-component.adoc[OpenStack Nova] (camel-openstack) + `openstack-nova:host` | 2.19 | The openstack-nova component allows messages to be sent to an OpenStack compute services. | link:camel-openstack/src/main/docs/openstack-swift-component.adoc[OpenStack Swift] (camel-openstack) + `openstack-swift:host` | 2.19 | The openstack-swift component allows messages to be sent to an OpenStack object storage services. | link:camel-optaplanner/src/main/docs/optaplanner-component.adoc[OptaPlanner] (camel-optaplanner) + `optaplanner:configFile` | 2.13 | Solves the planning problem contained in a message with OptaPlanner. | link:camel-eventadmin/src/main/docs/eventadmin-component.adoc[OSGi EventAdmin] (camel-eventadmin) + `eventadmin:topic` | 2.6 | The eventadmin component can be used in an OSGi environment to receive OSGi EventAdmin events and process them. | link:camel-paxlogging/src/main/docs/paxlogging-component.adoc[OSGi PAX Logging] (camel-paxlogging) + `paxlogging:appender` | 2.6 | The paxlogging component can be used in an OSGi environment to receive PaxLogging events and process them. | link:camel-paho/src/main/docs/paho-component.adoc[Paho] (camel-paho) + `paho:topic` | 2.16 | Component for communicating with MQTT M2M message brokers using Eclipse Paho MQTT Client. | link:camel-pdf/src/main/docs/pdf-component.adoc[PDF] (camel-pdf) + `pdf:operation` | 2.16 | The pdf components provides the ability to create modify or extract content from PDF documents. | link:camel-pgevent/src/main/docs/pgevent-component.adoc[PostgresSQL Event] (camel-pgevent) + `pgevent:host:port/database/channel` | 2.15 | The pgevent component allows for producing/consuming PostgreSQL events related to the LISTEN/NOTIFY commands. | link:camel-printer/src/main/docs/lpr-component.adoc[Printer] (camel-printer) + `lpr:hostname:port/printername` | 2.1 | The printer component is used for sending messages to printers as print jobs. | link:../camel-core/src/main/docs/properties-component.adoc[Properties] (camel-core) + `properties:key` | 2.3 | The properties component is used for using property placeholders in endpoint uris. | link:camel-quartz/src/main/docs/quartz-component.adoc[Quartz] (camel-quartz) + `quartz:groupName/timerName` | 1.0 | *deprecated* Provides a scheduled delivery of messages using the Quartz 1.x scheduler. | link:camel-quartz2/src/main/docs/quartz2-component.adoc[Quartz2] (camel-quartz2) + `quartz2:groupName/triggerName` | 2.12 | Provides a scheduled delivery of messages using the Quartz 2.x scheduler. | link:camel-quickfix/src/main/docs/quickfix-component.adoc[QuickFix] (camel-quickfix) + `quickfix:configurationName` | 2.1 | The quickfix component allows to send Financial Interchange (FIX) messages to the QuickFix engine. | link:camel-rabbitmq/src/main/docs/rabbitmq-component.adoc[RabbitMQ] (camel-rabbitmq) + `rabbitmq:hostname:portNumber/exchangeName` | 2.12 | The rabbitmq component allows you produce and consume messages from RabbitMQ instances. | link:camel-reactive-streams/src/main/docs/reactive-streams-component.adoc[Reactive Streams] (camel-reactive-streams) + `reactive-streams:stream` | 2.19 | The Camel reactive-streams endpoint. | link:../camel-core/src/main/docs/ref-component.adoc[Ref] (camel-core) + `ref:name` | 1.2 | The ref component is used for lookup of existing endpoints bound in the Registry. | link:../camel-core/src/main/docs/rest-component.adoc[REST] (camel-core) + `rest:method:path:uriTemplate` | 2.14 | The rest component is used for either hosting REST services (consumer) or calling external REST services (producer). | link:../camel-core/src/main/docs/rest-api-component.adoc[REST API] (camel-core) + `rest-api:path/contextIdPattern` | 2.16 | The rest-api component is used for providing Swagger API of the REST services which has been defined using the rest-dsl in Camel. | link:camel-restlet/src/main/docs/restlet-component.adoc[Restlet] (camel-restlet) + `restlet:protocol:host:port/uriPattern` | 2.0 | Component for consuming and producing Restful resources using Restlet. | link:camel-rmi/src/main/docs/rmi-component.adoc[RMI] (camel-rmi) + `rmi:hostname:port/name` | 1.0 | The rmi component is for invoking Java RMI beans from Camel. | link:camel-routebox/src/main/docs/routebox-component.adoc[RouteBox] (camel-routebox) + `routebox:routeboxName` | 2.6 | *deprecated* The routebox component allows to send/receive messages between Camel routes in a black box way. | link:camel-rss/src/main/docs/rss-component.adoc[RSS] (camel-rss) + `rss:feedUri` | 2.0 | The rss component is used for consuming RSS feeds. | link:camel-salesforce/src/main/docs/salesforce-component.adoc[Salesforce] (camel-salesforce) + `salesforce:operationName:topicName` | 2.12 | The salesforce component is used for integrating Camel with the massive Salesforce API. | link:camel-sap-netweaver/src/main/docs/sap-netweaver-component.adoc[SAP NetWeaver] (camel-sap-netweaver) + `sap-netweaver:url` | 2.12 | The sap-netweaver component integrates with the SAP NetWeaver Gateway using HTTP transports. | link:../camel-core/src/main/docs/scheduler-component.adoc[Scheduler] (camel-core) + `scheduler:name` | 2.15 | The scheduler component is used for generating message exchanges when a scheduler fires. | link:camel-schematron/src/main/docs/schematron-component.adoc[Schematron] (camel-schematron) + `schematron:path` | 2.15 | Validates the payload of a message using the Schematron Library. | link:camel-jsch/src/main/docs/scp-component.adoc[SCP] (camel-jsch) + `scp:host:port/directoryName` | 2.10 | To copy files using the secure copy protocol (SCP). | link:../camel-core/src/main/docs/seda-component.adoc[SEDA] (camel-core) + `seda:name` | 1.1 | The seda component provides asynchronous call to another endpoint from any CamelContext in the same JVM. | link:camel-servicenow/src/main/docs/servicenow-component.adoc[ServiceNow] (camel-servicenow) + `servicenow:instanceName` | 2.18 | The servicenow component is used to integrate Camel with ServiceNow cloud services. | link:camel-servlet/src/main/docs/servlet-component.adoc[Servlet] (camel-servlet) + `servlet:contextPath` | 2.0 | To use a HTTP Servlet as entry for Camel routes when running in a servlet container. | link:camel-ftp/src/main/docs/sftp-component.adoc[SFTP] (camel-ftp) + `sftp:host:port/directoryName` | 1.1 | The sftp (FTP over SSH) component is used for uploading or downloading files from SFTP servers. | link:camel-sjms/src/main/docs/sjms-component.adoc[Simple JMS] (camel-sjms) + `sjms:destinationType:destinationName` | 2.11 | The sjms component (simple jms) allows messages to be sent to (or consumed from) a JMS Queue or Topic. | link:camel-sjms/src/main/docs/sjms-batch-component.adoc[Simple JMS Batch] (camel-sjms) + `sjms-batch:destinationName` | 2.16 | The sjms-batch component is a specialized for highly performant transactional batch consumption from a JMS queue. | link:camel-sip/src/main/docs/sip-component.adoc[SIP] (camel-sip) + `sip:uri` | 2.5 | To send and receive messages using the SIP protocol (used in telco and mobile). | link:camel-slack/src/main/docs/slack-component.adoc[Slack] (camel-slack) + `slack:channel` | 2.16 | The slack component allows you to send messages to Slack. | link:camel-smpp/src/main/docs/smpp-component.adoc[SMPP] (camel-smpp) + `smpp:host:port` | 2.2 | To send and receive SMS using a SMSC (Short Message Service Center). | link:camel-snmp/src/main/docs/snmp-component.adoc[SNMP] (camel-snmp) + `snmp:host:port` | 2.1 | The snmp component gives you the ability to poll SNMP capable devices or receiving traps. | link:camel-solr/src/main/docs/solr-component.adoc[Solr] (camel-solr) + `solr:url` | 2.9 | The solr component allows you to interface with an Apache Lucene Solr server. | link:camel-spark-rest/src/main/docs/spark-rest-component.adoc[Spark Rest] (camel-spark-rest) + `spark-rest:verb:path` | 2.14 | The spark-rest component is used for hosting REST services which has been defined using Camel rest-dsl. | link:camel-splunk/src/main/docs/splunk-component.adoc[Splunk] (camel-splunk) + `splunk:name` | 2.13 | The splunk component allows to publish or search for events in Splunk. | link:camel-spring-batch/src/main/docs/spring-batch-component.adoc[Spring Batch] (camel-spring-batch) + `spring-batch:jobName` | 2.10 | The spring-batch component allows to send messages to Spring Batch for further processing. | link:camel-spring/src/main/docs/spring-event-component.adoc[Spring Event] (camel-spring) + `spring-event:name` | 1.4 | The spring-event component allows to listen for Spring Application Events. | link:camel-spring-integration/src/main/docs/spring-integration-component.adoc[Spring Integration] (camel-spring-integration) + `spring-integration:defaultChannel` | 1.4 | Bridges Camel with Spring Integration. | link:camel-spring-ldap/src/main/docs/spring-ldap-component.adoc[Spring LDAP] (camel-spring-ldap) + `spring-ldap:templateName` | 2.11 | The spring-ldap component allows you to perform searches in LDAP servers using filters as the message payload. | link:camel-spring-redis/src/main/docs/spring-redis-component.adoc[Spring Redis] (camel-spring-redis) + `spring-redis:host:port` | 2.11 | The spring-redis component allows sending and receiving messages from Redis. | link:camel-spring-ws/src/main/docs/spring-ws-component.adoc[Spring WebService] (camel-spring-ws) + `spring-ws:type:lookupKey:webServiceEndpointUri` | 2.6 | The spring-ws component is used for SOAP WebServices using Spring WebServices. | link:camel-sql/src/main/docs/sql-component.adoc[SQL] (camel-sql) + `sql:query` | 1.4 | The sql component allows you to work with databases using JDBC SQL queries. | link:camel-sql/src/main/docs/sql-stored-component.adoc[SQL StoredProcedure] (camel-sql) + `sql-stored:template` | 2.17 | The sql component allows you to work with databases using JDBC Stored Procedure queries. | link:camel-ssh/src/main/docs/ssh-component.adoc[SSH] (camel-ssh) + `ssh:host:port` | 2.10 | The ssh component enables access to SSH servers such that you can send an SSH command and process the response. | link:camel-stax/src/main/docs/stax-component.adoc[StAX] (camel-stax) + `stax:contentHandlerClass` | 2.9 | The stax component allows messages to be process through a SAX ContentHandler. | link:camel-stomp/src/main/docs/stomp-component.adoc[Stomp] (camel-stomp) + `stomp:destination` | 2.12 | The stomp component is used for communicating with Stomp compliant message brokers. | link:camel-stream/src/main/docs/stream-component.adoc[Stream] (camel-stream) + `stream:kind` | 1.3 | The stream: component provides access to the system-in system-out and system-err streams as well as allowing streaming of file and URL. | link:camel-stringtemplate/src/main/docs/string-template-component.adoc[String Template] (camel-stringtemplate) + `string-template:resourceUri` | 1.2 | Transforms the message using a String template. | link:../camel-core/src/main/docs/stub-component.adoc[Stub] (camel-core) + `stub:name` | 2.10 | The stub component provides a simple way to stub out any physical endpoints while in development or testing. | link:camel-telegram/src/main/docs/telegram-component.adoc[Telegram] (camel-telegram) + `telegram:type/authorizationToken` | 2.18 | The telegram component provides access to the Telegram Bot API. | link:../camel-core/src/main/docs/test-component.adoc[Test] (camel-core) + `test:name` | 1.3 | The test component extends the mock component by on startup to pull messages from another endpoint to set the expected message bodies. | link:camel-tika/src/main/docs/tika-component.adoc[Tika] (camel-tika) + `tika:operation` | 2.19 | This component integrates with Apache Tika to extract content and metadata from thousands of file types. | link:../camel-core/src/main/docs/timer-component.adoc[Timer] (camel-core) + `timer:timerName` | 1.0 | The timer component is used for generating message exchanges when a timer fires. | link:camel-twitter/src/main/docs/twitter-component.adoc[Twitter] (camel-twitter) + `twitter:kind` | 2.10 | This component integrates with Twitter to send tweets or search for tweets and more. | link:camel-undertow/src/main/docs/undertow-component.adoc[Undertow] (camel-undertow) + `undertow:httpURI` | 2.16 | The undertow component provides HTTP-based endpoints for consuming and producing HTTP requests. | link:../camel-core/src/main/docs/validator-component.adoc[Validator] (camel-core) + `validator:resourceUri` | 1.1 | Validates the payload of a message using XML Schema and JAXP Validation. | link:camel-velocity/src/main/docs/velocity-component.adoc[Velocity] (camel-velocity) + `velocity:resourceUri` | 1.2 | Transforms the message using a Velocity template. | link:camel-vertx/src/main/docs/vertx-component.adoc[Vert.x] (camel-vertx) + `vertx:address` | 2.12 | The vertx component is used for sending and receive messages from a vertx event bus. | link:../camel-core/src/main/docs/vm-component.adoc[VM] (camel-core) + `vm:name` | 1.1 | The vm component provides asynchronous call to another endpoint from the same CamelContext. | link:camel-weather/src/main/docs/weather-component.adoc[Weather] (camel-weather) + `weather:name` | 2.12 | Polls the weather information from Open Weather Map. | link:camel-xmlrpc/src/main/docs/xmlrpc-component.adoc[XML RPC] (camel-xmlrpc) + `xmlrpc:address` | 2.11 | The xmlrpc component is used for sending messages to a XML RPC service. | link:camel-xmlsecurity/src/main/docs/xmlsecurity-component.adoc[XML Security] (camel-xmlsecurity) + `xmlsecurity:command:name` | 2.12 | Used to sign and verify exchanges using the XML signature specification. | link:camel-xmpp/src/main/docs/xmpp-component.adoc[XMPP] (camel-xmpp) + `xmpp:host:port/participant` | 1.0 | To send and receive messages from a XMPP (chat) server. | link:camel-saxon/src/main/docs/xquery-component.adoc[XQuery] (camel-saxon) + `xquery:resourceUri` | 1.0 | Transforms the message using a XQuery template using Saxon. | link:../camel-core/src/main/docs/xslt-component.adoc[XSLT] (camel-core) + `xslt:resourceUri` | 1.3 | Transforms the message using a XSLT template. | link:camel-yammer/src/main/docs/yammer-component.adoc[Yammer] (camel-yammer) + `yammer:function` | 2.12 | The yammer component allows you to interact with the Yammer enterprise social network. | link:camel-zookeeper/src/main/docs/zookeeper-component.adoc[ZooKeeper] (camel-zookeeper) + `zookeeper:serverUrls/path` | 2.9 | The zookeeper component allows interaction with a ZooKeeper cluster. |======================================================================= // components: END Data Formats ^^^^^^^^^^^^ // dataformats: START Number of Data Formats: 45 [width=""100%"",cols=""4,1,5"",options=""header""] |======================================================================= | Data Format | Available From | Description | link:camel-avro/src/main/docs/avro-dataformat.adoc[Avro] (camel-avro) | 2.14 | Camel Avro data format | link:camel-barcode/src/main/docs/barcode-dataformat.adoc[Barcode] (camel-barcode) | 2.14 | Camel Barcode (e.g. QRcode, PDF417, DataMatrix) support | link:camel-base64/src/main/docs/base64-dataformat.adoc[Base64] (camel-base64) | 2.11 | Camel Base64 data format support | link:camel-beanio/src/main/docs/beanio-dataformat.adoc[BeanIO] (camel-beanio) | 2.10 | Camel BeanIO data format support | link:camel-bindy/src/main/docs/bindy-dataformat.adoc[Bindy CSV] (camel-bindy) | 2.0 | Camel Bindy data format support | link:camel-bindy/src/main/docs/bindy-dataformat.adoc[Bindy Fixed Length] (camel-bindy) | 2.0 | Camel Bindy data format support | link:camel-bindy/src/main/docs/bindy-dataformat.adoc[Bindy Key Value Pair] (camel-bindy) | 2.0 | Camel Bindy data format support | link:camel-boon/src/main/docs/boon-dataformat.adoc[Boon] (camel-boon) | 2.16 | Camel Boon support | link:camel-castor/src/main/docs/castor-dataformat.adoc[Castor] (camel-castor) | 2.1 | Camel Castor data format support | link:camel-crypto/src/main/docs/crypto-dataformat.adoc[Crypto (Java Cryptographic Extension)] (camel-crypto) | 2.3 | Camel Cryptographic Support | link:camel-csv/src/main/docs/csv-dataformat.adoc[CSV] (camel-csv) | 1.3 | Camel CSV data format support | link:camel-flatpack/src/main/docs/flatpack-dataformat.adoc[Flatpack] (camel-flatpack) | 2.1 | Camel FlatPack support | link:src/main/docs/gzip-dataformat.adoc[GZip] (camel-core) | 2.0 | GZip compression data format | link:camel-hessian/src/main/docs/hessian-dataformat.adoc[Hessian] (camel-hessian) | 2.17 | Hessian serialization support | link:camel-hl7/src/main/docs/hl7-dataformat.adoc[HL7] (camel-hl7) | 2.0 | Camel HL7 support | link:camel-ical/src/main/docs/ical-dataformat.adoc[iCal] (camel-ical) | 2.12 | Camel iCal component | link:camel-jacksonxml/src/main/docs/jacksonxml-dataformat.adoc[JacksonXML] (camel-jacksonxml) | 2.16 | Camel Jackson XML support | link:src/main/docs/serialization-dataformat.adoc[Java Object Serialization] (camel-core) | 2.12 | Java Object Serialization data format | link:camel-jaxb/src/main/docs/jaxb-dataformat.adoc[JAXB] (camel-jaxb) | 1.0 | Camel JAXB support | link:camel-jibx/src/main/docs/jibx-dataformat.adoc[JiBX] (camel-jibx) | 2.6 | Camel Jibx support | link:camel-gson/src/main/docs/json-gson-dataformat.adoc[JSon GSon] (camel-gson) | 2.10 | Camel Gson support | link:camel-jackson/src/main/docs/json-jackson-dataformat.adoc[JSon Jackson] (camel-jackson) | 2.0 | Camel Jackson support | link:camel-johnzon/src/main/docs/json-johnzon-dataformat.adoc[JSon Johnzon] (camel-johnzon) | 2.18 | Camel Johnzon support | link:camel-xstream/src/main/docs/json-xstream-dataformat.adoc[JSon XStream] (camel-xstream) | 2.0 | Camel XStream support | link:camel-lzf/src/main/docs/lzf-dataformat.adoc[LZF Deflate Compression] (camel-lzf) | 2.17 | Camel LZF support | link:camel-mail/src/main/docs/mime-multipart-dataformat.adoc[MIME Multipart] (camel-mail) | 2.17 | Camel Mail support | link:camel-crypto/src/main/docs/pgp-dataformat.adoc[PGP] (camel-crypto) | 2.9 | Camel Cryptographic Support | link:camel-protobuf/src/main/docs/protobuf-dataformat.adoc[Protobuf] (camel-protobuf) | 2.2 | Camel Google Protobuf data format support | link:camel-rss/src/main/docs/rss-dataformat.adoc[RSS] (camel-rss) | 2.1 | Camel RSS support | link:camel-soap/src/main/docs/soapjaxb-dataformat.adoc[SOAP] (camel-soap) | 2.3 | Camel SOAP support | link:src/main/docs/string-dataformat.adoc[String Encoding] (camel-core) | 2.12 | String (text based) data format | link:camel-syslog/src/main/docs/syslog-dataformat.adoc[Syslog] (camel-syslog) | 2.6 | Camel Syslog support | link:camel-tarfile/src/main/docs/tarfile-dataformat.adoc[Tar File] (camel-tarfile) | 2.16 | Camel Tar file support | link:camel-tagsoup/src/main/docs/tidyMarkup-dataformat.adoc[TidyMarkup] (camel-tagsoup) | 2.0 | Camel TagSoup support | link:camel-univocity-parsers/src/main/docs/univocity-csv-dataformat.adoc[uniVocity CSV] (camel-univocity-parsers) | 2.15 | Camel UniVocity parsers data format support | link:camel-univocity-parsers/src/main/docs/univocity-fixed-dataformat.adoc[uniVocity Fixed Length] (camel-univocity-parsers) | 2.15 | Camel UniVocity parsers data format support | link:camel-univocity-parsers/src/main/docs/univocity-tsv-dataformat.adoc[uniVocity TSV] (camel-univocity-parsers) | 2.15 | Camel UniVocity parsers data format support | link:camel-xmlbeans/src/main/docs/xmlBeans-dataformat.adoc[XML Beans] (camel-xmlbeans) | 1.2 | Camel XMLBeans support | link:camel-xmljson/src/main/docs/xmljson-dataformat.adoc[XML JSon] (camel-xmljson) | 2.10 | Camel XML JSON Data Format | link:camel-xmlrpc/src/main/docs/xmlrpc-dataformat.adoc[XML RPC] (camel-xmlrpc) | 2.11 | Camel XML RPC support | link:camel-xmlsecurity/src/main/docs/secureXML-dataformat.adoc[XML Security] (camel-xmlsecurity) | 2.0 | Camel Partial XML Encryption/Decryption and XML Signature support | link:camel-xstream/src/main/docs/xstream-dataformat.adoc[XStream] (camel-xstream) | 1.3 | Camel XStream support | link:camel-snakeyaml/src/main/docs/yaml-snakeyaml-dataformat.adoc[YAML SnakeYAML] (camel-snakeyaml) | 2.17 | Camel SnakeYAML support | link:src/main/docs/zip-dataformat.adoc[Zip Deflate Compression] (camel-core) | 2.12 | Zip compression data format (not for zip files) | link:camel-zipfile/src/main/docs/zipfile-dataformat.adoc[Zip File] (camel-zipfile) | 2.11 | Camel Zip file support |======================================================================= // dataformats: END Expression Languages ^^^^^^^^^^^^^^^^^^^^ // languages: START Number of Languages: 24 [width=""100%"",cols=""4,1,5"",options=""header""] |======================================================================= | Language | Available From | Description | link:src/main/docs/bean-language.adoc[Bean method] (camel-core) | 1.3 | For expressions and predicates using a java bean (aka method call) | link:src/main/docs/constant-language.adoc[Constant] (camel-core) | 1.5 | For expressions and predicates using a constant | link:camel-juel/src/main/docs/el-language.adoc[EL] (camel-juel) | 1.1 | For EL expressions and predicates | link:src/main/docs/exchangeProperty-language.adoc[ExchangeProperty] (camel-core) | 2.0 | An expression which extracts the named exchange property | link:src/main/docs/file-language.adoc[File] (camel-core) | 1.1 | For expressions and predicates using the file/simple language | link:camel-groovy/src/main/docs/groovy-language.adoc[Groovy] (camel-groovy) | 1.3 | For Groovy expressions and predicates | link:src/main/docs/header-language.adoc[Header] (camel-core) | 1.5 | An expression which extracts the named exchange header | link:camel-hl7/src/main/docs/terser-language.adoc[HL7 Terser] (camel-hl7) | 2.11 | For HL7 terser expressions and predicates | link:camel-script/src/main/docs/javaScript-language.adoc[JavaScript] (camel-script) | 1.0 | For JavaScript expressions and predicates | link:camel-jsonpath/src/main/docs/jsonpath-language.adoc[JSonPath] (camel-jsonpath) | 2.13 | For JSonPath expressions and predicates | link:camel-jxpath/src/main/docs/jxpath-language.adoc[JXPath] (camel-jxpath) | 1.3 | For JXPath expressions and predicates | link:camel-mvel/src/main/docs/mvel-language.adoc[MVEL] (camel-mvel) | 2.0 | For MVEL expressions and predicates | link:camel-ognl/src/main/docs/ognl-language.adoc[OGNL] (camel-ognl) | 1.1 | For OGNL expressions and predicates | link:camel-script/src/main/docs/php-language.adoc[PHP] (camel-script) | 1.0 | For PHP expressions and predicates | link:camel-script/src/main/docs/python-language.adoc[Python] (camel-script) | 1.0 | For Python expressions and predicates | link:src/main/docs/ref-language.adoc[Ref] (camel-core) | 2.8 | For using a custom expression or predicate | link:camel-script/src/main/docs/ruby-language.adoc[Ruby] (camel-script) | 1.0 | For Ruby expressions and predicates | link:src/main/docs/simple-language.adoc[Simple] (camel-core) | 1.1 | For expressions and predicates using the simple language | link:camel-spring/src/main/docs/spel-language.adoc[SpEL] (camel-spring) | 2.7 | For Spring Expression Language (SpEL) expressions and predicates | link:camel-josql/src/main/docs/sql-language.adoc[SQL] (camel-josql) | 1.0 | For SQL expressions and predicates | link:src/main/docs/tokenize-language.adoc[Tokenize] (camel-core) | 2.0 | For expressions and predicates using a body or header tokenizer | link:src/main/docs/xtokenize-language.adoc[XML Tokenize] (camel-core) | 2.14 | For expressions and predicates using a body or header XML tokenizer | link:src/main/docs/xpath-language.adoc[XPath] (camel-core) | 1.1 | For XPath expressions and predicates | link:camel-saxon/src/main/docs/xquery-language.adoc[XQuery] (camel-saxon) | 1.0 | For XQuery expressions and predicates |======================================================================= // languages: END Miscellaneous Components ^^^^^^^^^^^^^^^^^^^^^^^^ // others: START Number of Miscellaneous Components: 33 [width=""100%"",cols=""4,1,5"",options=""header""] |======================================================================= | Component | Available From | Description | link:camel-bam/src/main/docs/bam.adoc[BAM] (camel-bam) | 1.0 | *deprecated* Business Activity Monitoring | link:camel-blueprint/src/main/docs/blueprint.adoc[Blueprint] (camel-blueprint) | 2.4 | Using Camel with OSGi Blueprint | link:camel-cdi/src/main/docs/cdi.adoc[CDI] (camel-cdi) | 2.10 | Using Camel with CDI | link:camel-cxf-transport/src/main/docs/cxf-transport.adoc[CXF Transport] (camel-cxf-transport) | 2.8 | Camel Transport for Apache CXF | link:camel-eclipse/src/main/docs/eclipse.adoc[Eclipse] (camel-eclipse) | 2.3 | *deprecated* Camel classpath scanning support for running in Eclipse Desktop Applications | link:camel-guice/src/main/docs/guice.adoc[Guice] (camel-guice) | 1.5 | Using Camel with Guice | link:camel-hawtdb/src/main/docs/hawtdb.adoc[Hawtdb] (camel-hawtdb) | 2.3 | *deprecated* Using HawtDB as persistent EIP store | link:camel-hystrix/src/main/docs/hystrix.adoc[Hystrix] (camel-hystrix) | 2.18 | Circuit Breaker EIP using Netflix Hystrix | link:camel-jasypt/src/main/docs/jasypt.adoc[Jasypt] (camel-jasypt) | 2.5 | Security using Jasypt | link:camel-kura/src/main/docs/kura.adoc[Kura] (camel-kura) | 2.15 | Using Camel with Eclipse Kura (OSGi) | link:camel-leveldb/src/main/docs/leveldb.adoc[LevelDB] (camel-leveldb) | 2.10 | Using LevelDB as persistent EIP store | link:camel-ribbon/src/main/docs/ribbon.adoc[Ribbon] (camel-ribbon) | 2.18 | Camel Components | link:camel-ruby/src/main/docs/ruby.adoc[Ruby] (camel-ruby) | 1.0 | *deprecated* Camel Ruby DSL | link:camel-rx/src/main/docs/rx.adoc[RX] (camel-rx) | 2.11 | Camel Reactive using RxJava library | link:camel-scala/src/main/docs/scala.adoc[Scala] (camel-scala) | 1.4 | Camel Scala DSL | link:camel-scr/src/main/docs/scr.adoc[SCR] (camel-scr) | 2.15 | Camel with OSGi SCR (Declarative Services) | link:camel-servletlistener/src/main/docs/servletlistener.adoc[Servlet Listener] (camel-servletlistener) | 2.11 | Bootstrapping Camel using Servet Listener | link:camel-shiro/src/main/docs/shiro.adoc[Shiro] (camel-shiro) | 2.5 | Security using Shiro | link:camel-spring-boot/src/main/docs/spring-boot.adoc[Spring Boot] (camel-spring-boot) | 2.15 | Using Camel with Spring Boot | link:camel-spring-cloud/src/main/docs/spring-cloud.adoc[Spring Cloud] (camel-spring-cloud) | 2.19 | Camel Cloud integration with Spring Cloud | link:camel-spring-dm/src/main/docs/spring-dm.adoc[Spring DM] (camel-spring-dm) | 2.18 | *deprecated* Camel SpringDM (OSGi) XML DSL | link:camel-spring-javaconfig/src/main/docs/spring-javaconfig.adoc[Spring Java Configuration] (camel-spring-javaconfig) | 2.0 | Using Camel with Spring Java Configuration | link:camel-spring-security/src/main/docs/spring-security.adoc[Spring Security] (camel-spring-security) | 2.3 | Security using Spring Security | link:camel-swagger/src/main/docs/swagger.adoc[Swagger] (camel-swagger) | 2.14 | *deprecated* Rest-dsl support for using swagger api-doc | link:camel-swagger-java/src/main/docs/swagger-java.adoc[Swagger Java] (camel-swagger-java) | 2.16 | Rest-dsl support for using swagger api-doc | link:camel-test/src/main/docs/test.adoc[Test] (camel-test) | 2.9 | Camel unit testing | link:camel-test-blueprint/src/main/docs/test-blueprint.adoc[Test Blueprint] (camel-test-blueprint) | 2.10 | Camel unit testing with OSGi Blueprint | link:camel-test-cdi/src/main/docs/test-cdi.adoc[Test CDI] (camel-test-cdi) | 2.17 | Camel unit testing with CDI | link:camel-test-karaf/src/main/docs/test-karaf.adoc[Test Karaf] (camel-test-karaf) | 2.18 | Camel integration testing with Apache Karaf | link:camel-test-spring/src/main/docs/test-spring.adoc[Test Spring] (camel-test-spring) | 2.10 | Camel unit testing with Spring | link:camel-testng/src/main/docs/testng.adoc[TestNG] (camel-testng) | 2.8 | *deprecated* Camel unit testing with TestNG | link:camel-urlrewrite/src/main/docs/urlrewrite.adoc[URLRewrite] (camel-urlrewrite) | 2.11 | *deprecated* URL rewrite support for HTTP components | link:camel-zipkin/src/main/docs/zipkin.adoc[Zipkin] (camel-zipkin) | 2.18 | Distributed message tracing using Zipkin |======================================================================= // others: END ",16205,True,4757.803332590619,median "pragma Style_Checks (Off); -- This spec has been automatically generated from STM32H743x.svd pragma Restrictions (No_Elaboration_Code); with HAL; with System; package STM32_SVD.AXI is pragma Preelaborate; --------------- -- Registers -- --------------- subtype AXI_PERIPH_ID_4_JEP106CON_Field is HAL.UInt4; subtype AXI_PERIPH_ID_4_KCOUNT4_Field is HAL.UInt4; -- AXI interconnect - peripheral ID4 register type AXI_PERIPH_ID_4_Register is record -- Read-only. JEP106 continuation code JEP106CON : AXI_PERIPH_ID_4_JEP106CON_Field; -- Read-only. Register file size KCOUNT4 : AXI_PERIPH_ID_4_KCOUNT4_Field; -- unspecified Reserved_8_31 : HAL.UInt24; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_PERIPH_ID_4_Register use record JEP106CON at 0 range 0 .. 3; KCOUNT4 at 0 range 4 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; subtype AXI_PERIPH_ID_0_PARTNUM_Field is HAL.UInt8; -- AXI interconnect - peripheral ID0 register type AXI_PERIPH_ID_0_Register is record -- Read-only. Peripheral part number bits 0 to 7 PARTNUM : AXI_PERIPH_ID_0_PARTNUM_Field; -- unspecified Reserved_8_31 : HAL.UInt24; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_PERIPH_ID_0_Register use record PARTNUM at 0 range 0 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; subtype AXI_PERIPH_ID_1_PARTNUM_Field is HAL.UInt4; subtype AXI_PERIPH_ID_1_JEP106I_Field is HAL.UInt4; -- AXI interconnect - peripheral ID1 register type AXI_PERIPH_ID_1_Register is record -- Read-only. Peripheral part number bits 8 to 11 PARTNUM : AXI_PERIPH_ID_1_PARTNUM_Field; -- Read-only. JEP106 identity bits 0 to 3 JEP106I : AXI_PERIPH_ID_1_JEP106I_Field; -- unspecified Reserved_8_31 : HAL.UInt24; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_PERIPH_ID_1_Register use record PARTNUM at 0 range 0 .. 3; JEP106I at 0 range 4 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; subtype AXI_PERIPH_ID_2_JEP106ID_Field is HAL.UInt3; subtype AXI_PERIPH_ID_2_REVISION_Field is HAL.UInt4; -- AXI interconnect - peripheral ID2 register type AXI_PERIPH_ID_2_Register is record -- Read-only. JEP106 Identity bits 4 to 6 JEP106ID : AXI_PERIPH_ID_2_JEP106ID_Field; -- Read-only. JEP106 code flag JEDEC : Boolean; -- Read-only. Peripheral revision number REVISION : AXI_PERIPH_ID_2_REVISION_Field; -- unspecified Reserved_8_31 : HAL.UInt24; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_PERIPH_ID_2_Register use record JEP106ID at 0 range 0 .. 2; JEDEC at 0 range 3 .. 3; REVISION at 0 range 4 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; subtype AXI_PERIPH_ID_3_CUST_MOD_NUM_Field is HAL.UInt4; subtype AXI_PERIPH_ID_3_REV_AND_Field is HAL.UInt4; -- AXI interconnect - peripheral ID3 register type AXI_PERIPH_ID_3_Register is record -- Read-only. Customer modification CUST_MOD_NUM : AXI_PERIPH_ID_3_CUST_MOD_NUM_Field; -- Read-only. Customer version REV_AND : AXI_PERIPH_ID_3_REV_AND_Field; -- unspecified Reserved_8_31 : HAL.UInt24; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_PERIPH_ID_3_Register use record CUST_MOD_NUM at 0 range 0 .. 3; REV_AND at 0 range 4 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; subtype AXI_COMP_ID_0_PREAMBLE_Field is HAL.UInt8; -- AXI interconnect - component ID0 register type AXI_COMP_ID_0_Register is record -- Read-only. Preamble bits 0 to 7 PREAMBLE : AXI_COMP_ID_0_PREAMBLE_Field; -- unspecified Reserved_8_31 : HAL.UInt24; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_COMP_ID_0_Register use record PREAMBLE at 0 range 0 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; subtype AXI_COMP_ID_1_PREAMBLE_Field is HAL.UInt4; subtype AXI_COMP_ID_1_CLASS_Field is HAL.UInt4; -- AXI interconnect - component ID1 register type AXI_COMP_ID_1_Register is record -- Read-only. Preamble bits 8 to 11 PREAMBLE : AXI_COMP_ID_1_PREAMBLE_Field; -- Read-only. Component class CLASS : AXI_COMP_ID_1_CLASS_Field; -- unspecified Reserved_8_31 : HAL.UInt24; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_COMP_ID_1_Register use record PREAMBLE at 0 range 0 .. 3; CLASS at 0 range 4 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; subtype AXI_COMP_ID_2_PREAMBLE_Field is HAL.UInt8; -- AXI interconnect - component ID2 register type AXI_COMP_ID_2_Register is record -- Read-only. Preamble bits 12 to 19 PREAMBLE : AXI_COMP_ID_2_PREAMBLE_Field; -- unspecified Reserved_8_31 : HAL.UInt24; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_COMP_ID_2_Register use record PREAMBLE at 0 range 0 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; subtype AXI_COMP_ID_3_PREAMBLE_Field is HAL.UInt8; -- AXI interconnect - component ID3 register type AXI_COMP_ID_3_Register is record -- Read-only. Preamble bits 20 to 27 PREAMBLE : AXI_COMP_ID_3_PREAMBLE_Field; -- unspecified Reserved_8_31 : HAL.UInt24; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_COMP_ID_3_Register use record PREAMBLE at 0 range 0 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; -- AXI interconnect - TARG x bus matrix issuing functionality register type AXI_TARG1_FN_MOD_ISS_BM_Register is record -- READ_ISS_OVERRIDE READ_ISS_OVERRIDE : Boolean := False; -- Switch matrix write issuing override for target WRITE_ISS_OVERRIDE : Boolean := False; -- unspecified Reserved_2_31 : HAL.UInt30 := 16#1#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_TARG1_FN_MOD_ISS_BM_Register use record READ_ISS_OVERRIDE at 0 range 0 .. 0; WRITE_ISS_OVERRIDE at 0 range 1 .. 1; Reserved_2_31 at 0 range 2 .. 31; end record; -- AXI interconnect - TARG x bus matrix functionality 2 register type AXI_TARG1_FN_MOD2_Register is record -- Disable packing of beats to match the output data width BYPASS_MERGE : Boolean := False; -- unspecified Reserved_1_31 : HAL.UInt31 := 16#2#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_TARG1_FN_MOD2_Register use record BYPASS_MERGE at 0 range 0 .. 0; Reserved_1_31 at 0 range 1 .. 31; end record; -- AXI interconnect - TARG x long burst functionality modification type AXI_TARG1_FN_MOD_LB_Register is record -- Controls burst breaking of long bursts FN_MOD_LB : Boolean := False; -- unspecified Reserved_1_31 : HAL.UInt31 := 16#2#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_TARG1_FN_MOD_LB_Register use record FN_MOD_LB at 0 range 0 .. 0; Reserved_1_31 at 0 range 1 .. 31; end record; -- AXI interconnect - TARG x long burst functionality modification type AXI_TARG1_FN_MOD_Register is record -- Override AMIB read issuing capability READ_ISS_OVERRIDE : Boolean := False; -- Override AMIB write issuing capability WRITE_ISS_OVERRIDE : Boolean := False; -- unspecified Reserved_2_31 : HAL.UInt30 := 16#1#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_TARG1_FN_MOD_Register use record READ_ISS_OVERRIDE at 0 range 0 .. 0; WRITE_ISS_OVERRIDE at 0 range 1 .. 1; Reserved_2_31 at 0 range 2 .. 31; end record; -- AXI interconnect - TARG x bus matrix issuing functionality register type AXI_TARG2_FN_MOD_ISS_BM_Register is record -- READ_ISS_OVERRIDE READ_ISS_OVERRIDE : Boolean := False; -- Switch matrix write issuing override for target WRITE_ISS_OVERRIDE : Boolean := False; -- unspecified Reserved_2_31 : HAL.UInt30 := 16#1#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_TARG2_FN_MOD_ISS_BM_Register use record READ_ISS_OVERRIDE at 0 range 0 .. 0; WRITE_ISS_OVERRIDE at 0 range 1 .. 1; Reserved_2_31 at 0 range 2 .. 31; end record; -- AXI interconnect - TARG x bus matrix functionality 2 register type AXI_TARG2_FN_MOD2_Register is record -- Disable packing of beats to match the output data width BYPASS_MERGE : Boolean := False; -- unspecified Reserved_1_31 : HAL.UInt31 := 16#2#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_TARG2_FN_MOD2_Register use record BYPASS_MERGE at 0 range 0 .. 0; Reserved_1_31 at 0 range 1 .. 31; end record; -- AXI interconnect - TARG x long burst functionality modification type AXI_TARG2_FN_MOD_LB_Register is record -- Controls burst breaking of long bursts FN_MOD_LB : Boolean := False; -- unspecified Reserved_1_31 : HAL.UInt31 := 16#2#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_TARG2_FN_MOD_LB_Register use record FN_MOD_LB at 0 range 0 .. 0; Reserved_1_31 at 0 range 1 .. 31; end record; -- AXI interconnect - TARG x long burst functionality modification type AXI_TARG2_FN_MOD_Register is record -- Override AMIB read issuing capability READ_ISS_OVERRIDE : Boolean := False; -- Override AMIB write issuing capability WRITE_ISS_OVERRIDE : Boolean := False; -- unspecified Reserved_2_31 : HAL.UInt30 := 16#1#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_TARG2_FN_MOD_Register use record READ_ISS_OVERRIDE at 0 range 0 .. 0; WRITE_ISS_OVERRIDE at 0 range 1 .. 1; Reserved_2_31 at 0 range 2 .. 31; end record; -- AXI interconnect - TARG x bus matrix issuing functionality register type AXI_TARG3_FN_MOD_ISS_BM_Register is record -- READ_ISS_OVERRIDE READ_ISS_OVERRIDE : Boolean := False; -- Switch matrix write issuing override for target WRITE_ISS_OVERRIDE : Boolean := False; -- unspecified Reserved_2_31 : HAL.UInt30 := 16#1#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_TARG3_FN_MOD_ISS_BM_Register use record READ_ISS_OVERRIDE at 0 range 0 .. 0; WRITE_ISS_OVERRIDE at 0 range 1 .. 1; Reserved_2_31 at 0 range 2 .. 31; end record; -- AXI interconnect - TARG x bus matrix issuing functionality register type AXI_TARG4_FN_MOD_ISS_BM_Register is record -- READ_ISS_OVERRIDE READ_ISS_OVERRIDE : Boolean := False; -- Switch matrix write issuing override for target WRITE_ISS_OVERRIDE : Boolean := False; -- unspecified Reserved_2_31 : HAL.UInt30 := 16#1#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_TARG4_FN_MOD_ISS_BM_Register use record READ_ISS_OVERRIDE at 0 range 0 .. 0; WRITE_ISS_OVERRIDE at 0 range 1 .. 1; Reserved_2_31 at 0 range 2 .. 31; end record; -- AXI interconnect - TARG x bus matrix issuing functionality register type AXI_TARG5_FN_MOD_ISS_BM_Register is record -- READ_ISS_OVERRIDE READ_ISS_OVERRIDE : Boolean := False; -- Switch matrix write issuing override for target WRITE_ISS_OVERRIDE : Boolean := False; -- unspecified Reserved_2_31 : HAL.UInt30 := 16#1#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_TARG5_FN_MOD_ISS_BM_Register use record READ_ISS_OVERRIDE at 0 range 0 .. 0; WRITE_ISS_OVERRIDE at 0 range 1 .. 1; Reserved_2_31 at 0 range 2 .. 31; end record; -- AXI interconnect - TARG x bus matrix issuing functionality register type AXI_TARG6_FN_MOD_ISS_BM_Register is record -- READ_ISS_OVERRIDE READ_ISS_OVERRIDE : Boolean := False; -- Switch matrix write issuing override for target WRITE_ISS_OVERRIDE : Boolean := False; -- unspecified Reserved_2_31 : HAL.UInt30 := 16#1#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_TARG6_FN_MOD_ISS_BM_Register use record READ_ISS_OVERRIDE at 0 range 0 .. 0; WRITE_ISS_OVERRIDE at 0 range 1 .. 1; Reserved_2_31 at 0 range 2 .. 31; end record; -- AXI interconnect - TARG x bus matrix issuing functionality register type AXI_TARG7_FN_MOD_ISS_BM_Register is record -- READ_ISS_OVERRIDE READ_ISS_OVERRIDE : Boolean := False; -- Switch matrix write issuing override for target WRITE_ISS_OVERRIDE : Boolean := False; -- unspecified Reserved_2_31 : HAL.UInt30 := 16#1#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_TARG7_FN_MOD_ISS_BM_Register use record READ_ISS_OVERRIDE at 0 range 0 .. 0; WRITE_ISS_OVERRIDE at 0 range 1 .. 1; Reserved_2_31 at 0 range 2 .. 31; end record; -- AXI interconnect - TARG x bus matrix functionality 2 register type AXI_TARG7_FN_MOD2_Register is record -- Disable packing of beats to match the output data width BYPASS_MERGE : Boolean := False; -- unspecified Reserved_1_31 : HAL.UInt31 := 16#2#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_TARG7_FN_MOD2_Register use record BYPASS_MERGE at 0 range 0 .. 0; Reserved_1_31 at 0 range 1 .. 31; end record; -- AXI interconnect - TARG x long burst functionality modification type AXI_TARG7_FN_MOD_Register is record -- Override AMIB read issuing capability READ_ISS_OVERRIDE : Boolean := False; -- Override AMIB write issuing capability WRITE_ISS_OVERRIDE : Boolean := False; -- unspecified Reserved_2_31 : HAL.UInt30 := 16#1#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_TARG7_FN_MOD_Register use record READ_ISS_OVERRIDE at 0 range 0 .. 0; WRITE_ISS_OVERRIDE at 0 range 1 .. 1; Reserved_2_31 at 0 range 2 .. 31; end record; -- AXI interconnect - INI x functionality modification 2 register type AXI_INI1_FN_MOD2_Register is record -- Disables alteration of transactions by the up-sizer unless required -- by the protocol BYPASS_MERGE : Boolean := False; -- unspecified Reserved_1_31 : HAL.UInt31 := 16#2#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_INI1_FN_MOD2_Register use record BYPASS_MERGE at 0 range 0 .. 0; Reserved_1_31 at 0 range 1 .. 31; end record; -- AXI interconnect - INI x AHB functionality modification register type AXI_INI1_FN_MOD_AHB_Register is record -- Converts all AHB-Lite write transactions to a series of single beat -- AXI RD_INC_OVERRIDE : Boolean := False; -- Converts all AHB-Lite read transactions to a series of single beat -- AXI WR_INC_OVERRIDE : Boolean := False; -- unspecified Reserved_2_31 : HAL.UInt30 := 16#1#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_INI1_FN_MOD_AHB_Register use record RD_INC_OVERRIDE at 0 range 0 .. 0; WR_INC_OVERRIDE at 0 range 1 .. 1; Reserved_2_31 at 0 range 2 .. 31; end record; subtype AXI_INI1_READ_QOS_AR_QOS_Field is HAL.UInt4; -- AXI interconnect - INI x read QoS register type AXI_INI1_READ_QOS_Register is record -- Read channel QoS setting AR_QOS : AXI_INI1_READ_QOS_AR_QOS_Field := 16#4#; -- unspecified Reserved_4_31 : HAL.UInt28 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_INI1_READ_QOS_Register use record AR_QOS at 0 range 0 .. 3; Reserved_4_31 at 0 range 4 .. 31; end record; subtype AXI_INI1_WRITE_QOS_AW_QOS_Field is HAL.UInt4; -- AXI interconnect - INI x write QoS register type AXI_INI1_WRITE_QOS_Register is record -- Write channel QoS setting AW_QOS : AXI_INI1_WRITE_QOS_AW_QOS_Field := 16#4#; -- unspecified Reserved_4_31 : HAL.UInt28 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_INI1_WRITE_QOS_Register use record AW_QOS at 0 range 0 .. 3; Reserved_4_31 at 0 range 4 .. 31; end record; -- AXI interconnect - INI x issuing functionality modification register type AXI_INI1_FN_MOD_Register is record -- Override ASIB read issuing capability READ_ISS_OVERRIDE : Boolean := False; -- Override ASIB write issuing capability WRITE_ISS_OVERRIDE : Boolean := False; -- unspecified Reserved_2_31 : HAL.UInt30 := 16#1#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_INI1_FN_MOD_Register use record READ_ISS_OVERRIDE at 0 range 0 .. 0; WRITE_ISS_OVERRIDE at 0 range 1 .. 1; Reserved_2_31 at 0 range 2 .. 31; end record; subtype AXI_INI2_READ_QOS_AR_QOS_Field is HAL.UInt4; -- AXI interconnect - INI x read QoS register type AXI_INI2_READ_QOS_Register is record -- Read channel QoS setting AR_QOS : AXI_INI2_READ_QOS_AR_QOS_Field := 16#4#; -- unspecified Reserved_4_31 : HAL.UInt28 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_INI2_READ_QOS_Register use record AR_QOS at 0 range 0 .. 3; Reserved_4_31 at 0 range 4 .. 31; end record; subtype AXI_INI2_WRITE_QOS_AW_QOS_Field is HAL.UInt4; -- AXI interconnect - INI x write QoS register type AXI_INI2_WRITE_QOS_Register is record -- Write channel QoS setting AW_QOS : AXI_INI2_WRITE_QOS_AW_QOS_Field := 16#4#; -- unspecified Reserved_4_31 : HAL.UInt28 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_INI2_WRITE_QOS_Register use record AW_QOS at 0 range 0 .. 3; Reserved_4_31 at 0 range 4 .. 31; end record; -- AXI interconnect - INI x issuing functionality modification register type AXI_INI2_FN_MOD_Register is record -- Override ASIB read issuing capability READ_ISS_OVERRIDE : Boolean := False; -- Override ASIB write issuing capability WRITE_ISS_OVERRIDE : Boolean := False; -- unspecified Reserved_2_31 : HAL.UInt30 := 16#1#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_INI2_FN_MOD_Register use record READ_ISS_OVERRIDE at 0 range 0 .. 0; WRITE_ISS_OVERRIDE at 0 range 1 .. 1; Reserved_2_31 at 0 range 2 .. 31; end record; -- AXI interconnect - INI x functionality modification 2 register type AXI_INI3_FN_MOD2_Register is record -- Disables alteration of transactions by the up-sizer unless required -- by the protocol BYPASS_MERGE : Boolean := False; -- unspecified Reserved_1_31 : HAL.UInt31 := 16#2#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_INI3_FN_MOD2_Register use record BYPASS_MERGE at 0 range 0 .. 0; Reserved_1_31 at 0 range 1 .. 31; end record; -- AXI interconnect - INI x AHB functionality modification register type AXI_INI3_FN_MOD_AHB_Register is record -- Converts all AHB-Lite write transactions to a series of single beat -- AXI RD_INC_OVERRIDE : Boolean := False; -- Converts all AHB-Lite read transactions to a series of single beat -- AXI WR_INC_OVERRIDE : Boolean := False; -- unspecified Reserved_2_31 : HAL.UInt30 := 16#1#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_INI3_FN_MOD_AHB_Register use record RD_INC_OVERRIDE at 0 range 0 .. 0; WR_INC_OVERRIDE at 0 range 1 .. 1; Reserved_2_31 at 0 range 2 .. 31; end record; subtype AXI_INI3_READ_QOS_AR_QOS_Field is HAL.UInt4; -- AXI interconnect - INI x read QoS register type AXI_INI3_READ_QOS_Register is record -- Read channel QoS setting AR_QOS : AXI_INI3_READ_QOS_AR_QOS_Field := 16#4#; -- unspecified Reserved_4_31 : HAL.UInt28 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_INI3_READ_QOS_Register use record AR_QOS at 0 range 0 .. 3; Reserved_4_31 at 0 range 4 .. 31; end record; subtype AXI_INI3_WRITE_QOS_AW_QOS_Field is HAL.UInt4; -- AXI interconnect - INI x write QoS register type AXI_INI3_WRITE_QOS_Register is record -- Write channel QoS setting AW_QOS : AXI_INI3_WRITE_QOS_AW_QOS_Field := 16#4#; -- unspecified Reserved_4_31 : HAL.UInt28 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_INI3_WRITE_QOS_Register use record AW_QOS at 0 range 0 .. 3; Reserved_4_31 at 0 range 4 .. 31; end record; -- AXI interconnect - INI x issuing functionality modification register type AXI_INI3_FN_MOD_Register is record -- Override ASIB read issuing capability READ_ISS_OVERRIDE : Boolean := False; -- Override ASIB write issuing capability WRITE_ISS_OVERRIDE : Boolean := False; -- unspecified Reserved_2_31 : HAL.UInt30 := 16#1#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_INI3_FN_MOD_Register use record READ_ISS_OVERRIDE at 0 range 0 .. 0; WRITE_ISS_OVERRIDE at 0 range 1 .. 1; Reserved_2_31 at 0 range 2 .. 31; end record; subtype AXI_INI4_READ_QOS_AR_QOS_Field is HAL.UInt4; -- AXI interconnect - INI x read QoS register type AXI_INI4_READ_QOS_Register is record -- Read channel QoS setting AR_QOS : AXI_INI4_READ_QOS_AR_QOS_Field := 16#4#; -- unspecified Reserved_4_31 : HAL.UInt28 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_INI4_READ_QOS_Register use record AR_QOS at 0 range 0 .. 3; Reserved_4_31 at 0 range 4 .. 31; end record; subtype AXI_INI4_WRITE_QOS_AW_QOS_Field is HAL.UInt4; -- AXI interconnect - INI x write QoS register type AXI_INI4_WRITE_QOS_Register is record -- Write channel QoS setting AW_QOS : AXI_INI4_WRITE_QOS_AW_QOS_Field := 16#4#; -- unspecified Reserved_4_31 : HAL.UInt28 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_INI4_WRITE_QOS_Register use record AW_QOS at 0 range 0 .. 3; Reserved_4_31 at 0 range 4 .. 31; end record; -- AXI interconnect - INI x issuing functionality modification register type AXI_INI4_FN_MOD_Register is record -- Override ASIB read issuing capability READ_ISS_OVERRIDE : Boolean := False; -- Override ASIB write issuing capability WRITE_ISS_OVERRIDE : Boolean := False; -- unspecified Reserved_2_31 : HAL.UInt30 := 16#1#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_INI4_FN_MOD_Register use record READ_ISS_OVERRIDE at 0 range 0 .. 0; WRITE_ISS_OVERRIDE at 0 range 1 .. 1; Reserved_2_31 at 0 range 2 .. 31; end record; subtype AXI_INI5_READ_QOS_AR_QOS_Field is HAL.UInt4; -- AXI interconnect - INI x read QoS register type AXI_INI5_READ_QOS_Register is record -- Read channel QoS setting AR_QOS : AXI_INI5_READ_QOS_AR_QOS_Field := 16#4#; -- unspecified Reserved_4_31 : HAL.UInt28 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_INI5_READ_QOS_Register use record AR_QOS at 0 range 0 .. 3; Reserved_4_31 at 0 range 4 .. 31; end record; subtype AXI_INI5_WRITE_QOS_AW_QOS_Field is HAL.UInt4; -- AXI interconnect - INI x write QoS register type AXI_INI5_WRITE_QOS_Register is record -- Write channel QoS setting AW_QOS : AXI_INI5_WRITE_QOS_AW_QOS_Field := 16#4#; -- unspecified Reserved_4_31 : HAL.UInt28 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_INI5_WRITE_QOS_Register use record AW_QOS at 0 range 0 .. 3; Reserved_4_31 at 0 range 4 .. 31; end record; -- AXI interconnect - INI x issuing functionality modification register type AXI_INI5_FN_MOD_Register is record -- Override ASIB read issuing capability READ_ISS_OVERRIDE : Boolean := False; -- Override ASIB write issuing capability WRITE_ISS_OVERRIDE : Boolean := False; -- unspecified Reserved_2_31 : HAL.UInt30 := 16#1#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_INI5_FN_MOD_Register use record READ_ISS_OVERRIDE at 0 range 0 .. 0; WRITE_ISS_OVERRIDE at 0 range 1 .. 1; Reserved_2_31 at 0 range 2 .. 31; end record; subtype AXI_INI6_READ_QOS_AR_QOS_Field is HAL.UInt4; -- AXI interconnect - INI x read QoS register type AXI_INI6_READ_QOS_Register is record -- Read channel QoS setting AR_QOS : AXI_INI6_READ_QOS_AR_QOS_Field := 16#4#; -- unspecified Reserved_4_31 : HAL.UInt28 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_INI6_READ_QOS_Register use record AR_QOS at 0 range 0 .. 3; Reserved_4_31 at 0 range 4 .. 31; end record; subtype AXI_INI6_WRITE_QOS_AW_QOS_Field is HAL.UInt4; -- AXI interconnect - INI x write QoS register type AXI_INI6_WRITE_QOS_Register is record -- Write channel QoS setting AW_QOS : AXI_INI6_WRITE_QOS_AW_QOS_Field := 16#4#; -- unspecified Reserved_4_31 : HAL.UInt28 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_INI6_WRITE_QOS_Register use record AW_QOS at 0 range 0 .. 3; Reserved_4_31 at 0 range 4 .. 31; end record; -- AXI interconnect - INI x issuing functionality modification register type AXI_INI6_FN_MOD_Register is record -- Override ASIB read issuing capability READ_ISS_OVERRIDE : Boolean := False; -- Override ASIB write issuing capability WRITE_ISS_OVERRIDE : Boolean := False; -- unspecified Reserved_2_31 : HAL.UInt30 := 16#1#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AXI_INI6_FN_MOD_Register use record READ_ISS_OVERRIDE at 0 range 0 .. 0; WRITE_ISS_OVERRIDE at 0 range 1 .. 1; Reserved_2_31 at 0 range 2 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- AXI interconnect registers type AXI_Peripheral is record -- AXI interconnect - peripheral ID4 register AXI_PERIPH_ID_4 : aliased AXI_PERIPH_ID_4_Register; -- AXI interconnect - peripheral ID0 register AXI_PERIPH_ID_0 : aliased AXI_PERIPH_ID_0_Register; -- AXI interconnect - peripheral ID1 register AXI_PERIPH_ID_1 : aliased AXI_PERIPH_ID_1_Register; -- AXI interconnect - peripheral ID2 register AXI_PERIPH_ID_2 : aliased AXI_PERIPH_ID_2_Register; -- AXI interconnect - peripheral ID3 register AXI_PERIPH_ID_3 : aliased AXI_PERIPH_ID_3_Register; -- AXI interconnect - component ID0 register AXI_COMP_ID_0 : aliased AXI_COMP_ID_0_Register; -- AXI interconnect - component ID1 register AXI_COMP_ID_1 : aliased AXI_COMP_ID_1_Register; -- AXI interconnect - component ID2 register AXI_COMP_ID_2 : aliased AXI_COMP_ID_2_Register; -- AXI interconnect - component ID3 register AXI_COMP_ID_3 : aliased AXI_COMP_ID_3_Register; -- AXI interconnect - TARG x bus matrix issuing functionality register AXI_TARG1_FN_MOD_ISS_BM : aliased AXI_TARG1_FN_MOD_ISS_BM_Register; -- AXI interconnect - TARG x bus matrix functionality 2 register AXI_TARG1_FN_MOD2 : aliased AXI_TARG1_FN_MOD2_Register; -- AXI interconnect - TARG x long burst functionality modification AXI_TARG1_FN_MOD_LB : aliased AXI_TARG1_FN_MOD_LB_Register; -- AXI interconnect - TARG x long burst functionality modification AXI_TARG1_FN_MOD : aliased AXI_TARG1_FN_MOD_Register; -- AXI interconnect - TARG x bus matrix issuing functionality register AXI_TARG2_FN_MOD_ISS_BM : aliased AXI_TARG2_FN_MOD_ISS_BM_Register; -- AXI interconnect - TARG x bus matrix functionality 2 register AXI_TARG2_FN_MOD2 : aliased AXI_TARG2_FN_MOD2_Register; -- AXI interconnect - TARG x long burst functionality modification AXI_TARG2_FN_MOD_LB : aliased AXI_TARG2_FN_MOD_LB_Register; -- AXI interconnect - TARG x long burst functionality modification AXI_TARG2_FN_MOD : aliased AXI_TARG2_FN_MOD_Register; -- AXI interconnect - TARG x bus matrix issuing functionality register AXI_TARG3_FN_MOD_ISS_BM : aliased AXI_TARG3_FN_MOD_ISS_BM_Register; -- AXI interconnect - TARG x bus matrix issuing functionality register AXI_TARG4_FN_MOD_ISS_BM : aliased AXI_TARG4_FN_MOD_ISS_BM_Register; -- AXI interconnect - TARG x bus matrix issuing functionality register AXI_TARG5_FN_MOD_ISS_BM : aliased AXI_TARG5_FN_MOD_ISS_BM_Register; -- AXI interconnect - TARG x bus matrix issuing functionality register AXI_TARG6_FN_MOD_ISS_BM : aliased AXI_TARG6_FN_MOD_ISS_BM_Register; -- AXI interconnect - TARG x bus matrix issuing functionality register AXI_TARG7_FN_MOD_ISS_BM : aliased AXI_TARG7_FN_MOD_ISS_BM_Register; -- AXI interconnect - TARG x bus matrix functionality 2 register AXI_TARG7_FN_MOD2 : aliased AXI_TARG7_FN_MOD2_Register; -- AXI interconnect - TARG x long burst functionality modification AXI_TARG7_FN_MOD : aliased AXI_TARG7_FN_MOD_Register; -- AXI interconnect - INI x functionality modification 2 register AXI_INI1_FN_MOD2 : aliased AXI_INI1_FN_MOD2_Register; -- AXI interconnect - INI x AHB functionality modification register AXI_INI1_FN_MOD_AHB : aliased AXI_INI1_FN_MOD_AHB_Register; -- AXI interconnect - INI x read QoS register AXI_INI1_READ_QOS : aliased AXI_INI1_READ_QOS_Register; -- AXI interconnect - INI x write QoS register AXI_INI1_WRITE_QOS : aliased AXI_INI1_WRITE_QOS_Register; -- AXI interconnect - INI x issuing functionality modification register AXI_INI1_FN_MOD : aliased AXI_INI1_FN_MOD_Register; -- AXI interconnect - INI x read QoS register AXI_INI2_READ_QOS : aliased AXI_INI2_READ_QOS_Register; -- AXI interconnect - INI x write QoS register AXI_INI2_WRITE_QOS : aliased AXI_INI2_WRITE_QOS_Register; -- AXI interconnect - INI x issuing functionality modification register AXI_INI2_FN_MOD : aliased AXI_INI2_FN_MOD_Register; -- AXI interconnect - INI x functionality modification 2 register AXI_INI3_FN_MOD2 : aliased AXI_INI3_FN_MOD2_Register; -- AXI interconnect - INI x AHB functionality modification register AXI_INI3_FN_MOD_AHB : aliased AXI_INI3_FN_MOD_AHB_Register; -- AXI interconnect - INI x read QoS register AXI_INI3_READ_QOS : aliased AXI_INI3_READ_QOS_Register; -- AXI interconnect - INI x write QoS register AXI_INI3_WRITE_QOS : aliased AXI_INI3_WRITE_QOS_Register; -- AXI interconnect - INI x issuing functionality modification register AXI_INI3_FN_MOD : aliased AXI_INI3_FN_MOD_Register; -- AXI interconnect - INI x read QoS register AXI_INI4_READ_QOS : aliased AXI_INI4_READ_QOS_Register; -- AXI interconnect - INI x write QoS register AXI_INI4_WRITE_QOS : aliased AXI_INI4_WRITE_QOS_Register; -- AXI interconnect - INI x issuing functionality modification register AXI_INI4_FN_MOD : aliased AXI_INI4_FN_MOD_Register; -- AXI interconnect - INI x read QoS register AXI_INI5_READ_QOS : aliased AXI_INI5_READ_QOS_Register; -- AXI interconnect - INI x write QoS register AXI_INI5_WRITE_QOS : aliased AXI_INI5_WRITE_QOS_Register; -- AXI interconnect - INI x issuing functionality modification register AXI_INI5_FN_MOD : aliased AXI_INI5_FN_MOD_Register; -- AXI interconnect - INI x read QoS register AXI_INI6_READ_QOS : aliased AXI_INI6_READ_QOS_Register; -- AXI interconnect - INI x write QoS register AXI_INI6_WRITE_QOS : aliased AXI_INI6_WRITE_QOS_Register; -- AXI interconnect - INI x issuing functionality modification register AXI_INI6_FN_MOD : aliased AXI_INI6_FN_MOD_Register; end record with Volatile; for AXI_Peripheral use record AXI_PERIPH_ID_4 at 16#1FD0# range 0 .. 31; AXI_PERIPH_ID_0 at 16#1FE0# range 0 .. 31; AXI_PERIPH_ID_1 at 16#1FE4# range 0 .. 31; AXI_PERIPH_ID_2 at 16#1FE8# range 0 .. 31; AXI_PERIPH_ID_3 at 16#1FEC# range 0 .. 31; AXI_COMP_ID_0 at 16#1FF0# range 0 .. 31; AXI_COMP_ID_1 at 16#1FF4# range 0 .. 31; AXI_COMP_ID_2 at 16#1FF8# range 0 .. 31; AXI_COMP_ID_3 at 16#1FFC# range 0 .. 31; AXI_TARG1_FN_MOD_ISS_BM at 16#2008# range 0 .. 31; AXI_TARG1_FN_MOD2 at 16#2024# range 0 .. 31; AXI_TARG1_FN_MOD_LB at 16#202C# range 0 .. 31; AXI_TARG1_FN_MOD at 16#2108# range 0 .. 31; AXI_TARG2_FN_MOD_ISS_BM at 16#3008# range 0 .. 31; AXI_TARG2_FN_MOD2 at 16#3024# range 0 .. 31; AXI_TARG2_FN_MOD_LB at 16#302C# range 0 .. 31; AXI_TARG2_FN_MOD at 16#3108# range 0 .. 31; AXI_TARG3_FN_MOD_ISS_BM at 16#4008# range 0 .. 31; AXI_TARG4_FN_MOD_ISS_BM at 16#5008# range 0 .. 31; AXI_TARG5_FN_MOD_ISS_BM at 16#6008# range 0 .. 31; AXI_TARG6_FN_MOD_ISS_BM at 16#7008# range 0 .. 31; AXI_TARG7_FN_MOD_ISS_BM at 16#800C# range 0 .. 31; AXI_TARG7_FN_MOD2 at 16#8024# range 0 .. 31; AXI_TARG7_FN_MOD at 16#8108# range 0 .. 31; AXI_INI1_FN_MOD2 at 16#42024# range 0 .. 31; AXI_INI1_FN_MOD_AHB at 16#42028# range 0 .. 31; AXI_INI1_READ_QOS at 16#42100# range 0 .. 31; AXI_INI1_WRITE_QOS at 16#42104# range 0 .. 31; AXI_INI1_FN_MOD at 16#42108# range 0 .. 31; AXI_INI2_READ_QOS at 16#43100# range 0 .. 31; AXI_INI2_WRITE_QOS at 16#43104# range 0 .. 31; AXI_INI2_FN_MOD at 16#43108# range 0 .. 31; AXI_INI3_FN_MOD2 at 16#44024# range 0 .. 31; AXI_INI3_FN_MOD_AHB at 16#44028# range 0 .. 31; AXI_INI3_READ_QOS at 16#44100# range 0 .. 31; AXI_INI3_WRITE_QOS at 16#44104# range 0 .. 31; AXI_INI3_FN_MOD at 16#44108# range 0 .. 31; AXI_INI4_READ_QOS at 16#45100# range 0 .. 31; AXI_INI4_WRITE_QOS at 16#45104# range 0 .. 31; AXI_INI4_FN_MOD at 16#45108# range 0 .. 31; AXI_INI5_READ_QOS at 16#46100# range 0 .. 31; AXI_INI5_WRITE_QOS at 16#46104# range 0 .. 31; AXI_INI5_FN_MOD at 16#46108# range 0 .. 31; AXI_INI6_READ_QOS at 16#47100# range 0 .. 31; AXI_INI6_WRITE_QOS at 16#47104# range 0 .. 31; AXI_INI6_FN_MOD at 16#47108# range 0 .. 31; end record; -- AXI interconnect registers AXI_Periph : aliased AXI_Peripheral with Import, Address => AXI_Base; end STM32_SVD.AXI; ",12037,True,3354.8463879188776,median "------------------------------------------------------------------------------ -- -- -- GNAT LIBRARY COMPONENTS -- -- -- -- G N A T . S P I T B O L . P A T T E R N S -- -- -- -- S p e c -- -- -- -- Copyright (C) 1997-2019, AdaCore -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- . -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- SPITBOL-like pattern construction and matching -- This child package of GNAT.SPITBOL provides a complete implementation -- of the SPITBOL-like pattern construction and matching operations. This -- package is based on Macro-SPITBOL created by Robert Dewar. ------------------------------------------------------------ -- Summary of Pattern Matching Packages in GNAT Hierarchy -- ------------------------------------------------------------ -- There are three related packages that perform pattern matching functions. -- the following is an outline of these packages, to help you determine -- which is best for your needs. -- GNAT.Regexp (files g-regexp.ads/g-regexp.adb) -- This is a simple package providing Unix-style regular expression -- matching with the restriction that it matches entire strings. It -- is particularly useful for file name matching, and in particular -- it provides ""globbing patterns"" that are useful in implementing -- unix or DOS style wild card matching for file names. -- GNAT.Regpat (files g-regpat.ads/g-regpat.adb) -- This is a more complete implementation of Unix-style regular -- expressions, copied from the original V7 style regular expression -- library written in C by Henry Spencer. It is functionally the -- same as this library, and uses the same internal data structures -- stored in a binary compatible manner. -- GNAT.Spitbol.Patterns (files g-spipat.ads/g-spipat.adb) -- This is a completely general patterm matching package based on the -- pattern language of SNOBOL4, as implemented in SPITBOL. The pattern -- language is modeled on context free grammars, with context sensitive -- extensions that provide full (type 0) computational capabilities. with Ada.Strings.Maps; use Ada.Strings.Maps; with Ada.Text_IO; use Ada.Text_IO; package GNAT.Spitbol.Patterns is pragma Elaborate_Body; ------------------------------- -- Pattern Matching Tutorial -- ------------------------------- -- A pattern matching operation (a call to one of the Match subprograms) -- takes a subject string and a pattern, and optionally a replacement -- string. The replacement string option is only allowed if the subject -- is a variable. -- The pattern is matched against the subject string, and either the -- match fails, or it succeeds matching a contiguous substring. If a -- replacement string is specified, then the subject string is modified -- by replacing the matched substring with the given replacement. -- Concatenation and Alternation -- ============================= -- A pattern consists of a series of pattern elements. The pattern is -- built up using either the concatenation operator: -- A & B -- which means match A followed immediately by matching B, or the -- alternation operator: -- A or B -- which means first attempt to match A, and then if that does not -- succeed, match B. -- There is full backtracking, which means that if a given pattern -- element fails to match, then previous alternatives are matched. -- For example if we have the pattern: -- (A or B) & (C or D) & (E or F) -- First we attempt to match A, if that succeeds, then we go on to try -- to match C, and if that succeeds, we go on to try to match E. If E -- fails, then we try F. If F fails, then we go back and try matching -- D instead of C. Let's make this explicit using a specific example, -- and introducing the simplest kind of pattern element, which is a -- literal string. The meaning of this pattern element is simply to -- match the characters that correspond to the string characters. Now -- let's rewrite the above pattern form with specific string literals -- as the pattern elements: -- (""ABC"" or ""AB"") & (""DEF"" or ""CDE"") & (""GH"" or ""IJ"") -- The following strings will be attempted in sequence: -- ABC . DEF . GH -- ABC . DEF . IJ -- ABC . CDE . GH -- ABC . CDE . IJ -- AB . DEF . GH -- AB . DEF . IJ -- AB . CDE . GH -- AB . CDE . IJ -- Here we use the dot simply to separate the pieces of the string -- matched by the three separate elements. -- Moving the Start Point -- ====================== -- A pattern is not required to match starting at the first character -- of the string, and is not required to match to the end of the string. -- The first attempt does indeed attempt to match starting at the first -- character of the string, trying all the possible alternatives. But -- if all alternatives fail, then the starting point of the match is -- moved one character, and all possible alternatives are attempted at -- the new anchor point. -- The entire match fails only when every possible starting point has -- been attempted. As an example, suppose that we had the subject -- string -- ""ABABCDEIJKL"" -- matched using the pattern in the previous example: -- (""ABC"" or ""AB"") & (""DEF"" or ""CDE"") & (""GH"" or ""IJ"") -- would succeed, after two anchor point moves: -- ""ABABCDEIJKL"" -- ^^^^^^^ -- matched -- section -- This mode of pattern matching is called the unanchored mode. It is -- also possible to put the pattern matcher into anchored mode by -- setting the global variable Anchored_Mode to True. This will cause -- all subsequent matches to be performed in anchored mode, where the -- match is required to start at the first character. -- We will also see later how the effect of an anchored match can be -- obtained for a single specified anchor point if this is desired. -- Other Pattern Elements -- ====================== -- In addition to strings (or single characters), there are many special -- pattern elements that correspond to special predefined alternations: -- Arb Matches any string. First it matches the null string, and -- then on a subsequent failure, matches one character, and -- then two characters, and so on. It only fails if the -- entire remaining string is matched. -- Bal Matches a non-empty string that is parentheses balanced -- with respect to ordinary () characters. Examples of -- balanced strings are ""ABC"", ""A((B)C)"", and ""A(B)C(D)E"". -- Bal matches the shortest possible balanced string on the -- first attempt, and if there is a subsequent failure, -- attempts to extend the string. -- Cancel Immediately aborts the entire pattern match, signalling -- failure. This is a specialized pattern element, which is -- useful in conjunction with some of the special pattern -- elements that have side effects. -- Fail The null alternation. Matches no possible strings, so it -- always signals failure. This is a specialized pattern -- element, which is useful in conjunction with some of the -- special pattern elements that have side effects. -- Fence Matches the null string at first, and then if a failure -- causes alternatives to be sought, aborts the match (like -- a Cancel). Note that using Fence at the start of a pattern -- has the same effect as matching in anchored mode. -- Rest Matches from the current point to the last character in -- the string. This is a specialized pattern element, which -- is useful in conjunction with some of the special pattern -- elements that have side effects. -- Succeed Repeatedly matches the null string (it is equivalent to -- the alternation ("""" or """" or """" ....). This is a special -- pattern element, which is useful in conjunction with some -- of the special pattern elements that have side effects. -- Pattern Construction Functions -- ============================== -- The following functions construct additional pattern elements -- Any(S) Where S is a string, matches a single character that is -- any one of the characters in S. Fails if the current -- character is not one of the given set of characters. -- Arbno(P) Where P is any pattern, matches any number of instances -- of the pattern, starting with zero occurrences. It is -- thus equivalent to ("""" or (P & ("""" or (P & ("""" ....)))). -- The pattern P may contain any number of pattern elements -- including the use of alternation and concatenation. -- Break(S) Where S is a string, matches a string of zero or more -- characters up to but not including a break character -- that is one of the characters given in the string S. -- Can match the null string, but cannot match the last -- character in the string, since a break character is -- required to be present. -- BreakX(S) Where S is a string, behaves exactly like Break(S) when -- it first matches, but if a string is successfully matched, -- then a subsequent failure causes an attempt to extend the -- matched string. -- Fence(P) Where P is a pattern, attempts to match the pattern P -- including trying all possible alternatives of P. If none -- of these alternatives succeeds, then the Fence pattern -- fails. If one alternative succeeds, then the pattern -- match proceeds, but on a subsequent failure, no attempt -- is made to search for alternative matches of P. The -- pattern P may contain any number of pattern elements -- including the use of alternation and concatenation. -- Len(N) Where N is a natural number, matches the given number of -- characters. For example, Len(10) matches any string that -- is exactly ten characters long. -- NotAny(S) Where S is a string, matches a single character that is -- not one of the characters of S. Fails if the current -- character is one of the given set of characters. -- NSpan(S) Where S is a string, matches a string of zero or more -- characters that is among the characters given in the -- string. Always matches the longest possible such string. -- Always succeeds, since it can match the null string. -- Pos(N) Where N is a natural number, matches the null string -- if exactly N characters have been matched so far, and -- otherwise fails. -- Rpos(N) Where N is a natural number, matches the null string -- if exactly N characters remain to be matched, and -- otherwise fails. -- Rtab(N) Where N is a natural number, matches characters from -- the current position until exactly N characters remain -- to be matched in the string. Fails if fewer than N -- unmatched characters remain in the string. -- Tab(N) Where N is a natural number, matches characters from -- the current position until exactly N characters have -- been matched in all. Fails if more than N characters -- have already been matched. -- Span(S) Where S is a string, matches a string of one or more -- characters that is among the characters given in the -- string. Always matches the longest possible such string. -- Fails if the current character is not one of the given -- set of characters. -- Recursive Pattern Matching -- ========================== -- The plus operator (+P) where P is a pattern variable, creates -- a recursive pattern that will, at pattern matching time, follow -- the pointer to obtain the referenced pattern, and then match this -- pattern. This may be used to construct recursive patterns. Consider -- for example: -- P := (""A"" or (""B"" & (+P))) -- On the first attempt, this pattern attempts to match the string ""A"". -- If this fails, then the alternative matches a ""B"", followed by an -- attempt to match P again. This second attempt first attempts to -- match ""A"", and so on. The result is a pattern that will match a -- string of B's followed by a single A. -- This particular example could simply be written as NSpan('B') & 'A', -- but the use of recursive patterns in the general case can construct -- complex patterns which could not otherwise be built. -- Pattern Assignment Operations -- ============================= -- In addition to the overall result of a pattern match, which indicates -- success or failure, it is often useful to be able to keep track of -- the pieces of the subject string that are matched by individual -- pattern elements, or subsections of the pattern. -- The pattern assignment operators allow this capability. The first -- form is the immediate assignment: -- P * S -- Here P is an arbitrary pattern, and S is a variable of type VString -- that will be set to the substring matched by P. This assignment -- happens during pattern matching, so if P matches more than once, -- then the assignment happens more than once. -- The deferred assignment operation: -- P ** S -- avoids these multiple assignments by deferring the assignment to the -- end of the match. If the entire match is successful, and if the -- pattern P was part of the successful match, then at the end of the -- matching operation the assignment to S of the string matching P is -- performed. -- The cursor assignment operation: -- Setcur(N'Access) -- assigns the current cursor position to the natural variable N. The -- cursor position is defined as the count of characters that have been -- matched so far (including any start point moves). -- Finally the operations * and ** may be used with values of type -- Text_IO.File_Access. The effect is to do a Put_Line operation of -- the matched substring. These are particularly useful in debugging -- pattern matches. -- Deferred Matching -- ================= -- The pattern construction functions (such as Len and Any) all permit -- the use of pointers to natural or string values, or functions that -- return natural or string values. These forms cause the actual value -- to be obtained at pattern matching time. This allows interesting -- possibilities for constructing dynamic patterns as illustrated in -- the examples section. -- In addition the (+S) operator may be used where S is a pointer to -- string or function returning string, with a similar deferred effect. -- A special use of deferred matching is the construction of predicate -- functions. The element (+P) where P is an access to a function that -- returns a Boolean value, causes the function to be called at the -- time the element is matched. If the function returns True, then the -- null string is matched, if the function returns False, then failure -- is signalled and previous alternatives are sought. -- Deferred Replacement -- ==================== -- The simple model given for pattern replacement (where the matched -- substring is replaced by the string given as the third argument to -- Match) works fine in simple cases, but this approach does not work -- in the case where the expression used as the replacement string is -- dependent on values set by the match. -- For example, suppose we want to find an instance of a parenthesized -- character, and replace the parentheses with square brackets. At first -- glance it would seem that: -- Match (Subject, '(' & Len (1) * Char & ')', '[' & Char & ']'); -- would do the trick, but that does not work, because the third -- argument to Match gets evaluated too early, before the call to -- Match, and before the pattern match has had a chance to set Char. -- To solve this problem we provide the deferred replacement capability. -- With this approach, which of course is only needed if the pattern -- involved has side effects, is to do the match in two stages. The -- call to Match sets a pattern result in a variable of the private -- type Match_Result, and then a subsequent Replace operation uses -- this Match_Result object to perform the required replacement. -- Using this approach, we can now write the above operation properly -- in a manner that will work: -- M : Match_Result; -- ... -- Match (Subject, '(' & Len (1) * Char & ')', M); -- Replace (M, '[' & Char & ']'); -- As with other Match cases, there is a function and procedure form -- of this match call. A call to Replace after a failed match has no -- effect. Note that Subject should not be modified between the calls. -- Examples of Pattern Matching -- ============================ -- First a simple example of the use of pattern replacement to remove -- a line number from the start of a string. We assume that the line -- number has the form of a string of decimal digits followed by a -- period, followed by one or more spaces. -- Digs : constant Pattern := Span(""0123456789""); -- Lnum : constant Pattern := Pos(0) & Digs & '.' & Span(' '); -- Now to use this pattern we simply do a match with a replacement: -- Match (Line, Lnum, """"); -- which replaces the line number by the null string. Note that it is -- also possible to use an Ada.Strings.Maps.Character_Set value as an -- argument to Span and similar functions, and in particular all the -- useful constants 'in Ada.Strings.Maps.Constants are available. This -- means that we could define Digs as: -- Digs : constant Pattern := Span(Decimal_Digit_Set); -- The style we use here, of defining constant patterns and then using -- them is typical. It is possible to build up patterns dynamically, -- but it is usually more efficient to build them in pieces in advance -- using constant declarations. Note in particular that although it is -- possible to construct a pattern directly as an argument for the -- Match routine, it is much more efficient to preconstruct the pattern -- as we did in this example. -- Now let's look at the use of pattern assignment to break a -- string into sections. Suppose that the input string has two -- unsigned decimal integers, separated by spaces or a comma, -- with spaces allowed anywhere. Then we can isolate the two -- numbers with the following pattern: -- Num1, Num2 : aliased VString; -- B : constant Pattern := NSpan(' '); -- N : constant Pattern := Span(""0123456789""); -- T : constant Pattern := -- NSpan(' ') & N * Num1 & Span("" ,"") & N * Num2; -- The match operation Match ("" 124, 257 "", T) would assign the -- string 124 to Num1 and the string 257 to Num2. -- Now let's see how more complex elements can be built from the -- set of primitive elements. The following pattern matches strings -- that have the syntax of Ada 95 based literals: -- Digs : constant Pattern := Span(Decimal_Digit_Set); -- UDigs : constant Pattern := Digs & Arbno('_' & Digs); -- Edig : constant Pattern := Span(Hexadecimal_Digit_Set); -- UEdig : constant Pattern := Edig & Arbno('_' & Edig); -- Bnum : constant Pattern := Udigs & '#' & UEdig & '#'; -- A match against Bnum will now match the desired strings, e.g. -- it will match 16#123_abc#, but not a#b#. However, this pattern -- is not quite complete, since it does not allow colons to replace -- the pound signs. The following is more complete: -- Bchar : constant Pattern := Any(""#:""); -- Bnum : constant Pattern := Udigs & Bchar & UEdig & Bchar; -- but that is still not quite right, since it allows # and : to be -- mixed, and they are supposed to be used consistently. We solve -- this by using a deferred match. -- Temp : aliased VString; -- Bnum : constant Pattern := -- Udigs & Bchar * Temp & UEdig & (+Temp) -- Here the first instance of the base character is stored in Temp, and -- then later in the pattern we rematch the value that was assigned. -- For an example of a recursive pattern, let's define a pattern -- that is like the built in Bal, but the string matched is balanced -- with respect to square brackets or curly brackets. -- The language for such strings might be defined in extended BNF as -- ELEMENT ::= -- | '[' BALANCED_STRING ']' -- | '{' BALANCED_STRING '}' -- BALANCED_STRING ::= ELEMENT {ELEMENT} -- Here we use {} to indicate zero or more occurrences of a term, as -- is common practice in extended BNF. Now we can translate the above -- BNF into recursive patterns as follows: -- Element, Balanced_String : aliased Pattern; -- . -- . -- . -- Element := NotAny (""[]{}"") -- or -- ('[' & (+Balanced_String) & ']') -- or -- ('{' & (+Balanced_String) & '}'); -- Balanced_String := Element & Arbno (Element); -- Note the important use of + here to refer to a pattern not yet -- defined. Note also that we use assignments precisely because we -- cannot refer to as yet undeclared variables in initializations. -- Now that this pattern is constructed, we can use it as though it -- were a new primitive pattern element, and for example, the match: -- Match (""xy[ab{cd}]"", Balanced_String * Current_Output & Fail); -- will generate the output: -- x -- xy -- xy[ab{cd}] -- y -- y[ab{cd}] -- [ab{cd}] -- a -- ab -- ab{cd} -- b -- b{cd} -- {cd} -- c -- cd -- d -- Note that the function of the fail here is simply to force the -- pattern Balanced_String to match all possible alternatives. Studying -- the operation of this pattern in detail is highly instructive. -- Finally we give a rather elaborate example of the use of deferred -- matching. The following declarations build up a pattern which will -- find the longest string of decimal digits in the subject string. -- Max, Cur : VString; -- Loc : Natural; -- function GtS return Boolean is -- begin -- return Length (Cur) > Length (Max); -- end GtS; -- Digit : constant Character_Set := Decimal_Digit_Set; -- Digs : constant Pattern := Span(Digit); -- Find : constant Pattern := -- """" * Max & Fence & -- initialize Max to null -- BreakX (Digit) & -- scan looking for digits -- ((Span(Digit) * Cur & -- assign next string to Cur -- (+GtS'Unrestricted_Access) & -- check size(Cur) > Size(Max) -- Setcur(Loc'Access)) -- if so, save location -- * Max) & -- and assign to Max -- Fail; -- seek all alternatives -- As we see from the comments here, complex patterns like this take -- on aspects of sequential programs. In fact they are sequential -- programs with general backtracking. In this pattern, we first use -- a pattern assignment that matches null and assigns it to Max, so -- that it is initialized for the new match. Now BreakX scans to the -- next digit. Arb would do here, but BreakX will be more efficient. -- Once we have found a digit, we scan out the longest string of -- digits with Span, and assign it to Cur. The deferred call to GtS -- tests if the string we assigned to Cur is the longest so far. If -- not, then failure is signalled, and we seek alternatives (this -- means that BreakX will extend and look for the next digit string). -- If the call to GtS succeeds then the matched string is assigned -- as the largest string so far into Max and its location is saved -- in Loc. Finally Fail forces the match to fail and seek alternatives, -- so that the entire string is searched. -- If the pattern Find is matched against a string, the variable Max -- at the end of the pattern will have the longest string of digits, -- and Loc will be the starting character location of the string. For -- example, Match(""ab123cd4657ef23"", Find) will assign ""4657"" to Max -- and 11 to Loc (indicating that the string ends with the eleventh -- character of the string). -- Note: the use of Unrestricted_Access to reference GtS will not -- be needed if GtS is defined at the outer level, but definitely -- will be necessary if GtS is a nested function (in which case of -- course the scope of the pattern Find will be restricted to this -- nested scope, and this cannot be checked, i.e. use of the pattern -- outside this scope is erroneous). Generally it is a good idea to -- define patterns and the functions they call at the outer level -- where possible, to avoid such problems. -- Correspondence with Pattern Matching in SPITBOL -- =============================================== -- Generally the Ada syntax and names correspond closely to SPITBOL -- syntax for pattern matching construction. -- The basic pattern construction operators are renamed as follows: -- Spitbol Ada -- (space) & -- | or -- $ * -- . ** -- The Ada operators were chosen so that the relative precedences of -- these operators corresponds to that of the Spitbol operators, but -- as always, the use of parentheses is advisable to clarify. -- The pattern construction operators all have similar names except for -- Spitbol Ada -- Abort Cancel -- Rem Rest -- where we have clashes with Ada reserved names -- Ada requires the use of 'Access to refer to functions used in the -- pattern match, and often the use of 'Unrestricted_Access may be -- necessary to get around the scope restrictions if the functions -- are not declared at the outer level. -- The actual pattern matching syntax is modified in Ada as follows: -- Spitbol Ada -- X Y Match (X, Y); -- X Y = Z Match (X, Y, Z); -- and pattern failure is indicated by returning a Boolean result from -- the Match function (True for success, False for failure). ----------------------- -- Type Declarations -- ----------------------- type Pattern is private; -- Type representing a pattern. This package provides a complete set of -- operations for constructing patterns that can be used in the pattern -- matching operations provided. type Boolean_Func is access function return Boolean; -- General Boolean function type. When this type is used as a formal -- parameter type in this package, it indicates a deferred predicate -- pattern. The function will be called when the pattern element is -- matched and failure signalled if False is returned. type Natural_Func is access function return Natural; -- General Natural function type. When this type is used as a formal -- parameter type in this package, it indicates a deferred pattern. -- The function will be called when the pattern element is matched -- to obtain the currently referenced Natural value. type VString_Func is access function return VString; -- General VString function type. When this type is used as a formal -- parameter type in this package, it indicates a deferred pattern. -- The function will be called when the pattern element is matched -- to obtain the currently referenced string value. subtype PString is String; -- This subtype is used in the remainder of the package to indicate a -- formal parameter that is converted to its corresponding pattern, -- i.e. a pattern that matches the characters of the string. subtype PChar is Character; -- Similarly, this subtype is used in the remainder of the package to -- indicate a formal parameter that is converted to its corresponding -- pattern, i.e. a pattern that matches this one character. subtype VString_Var is VString; subtype Pattern_Var is Pattern; -- These synonyms are used as formal parameter types to a function where, -- if the language allowed, we would use in out parameters, but we are -- not allowed to have in out parameters for functions. Instead we pass -- actuals which must be variables, and with a bit of trickery in the -- body, manage to interpret them properly as though they were indeed -- in out parameters. pragma Warnings (Off, VString_Var); pragma Warnings (Off, Pattern_Var); -- We turn off warnings for these two types so that when variables are used -- as arguments in this context, warnings about them not being assigned in -- the source program will be suppressed. -------------------------------- -- Basic Pattern Construction -- -------------------------------- function ""&"" (L : Pattern; R : Pattern) return Pattern; function ""&"" (L : PString; R : Pattern) return Pattern; function ""&"" (L : Pattern; R : PString) return Pattern; function ""&"" (L : PChar; R : Pattern) return Pattern; function ""&"" (L : Pattern; R : PChar) return Pattern; -- Pattern concatenation. Matches L followed by R function ""or"" (L : Pattern; R : Pattern) return Pattern; function ""or"" (L : PString; R : Pattern) return Pattern; function ""or"" (L : Pattern; R : PString) return Pattern; function ""or"" (L : PString; R : PString) return Pattern; function ""or"" (L : PChar; R : Pattern) return Pattern; function ""or"" (L : Pattern; R : PChar) return Pattern; function ""or"" (L : PChar; R : PChar) return Pattern; function ""or"" (L : PString; R : PChar) return Pattern; function ""or"" (L : PChar; R : PString) return Pattern; -- Pattern alternation. Creates a pattern that will first try to match -- L and then on a subsequent failure, attempts to match R instead. ---------------------------------- -- Pattern Assignment Functions -- ---------------------------------- function ""*"" (P : Pattern; Var : VString_Var) return Pattern; function ""*"" (P : PString; Var : VString_Var) return Pattern; function ""*"" (P : PChar; Var : VString_Var) return Pattern; -- Matches P, and if the match succeeds, assigns the matched substring -- to the given VString variable Var. This assignment happens as soon as -- the substring is matched, and if the pattern P1 is matched more than -- once during the course of the match, then the assignment will occur -- more than once. function ""**"" (P : Pattern; Var : VString_Var) return Pattern; function ""**"" (P : PString; Var : VString_Var) return Pattern; function ""**"" (P : PChar; Var : VString_Var) return Pattern; -- Like ""*"" above, except that the assignment happens at most once -- after the entire match is completed successfully. If the match -- fails, then no assignment takes place. ---------------------------------- -- Deferred Matching Operations -- ---------------------------------- function ""+"" (Str : VString_Var) return Pattern; -- Here Str must be a VString variable. This function constructs a -- pattern which at pattern matching time will access the current -- value of this variable, and match against these characters. function ""+"" (Str : VString_Func) return Pattern; -- Constructs a pattern which at pattern matching time calls the given -- function, and then matches against the string or character value -- that is returned by the call. function ""+"" (P : Pattern_Var) return Pattern; -- Here P must be a Pattern variable. This function constructs a -- pattern which at pattern matching time will access the current -- value of this variable, and match against the pattern value. function ""+"" (P : Boolean_Func) return Pattern; -- Constructs a predicate pattern function that at pattern matching time -- calls the given function. If True is returned, then the pattern matches. -- If False is returned, then failure is signalled. -------------------------------- -- Pattern Building Functions -- -------------------------------- function Arb return Pattern; -- Constructs a pattern that will match any string. On the first attempt, -- the pattern matches a null string, then on each successive failure, it -- matches one more character, and only fails if matching the entire rest -- of the string. function Arbno (P : Pattern) return Pattern; function Arbno (P : PString) return Pattern; function Arbno (P : PChar) return Pattern; -- Pattern repetition. First matches null, then on a subsequent failure -- attempts to match an additional instance of the given pattern. -- Equivalent to (but more efficient than) P & ("""" or (P & ("""" or ... function Any (Str : String) return Pattern; function Any (Str : VString) return Pattern; function Any (Str : Character) return Pattern; function Any (Str : Character_Set) return Pattern; function Any (Str : not null access VString) return Pattern; function Any (Str : VString_Func) return Pattern; -- Constructs a pattern that matches a single character that is one of -- the characters in the given argument. The pattern fails if the current -- character is not in Str. function Bal return Pattern; -- Constructs a pattern that will match any non-empty string that is -- parentheses balanced with respect to the normal parentheses characters. -- Attempts to extend the string if a subsequent failure occurs. function Break (Str : String) return Pattern; function Break (Str : VString) return Pattern; function Break (Str : Character) return Pattern; function Break (Str : Character_Set) return Pattern; function Break (Str : not null access VString) return Pattern; function Break (Str : VString_Func) return Pattern; -- Constructs a pattern that matches a (possibly null) string which -- is immediately followed by a character in the given argument. This -- character is not part of the matched string. The pattern fails if -- the remaining characters to be matched do not include any of the -- characters in Str. function BreakX (Str : String) return Pattern; function BreakX (Str : VString) return Pattern; function BreakX (Str : Character) return Pattern; function BreakX (Str : Character_Set) return Pattern; function BreakX (Str : not null access VString) return Pattern; function BreakX (Str : VString_Func) return Pattern; -- Like Break, but the pattern attempts to extend on a failure to find -- the next occurrence of a character in Str, and only fails when the -- last such instance causes a failure. function Cancel return Pattern; -- Constructs a pattern that immediately aborts the entire match function Fail return Pattern; -- Constructs a pattern that always fails function Fence return Pattern; -- Constructs a pattern that matches null on the first attempt, and then -- causes the entire match to be aborted if a subsequent failure occurs. function Fence (P : Pattern) return Pattern; -- Constructs a pattern that first matches P. If P fails, then the -- constructed pattern fails. If P succeeds, then the match proceeds, -- but if subsequent failure occurs, alternatives in P are not sought. -- The idea of Fence is that each time the pattern is matched, just -- one attempt is made to match P, without trying alternatives. function Len (Count : Natural) return Pattern; function Len (Count : not null access Natural) return Pattern; function Len (Count : Natural_Func) return Pattern; -- Constructs a pattern that matches exactly the given number of -- characters. The pattern fails if fewer than this number of characters -- remain to be matched in the string. function NotAny (Str : String) return Pattern; function NotAny (Str : VString) return Pattern; function NotAny (Str : Character) return Pattern; function NotAny (Str : Character_Set) return Pattern; function NotAny (Str : not null access VString) return Pattern; function NotAny (Str : VString_Func) return Pattern; -- Constructs a pattern that matches a single character that is not -- one of the characters in the given argument. The pattern Fails if -- the current character is in Str. function NSpan (Str : String) return Pattern; function NSpan (Str : VString) return Pattern; function NSpan (Str : Character) return Pattern; function NSpan (Str : Character_Set) return Pattern; function NSpan (Str : not null access VString) return Pattern; function NSpan (Str : VString_Func) return Pattern; -- Constructs a pattern that matches the longest possible string -- consisting entirely of characters from the given argument. The -- string may be empty, so this pattern always succeeds. function Pos (Count : Natural) return Pattern; function Pos (Count : not null access Natural) return Pattern; function Pos (Count : Natural_Func) return Pattern; -- Constructs a pattern that matches the null string if exactly Count -- characters have already been matched, and otherwise fails. function Rest return Pattern; -- Constructs a pattern that always succeeds, matching the remaining -- unmatched characters in the pattern. function Rpos (Count : Natural) return Pattern; function Rpos (Count : not null access Natural) return Pattern; function Rpos (Count : Natural_Func) return Pattern; -- Constructs a pattern that matches the null string if exactly Count -- characters remain to be matched in the string, and otherwise fails. function Rtab (Count : Natural) return Pattern; function Rtab (Count : not null access Natural) return Pattern; function Rtab (Count : Natural_Func) return Pattern; -- Constructs a pattern that matches from the current location until -- exactly Count characters remain to be matched in the string. The -- pattern fails if fewer than Count characters remain to be matched. function Setcur (Var : not null access Natural) return Pattern; -- Constructs a pattern that matches the null string, and assigns the -- current cursor position in the string. This value is the number of -- characters matched so far. So it is zero at the start of the match. function Span (Str : String) return Pattern; function Span (Str : VString) return Pattern; function Span (Str : Character) return Pattern; function Span (Str : Character_Set) return Pattern; function Span (Str : not null access VString) return Pattern; function Span (Str : VString_Func) return Pattern; -- Constructs a pattern that matches the longest possible string -- consisting entirely of characters from the given argument. The -- string cannot be empty, so the pattern fails if the current -- character is not one of the characters in Str. function Succeed return Pattern; -- Constructs a pattern that succeeds matching null, both on the first -- attempt, and on any rematch attempt, i.e. it is equivalent to an -- infinite alternation of null strings. function Tab (Count : Natural) return Pattern; function Tab (Count : not null access Natural) return Pattern; function Tab (Count : Natural_Func) return Pattern; -- Constructs a pattern that from the current location until Count -- characters have been matched. The pattern fails if more than Count -- characters have already been matched. --------------------------------- -- Pattern Matching Operations -- --------------------------------- -- The Match function performs an actual pattern matching operation. -- The versions with three parameters perform a match without modifying -- the subject string and return a Boolean result indicating if the -- match is successful or not. The Anchor parameter is set to True to -- obtain an anchored match in which the pattern is required to match -- the first character of the string. In an unanchored match, which is -- the default, successive attempts are made to match the given pattern -- at each character of the subject string until a match succeeds, or -- until all possibilities have failed. -- Note that pattern assignment functions in the pattern may generate -- side effects, so these functions are not necessarily pure. Anchored_Mode : Boolean := False; -- This global variable can be set True to cause all subsequent pattern -- matches to operate in anchored mode. In anchored mode, no attempt is -- made to move the anchor point, so that if the match succeeds it must -- succeed starting at the first character. Note that the effect of -- anchored mode may be achieved in individual pattern matches by using -- Fence or Pos(0) at the start of the pattern. Pattern_Stack_Overflow : exception; -- Exception raised if internal pattern matching stack overflows. This -- is typically the result of runaway pattern recursion. If there is a -- genuine case of stack overflow, then either the match must be broken -- down into simpler steps, or the stack limit must be reset. Stack_Size : constant Positive := 2000; -- Size used for internal pattern matching stack. Increase this size if -- complex patterns cause Pattern_Stack_Overflow to be raised. -- Simple match functions. The subject is matched against the pattern. -- Any immediate or deferred assignments or writes are executed, and -- the returned value indicates whether or not the match succeeded. function Match (Subject : VString; Pat : Pattern) return Boolean; function Match (Subject : VString; Pat : PString) return Boolean; function Match (Subject : String; Pat : Pattern) return Boolean; function Match (Subject : String; Pat : PString) return Boolean; -- Replacement functions. The subject is matched against the pattern. -- Any immediate or deferred assignments or writes are executed, and -- the returned value indicates whether or not the match succeeded. -- If the match succeeds, then the matched part of the subject string -- is replaced by the given Replace string. function Match (Subject : VString_Var; Pat : Pattern; Replace : VString) return Boolean; function Match (Subject : VString_Var; Pat : PString; Replace : VString) return Boolean; function Match (Subject : VString_Var; Pat : Pattern; Replace : String) return Boolean; function Match (Subject : VString_Var; Pat : PString; Replace : String) return Boolean; -- Simple match procedures. The subject is matched against the pattern. -- Any immediate or deferred assignments or writes are executed. No -- indication of success or failure is returned. procedure Match (Subject : VString; Pat : Pattern); procedure Match (Subject : VString; Pat : PString); procedure Match (Subject : String; Pat : Pattern); procedure Match (Subject : String; Pat : PString); -- Replacement procedures. The subject is matched against the pattern. -- Any immediate or deferred assignments or writes are executed. No -- indication of success or failure is returned. If the match succeeds, -- then the matched part of the subject string is replaced by the given -- Replace string. procedure Match (Subject : in out VString; Pat : Pattern; Replace : VString); procedure Match (Subject : in out VString; Pat : PString; Replace : VString); procedure Match (Subject : in out VString; Pat : Pattern; Replace : String); procedure Match (Subject : in out VString; Pat : PString; Replace : String); -- Deferred Replacement type Match_Result is private; -- Type used to record result of pattern match subtype Match_Result_Var is Match_Result; -- This synonyms is used as a formal parameter type to a function where, -- if the language allowed, we would use an in out parameter, but we are -- not allowed to have in out parameters for functions. Instead we pass -- actuals which must be variables, and with a bit of trickery in the -- body, manage to interpret them properly as though they were indeed -- in out parameters. function Match (Subject : VString_Var; Pat : Pattern; Result : Match_Result_Var) return Boolean; procedure Match (Subject : in out VString; Pat : Pattern; Result : out Match_Result); procedure Replace (Result : in out Match_Result; Replace : VString); -- Given a previous call to Match which set Result, performs a pattern -- replacement if the match was successful. Has no effect if the match -- failed. This call should immediately follow the Match call. ------------------------ -- Debugging Routines -- ------------------------ -- Debugging pattern matching operations can often be quite complex, -- since there is no obvious way to trace the progress of the match. -- The declarations in this section provide some debugging assistance. Debug_Mode : Boolean := False; -- This global variable can be set True to generate debugging on all -- subsequent calls to Match. The debugging output is a full trace of -- the actions of the pattern matcher, written to Standard_Output. The -- level of this information is intended to be comprehensible at the -- abstract level of this package declaration. However, note that the -- use of this switch often generates large amounts of output. function ""*"" (P : Pattern; Fil : File_Access) return Pattern; function ""*"" (P : PString; Fil : File_Access) return Pattern; function ""*"" (P : PChar; Fil : File_Access) return Pattern; function ""**"" (P : Pattern; Fil : File_Access) return Pattern; function ""**"" (P : PString; Fil : File_Access) return Pattern; function ""**"" (P : PChar; Fil : File_Access) return Pattern; -- These are similar to the corresponding pattern assignment operations -- except that instead of setting the value of a variable, the matched -- substring is written to the appropriate file. This can be useful in -- following the progress of a match without generating the full amount -- of information obtained by setting Debug_Mode to True. Terminal : constant File_Access := Standard_Error; Output : constant File_Access := Standard_Output; -- Two handy synonyms for use with the above pattern write operations -- Finally we have some routines that are useful for determining what -- patterns are in use, particularly if they are constructed dynamically. function Image (P : Pattern) return String; function Image (P : Pattern) return VString; -- This procedures yield strings that corresponds to the syntax needed -- to create the given pattern using the functions in this package. The -- form of this string is such that it could actually be compiled and -- evaluated to yield the required pattern except for references to -- variables and functions, which are output using one of the following -- forms: -- -- access Natural NP(16#...#) -- access Pattern PP(16#...#) -- access VString VP(16#...#) -- -- Natural_Func NF(16#...#) -- VString_Func VF(16#...#) -- -- where 16#...# is the hex representation of the integer address that -- corresponds to the given access value procedure Dump (P : Pattern); -- This procedure writes information about the pattern to Standard_Out. -- The format of this information is keyed to the internal data structures -- used to implement patterns. The information provided by Dump is thus -- more precise than that yielded by Image, but is also a bit more obscure -- (i.e. it cannot be interpreted solely in terms of this spec, you have -- to know something about the data structures). ------------------ -- Private Part -- ------------------ private type PE; -- Pattern element, a pattern is a complex structure of PE's. This type -- is defined and described in the body of this package. type PE_Ptr is access all PE; -- Pattern reference. PE's use PE_Ptr values to reference other PE's type Pattern is new Controlled with record Stk : Natural := 0; -- Maximum number of stack entries required for matching this -- pattern. See description of pattern history stack in body. P : PE_Ptr := null; -- Pointer to initial pattern element for pattern end record; pragma Finalize_Storage_Only (Pattern); procedure Adjust (Object : in out Pattern); -- Adjust routine used to copy pattern objects procedure Finalize (Object : in out Pattern); -- Finalization routine used to release storage allocated for a pattern type VString_Ptr is access all VString; type Match_Result is record Var : VString_Ptr; -- Pointer to subject string. Set to null if match failed Start : Natural := 1; -- Starting index position (1's origin) of matched section of -- subject string. Only valid if Var is non-null. Stop : Natural := 0; -- Ending index position (1's origin) of matched section of -- subject string. Only valid if Var is non-null. end record; pragma Volatile (Match_Result); -- This ensures that the Result parameter is passed by reference, so -- that we can play our games with the bogus Match_Result_Var parameter -- in the function case to treat it as though it were an in out parameter. end GNAT.Spitbol.Patterns; ",12364,False,2346.347692983126,median "------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- R E S T R I C T -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2020, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING3. If not, go to -- -- http://www.gnu.org/licenses for a complete copy of the license. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Atree; use Atree; with Casing; use Casing; with Einfo; use Einfo; with Errout; use Errout; with Debug; use Debug; with Fname; use Fname; with Fname.UF; use Fname.UF; with Lib; use Lib; with Opt; use Opt; with Sinfo; use Sinfo; with Sinput; use Sinput; with Stand; use Stand; with Targparm; use Targparm; with Uname; use Uname; package body Restrict is Global_Restriction_No_Tasking : Boolean := False; -- Set to True when No_Tasking is set in the run-time package System -- or in a configuration pragmas file (for example, gnat.adc). -------------------------------- -- Package Local Declarations -- -------------------------------- Config_Cunit_Boolean_Restrictions : Save_Cunit_Boolean_Restrictions; -- Save compilation unit restrictions set by config pragma files Restricted_Profile_Result : Boolean := False; -- This switch memoizes the result of Restricted_Profile function calls for -- improved efficiency. Valid only if Restricted_Profile_Cached is True. -- Note: if this switch is ever set True, it is never turned off again. Restricted_Profile_Cached : Boolean := False; -- This flag is set to True if the Restricted_Profile_Result contains the -- correct cached result of Restricted_Profile calls. No_Specification_Of_Aspects : array (Aspect_Id) of Source_Ptr := (others => No_Location); -- Entries in this array are set to point to a previously occuring pragma -- that activates a No_Specification_Of_Aspect check. No_Specification_Of_Aspect_Warning : array (Aspect_Id) of Boolean := (others => True); -- An entry in this array is set False in reponse to a previous call to -- Set_No_Speficiation_Of_Aspect for pragmas in the main unit that -- specify Warning as False. Once set False, an entry is never reset. No_Specification_Of_Aspect_Set : Boolean := False; -- Set True if any entry of No_Specifcation_Of_Aspects has been set True. -- Once set True, this is never turned off again. No_Use_Of_Attribute : array (Attribute_Id) of Source_Ptr := (others => No_Location); No_Use_Of_Attribute_Warning : array (Attribute_Id) of Boolean := (others => False); No_Use_Of_Attribute_Set : Boolean := False; -- Indicates that No_Use_Of_Attribute was set at least once No_Use_Of_Pragma : array (Pragma_Id) of Source_Ptr := (others => No_Location); -- Source location of pragma No_Use_Of_Pragma for given pragma, a value -- of System_Location indicates occurrence in system.ads. No_Use_Of_Pragma_Warning : array (Pragma_Id) of Boolean := (others => False); No_Use_Of_Pragma_Set : Boolean := False; -- Indicates that No_Use_Of_Pragma was set at least once ----------------------- -- Local Subprograms -- ----------------------- procedure Restriction_Msg (R : Restriction_Id; N : Node_Id); -- Called if a violation of restriction R at node N is found. This routine -- outputs the appropriate message or messages taking care of warning vs -- real violation, serious vs non-serious, implicit vs explicit, the second -- message giving the profile name if needed, and the location information. function Same_Entity (E1, E2 : Node_Id) return Boolean; -- Returns True iff E1 and E2 represent the same entity. Used for handling -- of No_Use_Of_Entity => fully_qualified_ENTITY restriction case. function Same_Unit (U1, U2 : Node_Id) return Boolean; -- Returns True iff U1 and U2 represent the same library unit. Used for -- handling of No_Dependence => Unit restriction case. function Suppress_Restriction_Message (N : Node_Id) return Boolean; -- N is the node for a possible restriction violation message, but the -- message is to be suppressed if this is an internal file and this file is -- not the main unit. Returns True if message is to be suppressed. ------------------- -- Abort_Allowed -- ------------------- function Abort_Allowed return Boolean is begin if Restrictions.Set (No_Abort_Statements) and then Restrictions.Set (Max_Asynchronous_Select_Nesting) and then Restrictions.Value (Max_Asynchronous_Select_Nesting) = 0 then return False; else return True; end if; end Abort_Allowed; ---------------------------------------- -- Add_To_Config_Boolean_Restrictions -- ---------------------------------------- procedure Add_To_Config_Boolean_Restrictions (R : Restriction_Id) is begin Config_Cunit_Boolean_Restrictions (R) := True; end Add_To_Config_Boolean_Restrictions; -- Add specified restriction to stored configuration boolean restrictions. -- This is used for handling the special case of No_Elaboration_Code. ------------------------- -- Check_Compiler_Unit -- ------------------------- procedure Check_Compiler_Unit (Feature : String; N : Node_Id) is begin if Compiler_Unit then Error_Msg_N (Feature & "" not allowed in compiler unit!!??"", N); end if; end Check_Compiler_Unit; procedure Check_Compiler_Unit (Feature : String; Loc : Source_Ptr) is begin if Compiler_Unit then Error_Msg (Feature & "" not allowed in compiler unit!!??"", Loc); end if; end Check_Compiler_Unit; ------------------------------------ -- Check_Elaboration_Code_Allowed -- ------------------------------------ procedure Check_Elaboration_Code_Allowed (N : Node_Id) is begin Check_Restriction (No_Elaboration_Code, N); end Check_Elaboration_Code_Allowed; ----------------------------------------- -- Check_Implicit_Dynamic_Code_Allowed -- ----------------------------------------- procedure Check_Implicit_Dynamic_Code_Allowed (N : Node_Id) is begin Check_Restriction (No_Implicit_Dynamic_Code, N); end Check_Implicit_Dynamic_Code_Allowed; -------------------------------- -- Check_No_Implicit_Aliasing -- -------------------------------- procedure Check_No_Implicit_Aliasing (Obj : Node_Id) is E : Entity_Id; begin -- If restriction not active, nothing to check if not Restriction_Active (No_Implicit_Aliasing) then return; end if; -- If we have an entity name, check entity if Is_Entity_Name (Obj) then E := Entity (Obj); -- Restriction applies to entities that are objects if Is_Object (E) then if Is_Aliased (E) then return; elsif Present (Renamed_Object (E)) then Check_No_Implicit_Aliasing (Renamed_Object (E)); return; end if; -- If we don't have an object, then it's OK else return; end if; -- For selected component, check selector elsif Nkind (Obj) = N_Selected_Component then Check_No_Implicit_Aliasing (Selector_Name (Obj)); return; -- Indexed component is OK if aliased components elsif Nkind (Obj) = N_Indexed_Component then if Has_Aliased_Components (Etype (Prefix (Obj))) or else (Is_Access_Type (Etype (Prefix (Obj))) and then Has_Aliased_Components (Designated_Type (Etype (Prefix (Obj))))) then return; end if; -- For type conversion, check converted expression elsif Nkind (Obj) in N_Unchecked_Type_Conversion | N_Type_Conversion then Check_No_Implicit_Aliasing (Expression (Obj)); return; -- Explicit dereference is always OK elsif Nkind (Obj) = N_Explicit_Dereference then return; end if; -- If we fall through, then we have an aliased view that does not meet -- the rules for being explicitly aliased, so issue restriction msg. Check_Restriction (No_Implicit_Aliasing, Obj); end Check_No_Implicit_Aliasing; ---------------------------------- -- Check_No_Implicit_Heap_Alloc -- ---------------------------------- procedure Check_No_Implicit_Heap_Alloc (N : Node_Id) is begin Check_Restriction (No_Implicit_Heap_Allocations, N); end Check_No_Implicit_Heap_Alloc; ---------------------------------- -- Check_No_Implicit_Task_Alloc -- ---------------------------------- procedure Check_No_Implicit_Task_Alloc (N : Node_Id) is begin Check_Restriction (No_Implicit_Task_Allocations, N); end Check_No_Implicit_Task_Alloc; --------------------------------------- -- Check_No_Implicit_Protected_Alloc -- --------------------------------------- procedure Check_No_Implicit_Protected_Alloc (N : Node_Id) is begin Check_Restriction (No_Implicit_Protected_Object_Allocations, N); end Check_No_Implicit_Protected_Alloc; ----------------------------------- -- Check_Obsolescent_2005_Entity -- ----------------------------------- procedure Check_Obsolescent_2005_Entity (E : Entity_Id; N : Node_Id) is function Chars_Is (E : Entity_Id; S : String) return Boolean; -- Return True iff Chars (E) matches S (given in lower case) -------------- -- Chars_Is -- -------------- function Chars_Is (E : Entity_Id; S : String) return Boolean is Nam : constant Name_Id := Chars (E); begin if Length_Of_Name (Nam) /= S'Length then return False; else return Get_Name_String (Nam) = S; end if; end Chars_Is; -- Start of processing for Check_Obsolescent_2005_Entity begin if Restriction_Check_Required (No_Obsolescent_Features) and then Ada_Version >= Ada_2005 and then Chars_Is (Scope (E), ""handling"") and then Chars_Is (Scope (Scope (E)), ""characters"") and then Chars_Is (Scope (Scope (Scope (E))), ""ada"") and then Scope (Scope (Scope (Scope (E)))) = Standard_Standard then if Chars_Is (E, ""is_character"") or else Chars_Is (E, ""is_string"") or else Chars_Is (E, ""to_character"") or else Chars_Is (E, ""to_string"") or else Chars_Is (E, ""to_wide_character"") or else Chars_Is (E, ""to_wide_string"") then Check_Restriction (No_Obsolescent_Features, N); end if; end if; end Check_Obsolescent_2005_Entity; --------------------------- -- Check_Restricted_Unit -- --------------------------- procedure Check_Restricted_Unit (U : Unit_Name_Type; N : Node_Id) is begin if Suppress_Restriction_Message (N) then return; elsif Is_Spec_Name (U) then declare Fnam : constant File_Name_Type := Get_File_Name (U, Subunit => False); begin -- Get file name Get_Name_String (Fnam); -- Nothing to do if name not at least 5 characters long ending -- in .ads or .adb extension, which we strip. if Name_Len < 5 or else (Name_Buffer (Name_Len - 3 .. Name_Len) /= "".ads"" and then Name_Buffer (Name_Len - 3 .. Name_Len) /= "".adb"") then return; end if; -- Strip extension and pad to eight characters Name_Len := Name_Len - 4; Add_Str_To_Name_Buffer ((Name_Len + 1 .. 8 => ' ')); -- If predefined unit, check the list of restricted units if Is_Predefined_File_Name (Fnam) then for J in Unit_Array'Range loop if Name_Len = 8 and then Name_Buffer (1 .. 8) = Unit_Array (J).Filenm then Check_Restriction (Unit_Array (J).Res_Id, N); end if; end loop; -- If not predefined unit, then one special check still -- remains. GNAT.Current_Exception is not allowed if we have -- restriction No_Exception_Propagation active. else if Name_Buffer (1 .. 8) = ""g-curexc"" then Check_Restriction (No_Exception_Propagation, N); end if; end if; end; end if; end Check_Restricted_Unit; ----------------------- -- Check_Restriction -- ----------------------- procedure Check_Restriction (R : Restriction_Id; N : Node_Id; V : Uint := Uint_Minus_1) is Msg_Issued : Boolean; pragma Unreferenced (Msg_Issued); begin Check_Restriction (Msg_Issued, R, N, V); end Check_Restriction; procedure Check_Restriction (Msg_Issued : out Boolean; R : Restriction_Id; N : Node_Id; V : Uint := Uint_Minus_1) is VV : Integer; -- V converted to integer form. If V is greater than Integer'Last, -- it is reset to minus 1 (unknown value). procedure Update_Restrictions (Info : in out Restrictions_Info); -- Update violation information in Info.Violated and Info.Count ------------------------- -- Update_Restrictions -- ------------------------- procedure Update_Restrictions (Info : in out Restrictions_Info) is begin -- If not violated, set as violated now if not Info.Violated (R) then Info.Violated (R) := True; if R in All_Parameter_Restrictions then if VV < 0 then Info.Unknown (R) := True; Info.Count (R) := 1; else Info.Count (R) := VV; end if; end if; -- Otherwise if violated already and a parameter restriction, -- update count by maximizing or summing depending on restriction. elsif R in All_Parameter_Restrictions then -- If new value is unknown, result is unknown if VV < 0 then Info.Unknown (R) := True; -- If checked by maximization, nothing to do because the -- check is per-object. elsif R in Checked_Max_Parameter_Restrictions then null; -- If checked by adding, do add, checking for overflow elsif R in Checked_Add_Parameter_Restrictions then declare pragma Unsuppress (Overflow_Check); begin Info.Count (R) := Info.Count (R) + VV; exception when Constraint_Error => Info.Count (R) := Integer'Last; Info.Unknown (R) := True; end; -- Should not be able to come here, known counts should only -- occur for restrictions that are Checked_max or Checked_Sum. else raise Program_Error; end if; end if; end Update_Restrictions; -- Start of processing for Check_Restriction begin Msg_Issued := False; -- In CodePeer mode, we do not want to check for any restriction, or set -- additional restrictions other than those already set in gnat1drv.adb -- so that we have consistency between each compilation. -- In GNATprove mode restrictions are checked, except for -- No_Initialize_Scalars, which is implicitly set in gnat1drv.adb. if CodePeer_Mode or else (GNATprove_Mode and then R = No_Initialize_Scalars) then return; end if; if UI_Is_In_Int_Range (V) then VV := Integer (UI_To_Int (V)); else VV := -1; end if; -- Count can only be specified in the checked val parameter case pragma Assert (VV < 0 or else R in Checked_Val_Parameter_Restrictions); -- Nothing to do if value of zero specified for parameter restriction if VV = 0 then return; end if; -- Update current restrictions Update_Restrictions (Restrictions); -- If in main extended unit, update main restrictions as well. Note -- that as usual we check for Main_Unit explicitly to deal with the -- case of configuration pragma files. if Current_Sem_Unit = Main_Unit or else In_Extended_Main_Source_Unit (N) then Update_Restrictions (Main_Restrictions); end if; -- Nothing to do if restriction message suppressed if Suppress_Restriction_Message (N) then null; -- If restriction not set, nothing to do elsif not Restrictions.Set (R) then null; -- Don't complain about No_Obsolescent_Features in an instance, since we -- will complain on the template, which is much better. Are there other -- cases like this ??? Do we need a more general mechanism ??? elsif R = No_Obsolescent_Features and then Instantiation_Location (Sloc (N)) /= No_Location then null; -- Here if restriction set, check for violation (this is a Boolean -- restriction, or a parameter restriction with a value of zero and an -- unknown count, or a parameter restriction with a known value that -- exceeds the restriction count). elsif R in All_Boolean_Restrictions or else (Restrictions.Unknown (R) and then Restrictions.Value (R) = 0) or else Restrictions.Count (R) > Restrictions.Value (R) then Msg_Issued := True; Restriction_Msg (R, N); end if; -- For Max_Entries and the like, do not carry forward the violation -- count because it does not affect later declarations. if R in Checked_Max_Parameter_Restrictions then Restrictions.Count (R) := 0; Restrictions.Violated (R) := False; end if; end Check_Restriction; ------------------------------------- -- Check_Restriction_No_Dependence -- ------------------------------------- procedure Check_Restriction_No_Dependence (U : Node_Id; Err : Node_Id) is DU : Node_Id; begin -- Ignore call if node U is not in the main source unit. This avoids -- cascaded errors, e.g. when Ada.Containers units with other units. -- However, allow Standard_Location here, since this catches some cases -- of constructs that get converted to run-time calls. if not In_Extended_Main_Source_Unit (U) and then Sloc (U) /= Standard_Location then return; end if; -- Loop through entries in No_Dependence table to check each one in turn for J in No_Dependences.First .. No_Dependences.Last loop DU := No_Dependences.Table (J).Unit; if Same_Unit (U, DU) then Error_Msg_Sloc := Sloc (DU); Error_Msg_Node_1 := DU; if No_Dependences.Table (J).Warn then Error_Msg (""?*?violation of restriction `No_Dependence '='> &`#"", Sloc (Err)); else Error_Msg (""|violation of restriction `No_Dependence '='> &`#"", Sloc (Err)); end if; return; end if; end loop; end Check_Restriction_No_Dependence; -------------------------------------------------- -- Check_Restriction_No_Specification_Of_Aspect -- -------------------------------------------------- procedure Check_Restriction_No_Specification_Of_Aspect (N : Node_Id) is A_Id : Aspect_Id; Id : Node_Id; begin -- Ignore call if no instances of this restriction set if not No_Specification_Of_Aspect_Set then return; end if; -- Ignore call if node N is not in the main source unit, since we only -- give messages for the main unit. This avoids giving messages for -- aspects that are specified in withed units. if not In_Extended_Main_Source_Unit (N) then return; end if; if Nkind (N) = N_Pragma then Id := Pragma_Identifier (N); elsif Nkind (N) = N_Attribute_Definition_Clause then Id := N; else Id := Identifier (N); end if; A_Id := Get_Aspect_Id (Chars (Id)); pragma Assert (A_Id /= No_Aspect); Error_Msg_Sloc := No_Specification_Of_Aspects (A_Id); if Error_Msg_Sloc /= No_Location then Error_Msg_Node_1 := Id; Error_Msg_Warn := No_Specification_Of_Aspect_Warning (A_Id); Error_Msg_N (""<* %` #"", N); end if; end Check_Restriction_No_Use_Of_Attribute; ---------------------------------------- -- Check_Restriction_No_Use_Of_Entity -- ---------------------------------------- procedure Check_Restriction_No_Use_Of_Entity (N : Node_Id) is begin -- Error defence (not clearly necessary, but better safe) if No (Entity (N)) then return; end if; -- If simple name of entity not flagged with Boolean2 flag, then there -- cannot be a matching entry in the table, so skip the search. if Get_Name_Table_Boolean2 (Chars (Entity (N))) = False then return; end if; -- Restriction is only recognized within a configuration pragma file, -- or within a unit of the main extended program. Note: the test for -- Main_Unit is needed to properly include the case of configuration -- pragma files. if Current_Sem_Unit /= Main_Unit and then not In_Extended_Main_Source_Unit (N) then return; end if; -- Here we must search the table for J in No_Use_Of_Entity.First .. No_Use_Of_Entity.Last loop declare NE_Ent : NE_Entry renames No_Use_Of_Entity.Table (J); Ent : Entity_Id; Expr : Node_Id; begin Ent := Entity (N); Expr := NE_Ent.Entity; loop -- Here if at outer level of entity name in reference (handle -- also the direct use of Text_IO in the pragma). For example: -- pragma Restrictions (No_Use_Of_Entity => Text_IO.Put); if Scope (Ent) = Standard_Standard or else (Nkind (Expr) = N_Identifier and then Chars (Ent) = Name_Text_IO and then Chars (Scope (Ent)) = Name_Ada and then Scope (Scope (Ent)) = Standard_Standard) then if Nkind (Expr) in N_Identifier | N_Operator_Symbol and then Chars (Ent) = Chars (Expr) then Error_Msg_Node_1 := N; Error_Msg_Warn := NE_Ent.Warn; Error_Msg_Sloc := Sloc (NE_Ent.Entity); Error_Msg_N (""<* New_Name := Name_Simple_Barriers; when Name_Max_Entry_Queue_Depth => New_Name := Name_Max_Entry_Queue_Length; when Name_No_Dynamic_Interrupts => New_Name := Name_No_Dynamic_Attachment; when Name_No_Requeue => New_Name := Name_No_Requeue_Statements; when Name_No_Task_Attributes => New_Name := Name_No_Task_Attributes_Package; when others => return Old_Name; end case; -- Output warning if we are warning on obsolescent features. if Warn_On_Obsolescent_Feature then Error_Msg_Name_1 := Old_Name; Error_Msg_N (""restriction identifier % is obsolescent?j?"", N); Error_Msg_Name_1 := New_Name; Error_Msg_N (""|use restriction identifier % instead?j?"", N); end if; return New_Name; end Process_Restriction_Synonyms; -------------------------------------- -- Reset_Cunit_Boolean_Restrictions -- -------------------------------------- procedure Reset_Cunit_Boolean_Restrictions is begin for J in Cunit_Boolean_Restrictions loop Restrictions.Set (J) := False; end loop; end Reset_Cunit_Boolean_Restrictions; ----------------------------------------------- -- Restore_Config_Cunit_Boolean_Restrictions -- ----------------------------------------------- procedure Restore_Config_Cunit_Boolean_Restrictions is begin Cunit_Boolean_Restrictions_Restore (Config_Cunit_Boolean_Restrictions); end Restore_Config_Cunit_Boolean_Restrictions; ------------------------ -- Restricted_Profile -- ------------------------ function Restricted_Profile return Boolean is begin if Restricted_Profile_Cached then return Restricted_Profile_Result; else Restricted_Profile_Result := True; Restricted_Profile_Cached := True; declare R : Restriction_Flags renames Profile_Info (Restricted_Tasking).Set; V : Restriction_Values renames Profile_Info (Restricted_Tasking).Value; begin for J in R'Range loop if R (J) and then (Restrictions.Set (J) = False or else Restriction_Warnings (J) or else (J in All_Parameter_Restrictions and then Restrictions.Value (J) > V (J))) then Restricted_Profile_Result := False; exit; end if; end loop; return Restricted_Profile_Result; end; end if; end Restricted_Profile; ------------------------ -- Restriction_Active -- ------------------------ function Restriction_Active (R : All_Restrictions) return Boolean is begin return Restrictions.Set (R) and then not Restriction_Warnings (R); end Restriction_Active; -------------------------------- -- Restriction_Check_Required -- -------------------------------- function Restriction_Check_Required (R : All_Restrictions) return Boolean is begin return Restrictions.Set (R); end Restriction_Check_Required; --------------------- -- Restriction_Msg -- --------------------- procedure Restriction_Msg (R : Restriction_Id; N : Node_Id) is Msg : String (1 .. 100); Len : Natural := 0; procedure Add_Char (C : Character); -- Append given character to Msg, bumping Len procedure Add_Str (S : String); -- Append given string to Msg, bumping Len appropriately procedure Id_Case (S : String; Quotes : Boolean := True); -- Given a string S, case it according to current identifier casing, and -- store in Error_Msg_String. Then append `~` to the message buffer -- to output the string unchanged surrounded in quotes. The quotes -- are suppressed if Quotes = False. -------------- -- Add_Char -- -------------- procedure Add_Char (C : Character) is begin Len := Len + 1; Msg (Len) := C; end Add_Char; ------------- -- Add_Str -- ------------- procedure Add_Str (S : String) is begin Msg (Len + 1 .. Len + S'Length) := S; Len := Len + S'Length; end Add_Str; ------------- -- Id_Case -- ------------- procedure Id_Case (S : String; Quotes : Boolean := True) is begin Name_Buffer (1 .. S'Last) := S; Name_Len := S'Length; Set_Casing (Identifier_Casing (Get_Source_File_Index (Sloc (N)))); Error_Msg_Strlen := Name_Len; Error_Msg_String (1 .. Name_Len) := Name_Buffer (1 .. Name_Len); if Quotes then Add_Str (""`~`""); else Add_Char ('~'); end if; end Id_Case; -- Start of processing for Restriction_Msg begin -- Set warning message if warning if Restriction_Warnings (R) then Add_Str (""?*?""); -- If real violation (not warning), then mark it as non-serious unless -- it is a violation of No_Finalization in which case we leave it as a -- serious message, since otherwise we get crashes during attempts to -- expand stuff that is not properly formed due to assumptions made -- about no finalization being present. elsif R /= No_Finalization then Add_Char ('|'); end if; Error_Msg_Sloc := Restrictions_Loc (R); -- Set main message, adding implicit if no source location if Error_Msg_Sloc > No_Location or else Error_Msg_Sloc = System_Location then Add_Str (""violation of restriction ""); else Add_Str (""violation of implicit restriction ""); Error_Msg_Sloc := No_Location; end if; -- Case of parameterized restriction if R in All_Parameter_Restrictions then Add_Char ('`'); Id_Case (Restriction_Id'Image (R), Quotes => False); Add_Str ("" = ^`""); Error_Msg_Uint_1 := UI_From_Int (Int (Restrictions.Value (R))); -- Case of boolean restriction else Id_Case (Restriction_Id'Image (R)); end if; -- Case of no secondary profile continuation message if Restriction_Profile_Name (R) = No_Profile then if Error_Msg_Sloc /= No_Location then Add_Char ('#'); end if; Add_Char ('!'); Error_Msg_N (Msg (1 .. Len), N); -- Case of secondary profile continuation message present else Add_Char ('!'); Error_Msg_N (Msg (1 .. Len), N); Len := 0; Add_Char ('\\'); -- Set as warning if warning case if Restriction_Warnings (R) then Add_Str (""??""); end if; -- Set main message Add_Str (""from profile ""); Id_Case (Profile_Name'Image (Restriction_Profile_Name (R))); -- Add location if we have one if Error_Msg_Sloc /= No_Location then Add_Char ('#'); end if; -- Output unconditional message and we are done Add_Char ('!'); Error_Msg_N (Msg (1 .. Len), N); end if; end Restriction_Msg; ----------------- -- Same_Entity -- ----------------- function Same_Entity (E1, E2 : Node_Id) return Boolean is begin if Nkind (E1) in N_Identifier | N_Operator_Symbol and then Nkind (E2) in N_Identifier | N_Operator_Symbol then return Chars (E1) = Chars (E2); elsif Nkind (E1) in N_Selected_Component | N_Expanded_Name and then Nkind (E2) in N_Selected_Component | N_Expanded_Name then return Same_Unit (Prefix (E1), Prefix (E2)) and then Same_Unit (Selector_Name (E1), Selector_Name (E2)); else return False; end if; end Same_Entity; --------------- -- Same_Unit -- --------------- function Same_Unit (U1, U2 : Node_Id) return Boolean is begin if Nkind (U1) = N_Identifier and then Nkind (U2) = N_Identifier then return Chars (U1) = Chars (U2); elsif Nkind (U1) in N_Selected_Component | N_Expanded_Name and then Nkind (U2) in N_Selected_Component | N_Expanded_Name then return Same_Unit (Prefix (U1), Prefix (U2)) and then Same_Unit (Selector_Name (U1), Selector_Name (U2)); else return False; end if; end Same_Unit; -------------------------------------------- -- Save_Config_Cunit_Boolean_Restrictions -- -------------------------------------------- procedure Save_Config_Cunit_Boolean_Restrictions is begin Config_Cunit_Boolean_Restrictions := Cunit_Boolean_Restrictions_Save; end Save_Config_Cunit_Boolean_Restrictions; ------------------------------ -- Set_Profile_Restrictions -- ------------------------------ procedure Set_Profile_Restrictions (P : Profile_Name; N : Node_Id; Warn : Boolean) is R : Restriction_Flags renames Profile_Info (P).Set; V : Restriction_Values renames Profile_Info (P).Value; begin for J in R'Range loop if R (J) then declare Already_Restricted : constant Boolean := Restriction_Active (J); begin -- Set the restriction if J in All_Boolean_Restrictions then Set_Restriction (J, N); else Set_Restriction (J, N, V (J)); end if; -- Record that this came from a Profile[_Warnings] restriction Restriction_Profile_Name (J) := P; -- Set warning flag, except that we do not set the warning -- flag if the restriction was already active and this is -- the warning case. That avoids a warning overriding a real -- restriction, which should never happen. if not (Warn and Already_Restricted) then Restriction_Warnings (J) := Warn; end if; end; end if; end loop; end Set_Profile_Restrictions; --------------------- -- Set_Restriction -- --------------------- procedure Set_Restriction (R : All_Boolean_Restrictions; N : Node_Id) is begin Restrictions.Set (R) := True; if Restricted_Profile_Cached and Restricted_Profile_Result then null; else Restricted_Profile_Cached := False; end if; -- Set location, but preserve location of system restriction for nice -- error msg with run time name. if Restrictions_Loc (R) /= System_Location then Restrictions_Loc (R) := Sloc (N); end if; -- Note restriction came from restriction pragma, not profile Restriction_Profile_Name (R) := No_Profile; -- Record the restriction if we are in the main unit, or in the extended -- main unit. The reason that we test separately for Main_Unit is that -- gnat.adc is processed with Current_Sem_Unit = Main_Unit, but nodes in -- gnat.adc do not appear to be in the extended main source unit (they -- probably should do ???) if Current_Sem_Unit = Main_Unit or else In_Extended_Main_Source_Unit (N) then if not Restriction_Warnings (R) then Main_Restrictions.Set (R) := True; end if; end if; end Set_Restriction; procedure Set_Restriction (R : All_Parameter_Restrictions; N : Node_Id; V : Integer) is begin if Restricted_Profile_Cached and Restricted_Profile_Result then null; else Restricted_Profile_Cached := False; end if; if Restrictions.Set (R) then if V < Restrictions.Value (R) then Restrictions.Value (R) := V; Restrictions_Loc (R) := Sloc (N); end if; else Restrictions.Set (R) := True; Restrictions.Value (R) := V; Restrictions_Loc (R) := Sloc (N); end if; -- Record the restriction if we are in the main unit, or in the extended -- main unit. The reason that we test separately for Main_Unit is that -- gnat.adc is processed with Current_Sem_Unit = Main_Unit, but nodes in -- gnat.adc do not appear to be the extended main source unit (they -- probably should do ???) if Current_Sem_Unit = Main_Unit or else In_Extended_Main_Source_Unit (N) then if Main_Restrictions.Set (R) then if V < Main_Restrictions.Value (R) then Main_Restrictions.Value (R) := V; end if; elsif not Restriction_Warnings (R) then Main_Restrictions.Set (R) := True; Main_Restrictions.Value (R) := V; end if; end if; -- Note restriction came from restriction pragma, not profile Restriction_Profile_Name (R) := No_Profile; end Set_Restriction; procedure Set_Restriction (R : All_Restrictions; N : Node_Id; Warn : Boolean; V : Integer := Integer'First) is Set : Boolean := True; begin if Warn and then Restriction_Active (R) then Set := False; end if; if Set then if R in All_Boolean_Restrictions then Set_Restriction (R, N); else Set_Restriction (R, N, V); end if; Restriction_Warnings (R) := Warn; end if; end Set_Restriction; ----------------------------------- -- Set_Restriction_No_Dependence -- ----------------------------------- procedure Set_Restriction_No_Dependence (Unit : Node_Id; Warn : Boolean; Profile : Profile_Name := No_Profile) is begin -- Loop to check for duplicate entry for J in No_Dependences.First .. No_Dependences.Last loop -- Case of entry already in table if Same_Unit (Unit, No_Dependences.Table (J).Unit) then -- Error has precedence over warning if not Warn then No_Dependences.Table (J).Warn := False; end if; return; end if; end loop; -- Entry is not currently in table No_Dependences.Append ((Unit, Warn, Profile)); end Set_Restriction_No_Dependence; -------------------------------------- -- Set_Restriction_No_Use_Of_Entity -- -------------------------------------- procedure Set_Restriction_No_Use_Of_Entity (Entity : Node_Id; Warn : Boolean; Profile : Profile_Name := No_Profile) is Nam : Node_Id; begin -- Loop to check for duplicate entry for J in No_Use_Of_Entity.First .. No_Use_Of_Entity.Last loop -- Case of entry already in table if Same_Entity (Entity, No_Use_Of_Entity.Table (J).Entity) then -- Error has precedence over warning if not Warn then No_Use_Of_Entity.Table (J).Warn := False; end if; return; end if; end loop; -- Entry is not currently in table No_Use_Of_Entity.Append ((Entity, Warn, Profile)); -- Now we need to find the direct name and set Boolean2 flag if Nkind (Entity) in N_Identifier | N_Operator_Symbol then Nam := Entity; else pragma Assert (Nkind (Entity) = N_Selected_Component); Nam := Selector_Name (Entity); pragma Assert (Nkind (Nam) in N_Identifier | N_Operator_Symbol); end if; Set_Name_Table_Boolean2 (Chars (Nam), True); end Set_Restriction_No_Use_Of_Entity; ------------------------------------------------ -- Set_Restriction_No_Specification_Of_Aspect -- ------------------------------------------------ procedure Set_Restriction_No_Specification_Of_Aspect (N : Node_Id; Warn : Boolean) is A_Id : constant Aspect_Id_Exclude_No_Aspect := Get_Aspect_Id (Chars (N)); begin No_Specification_Of_Aspect_Set := True; No_Specification_Of_Aspects (A_Id) := Sloc (N); No_Specification_Of_Aspect_Warning (A_Id) := Warn; end Set_Restriction_No_Specification_Of_Aspect; procedure Set_Restriction_No_Specification_Of_Aspect (A_Id : Aspect_Id) is begin No_Specification_Of_Aspect_Set := True; No_Specification_Of_Aspects (A_Id) := System_Location; No_Specification_Of_Aspect_Warning (A_Id) := False; end Set_Restriction_No_Specification_Of_Aspect; ----------------------------------------- -- Set_Restriction_No_Use_Of_Attribute -- ----------------------------------------- procedure Set_Restriction_No_Use_Of_Attribute (N : Node_Id; Warn : Boolean) is A_Id : constant Attribute_Id := Get_Attribute_Id (Chars (N)); begin No_Use_Of_Attribute_Set := True; No_Use_Of_Attribute (A_Id) := Sloc (N); No_Use_Of_Attribute_Warning (A_Id) := Warn; end Set_Restriction_No_Use_Of_Attribute; procedure Set_Restriction_No_Use_Of_Attribute (A_Id : Attribute_Id) is begin No_Use_Of_Attribute_Set := True; No_Use_Of_Attribute (A_Id) := System_Location; No_Use_Of_Attribute_Warning (A_Id) := False; end Set_Restriction_No_Use_Of_Attribute; -------------------------------------- -- Set_Restriction_No_Use_Of_Pragma -- -------------------------------------- procedure Set_Restriction_No_Use_Of_Pragma (N : Node_Id; Warn : Boolean) is A_Id : constant Pragma_Id := Get_Pragma_Id (Chars (N)); begin No_Use_Of_Pragma_Set := True; No_Use_Of_Pragma (A_Id) := Sloc (N); No_Use_Of_Pragma_Warning (A_Id) := Warn; end Set_Restriction_No_Use_Of_Pragma; procedure Set_Restriction_No_Use_Of_Pragma (A_Id : Pragma_Id) is begin No_Use_Of_Pragma_Set := True; No_Use_Of_Pragma (A_Id) := System_Location; No_Use_Of_Pragma_Warning (A_Id) := False; end Set_Restriction_No_Use_Of_Pragma; --------------------------- -- Set_Global_No_Tasking -- --------------------------- procedure Set_Global_No_Tasking is begin Global_Restriction_No_Tasking := True; end Set_Global_No_Tasking; ---------------------------------- -- Suppress_Restriction_Message -- ---------------------------------- function Suppress_Restriction_Message (N : Node_Id) return Boolean is begin -- We only output messages for the extended main source unit if In_Extended_Main_Source_Unit (N) then return False; -- If loaded by rtsfind, then suppress message elsif Sloc (N) <= No_Location then return True; -- Otherwise suppress message if internal file else return In_Internal_Unit (N); end if; end Suppress_Restriction_Message; --------------------- -- Tasking_Allowed -- --------------------- function Tasking_Allowed return Boolean is begin return not Restrictions.Set (No_Tasking) and then (not Restrictions.Set (Max_Tasks) or else Restrictions.Value (Max_Tasks) > 0) and then not No_Run_Time_Mode; end Tasking_Allowed; end Restrict; ",12369,False,2435.7437130913368,median "------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- P R J . P A R T -- -- -- -- B o d y -- -- -- -- Copyright (C) 2001-2006, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, -- -- Boston, MA 02110-1301, USA. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Err_Vars; use Err_Vars; with Namet; use Namet; with Opt; use Opt; with Osint; use Osint; with Output; use Output; with Prj.Com; use Prj.Com; with Prj.Dect; with Prj.Err; use Prj.Err; with Prj.Ext; use Prj.Ext; with Sinput; use Sinput; with Sinput.P; use Sinput.P; with Snames; with Table; with Ada.Characters.Handling; use Ada.Characters.Handling; with Ada.Exceptions; use Ada.Exceptions; with GNAT.Directory_Operations; use GNAT.Directory_Operations; with System.HTable; use System.HTable; package body Prj.Part is Buffer : String_Access; Buffer_Last : Natural := 0; Dir_Sep : Character renames GNAT.OS_Lib.Directory_Separator; type Extension_Origin is (None, Extending_Simple, Extending_All); -- Type of parameter From_Extended for procedures Parse_Single_Project and -- Post_Parse_Context_Clause. Extending_All means that we are parsing the -- tree rooted at an extending all project. ------------------------------------ -- Local Packages and Subprograms -- ------------------------------------ type With_Id is new Nat; No_With : constant With_Id := 0; type With_Record is record Path : Name_Id; Location : Source_Ptr; Limited_With : Boolean; Node : Project_Node_Id; Next : With_Id; end record; -- Information about an imported project, to be put in table Withs below package Withs is new Table.Table (Table_Component_Type => With_Record, Table_Index_Type => With_Id, Table_Low_Bound => 1, Table_Initial => 10, Table_Increment => 50, Table_Name => ""Prj.Part.Withs""); -- Table used to store temporarily paths and locations of imported -- projects. These imported projects will be effectively parsed after the -- name of the current project has been extablished. type Names_And_Id is record Path_Name : Name_Id; Canonical_Path_Name : Name_Id; Id : Project_Node_Id; end record; package Project_Stack is new Table.Table (Table_Component_Type => Names_And_Id, Table_Index_Type => Nat, Table_Low_Bound => 1, Table_Initial => 10, Table_Increment => 50, Table_Name => ""Prj.Part.Project_Stack""); -- This table is used to detect circular dependencies -- for imported and extended projects and to get the project ids of -- limited imported projects when there is a circularity with at least -- one limited imported project file. package Virtual_Hash is new System.HTable.Simple_HTable (Header_Num => Header_Num, Element => Project_Node_Id, No_Element => Empty_Node, Key => Project_Node_Id, Hash => Prj.Tree.Hash, Equal => ""=""); -- Hash table to store the node id of the project for which a virtual -- extending project need to be created. package Processed_Hash is new System.HTable.Simple_HTable (Header_Num => Header_Num, Element => Boolean, No_Element => False, Key => Project_Node_Id, Hash => Prj.Tree.Hash, Equal => ""=""); -- Hash table to store the project process when looking for project that -- need to have a virtual extending project, to avoid processing the same -- project twice. procedure Create_Virtual_Extending_Project (For_Project : Project_Node_Id; Main_Project : Project_Node_Id; In_Tree : Project_Node_Tree_Ref); -- Create a virtual extending project of For_Project. Main_Project is -- the extending all project. -- -- The String_Value_Of is not set for the automatically added with -- clause and keeps the default value of No_Name. This enables Prj.PP -- to skip these automatically added with clauses to be processed. procedure Look_For_Virtual_Projects_For (Proj : Project_Node_Id; In_Tree : Project_Node_Tree_Ref; Potentially_Virtual : Boolean); -- Look for projects that need to have a virtual extending project. -- This procedure is recursive. If called with Potentially_Virtual set to -- True, then Proj may need an virtual extending project; otherwise it -- does not (because it is already extended), but other projects that it -- imports may need to be virtually extended. procedure Pre_Parse_Context_Clause (In_Tree : Project_Node_Tree_Ref; Context_Clause : out With_Id); -- Parse the context clause of a project. -- Store the paths and locations of the imported projects in table Withs. -- Does nothing if there is no context clause (if the current -- token is not ""with"" or ""limited"" followed by ""with""). procedure Post_Parse_Context_Clause (Context_Clause : With_Id; In_Tree : Project_Node_Tree_Ref; Imported_Projects : out Project_Node_Id; Project_Directory : Name_Id; From_Extended : Extension_Origin; In_Limited : Boolean; Packages_To_Check : String_List_Access); -- Parse the imported projects that have been stored in table Withs, -- if any. From_Extended is used for the call to Parse_Single_Project -- below. When In_Limited is True, the importing path includes at least -- one ""limited with"". procedure Parse_Single_Project (In_Tree : Project_Node_Tree_Ref; Project : out Project_Node_Id; Extends_All : out Boolean; Path_Name : String; Extended : Boolean; From_Extended : Extension_Origin; In_Limited : Boolean; Packages_To_Check : String_List_Access); -- Parse a project file. -- Recursive procedure: it calls itself for imported and extended -- projects. When From_Extended is not None, if the project has already -- been parsed and is an extended project A, return the ultimate -- (not extended) project that extends A. When In_Limited is True, -- the importing path includes at least one ""limited with"". function Project_Path_Name_Of (Project_File_Name : String; Directory : String) return String; -- Returns the path name of a project file. Returns an empty string -- if project file cannot be found. function Immediate_Directory_Of (Path_Name : Name_Id) return Name_Id; -- Get the directory of the file with the specified path name. -- This includes the directory separator as the last character. -- Returns ""./"" if Path_Name contains no directory separator. function Project_Name_From (Path_Name : String) return Name_Id; -- Returns the name of the project that corresponds to its path name. -- Returns No_Name if the path name is invalid, because the corresponding -- project name does not have the syntax of an ada identifier. -------------------------------------- -- Create_Virtual_Extending_Project -- -------------------------------------- procedure Create_Virtual_Extending_Project (For_Project : Project_Node_Id; Main_Project : Project_Node_Id; In_Tree : Project_Node_Tree_Ref) is Virtual_Name : constant String := Virtual_Prefix & Get_Name_String (Name_Of (For_Project, In_Tree)); -- The name of the virtual extending project Virtual_Name_Id : Name_Id; -- Virtual extending project name id Virtual_Path_Id : Name_Id; -- Fake path name of the virtual extending project. The directory is -- the same directory as the extending all project. Virtual_Dir_Id : constant Name_Id := Immediate_Directory_Of (Path_Name_Of (Main_Project, In_Tree)); -- The directory of the extending all project -- The source of the virtual extending project is something like: -- project V$ extends is -- for Source_Dirs use (); -- end V$; -- The project directory cannot be specified during parsing; it will be -- put directly in the virtual extending project data during processing. -- Nodes that made up the virtual extending project Virtual_Project : constant Project_Node_Id := Default_Project_Node (In_Tree, N_Project); With_Clause : constant Project_Node_Id := Default_Project_Node (In_Tree, N_With_Clause); Project_Declaration : constant Project_Node_Id := Default_Project_Node (In_Tree, N_Project_Declaration); Source_Dirs_Declaration : constant Project_Node_Id := Default_Project_Node (In_Tree, N_Declarative_Item); Source_Dirs_Attribute : constant Project_Node_Id := Default_Project_Node (In_Tree, N_Attribute_Declaration, List); Source_Dirs_Expression : constant Project_Node_Id := Default_Project_Node (In_Tree, N_Expression, List); Source_Dirs_Term : constant Project_Node_Id := Default_Project_Node (In_Tree, N_Term, List); Source_Dirs_List : constant Project_Node_Id := Default_Project_Node (In_Tree, N_Literal_String_List, List); begin -- Get the virtual name id Name_Len := Virtual_Name'Length; Name_Buffer (1 .. Name_Len) := Virtual_Name; Virtual_Name_Id := Name_Find; -- Get the virtual path name Get_Name_String (Path_Name_Of (Main_Project, In_Tree)); while Name_Len > 0 and then Name_Buffer (Name_Len) /= Directory_Separator and then Name_Buffer (Name_Len) /= '/' loop Name_Len := Name_Len - 1; end loop; Name_Buffer (Name_Len + 1 .. Name_Len + Virtual_Name'Length) := Virtual_Name; Name_Len := Name_Len + Virtual_Name'Length; Virtual_Path_Id := Name_Find; -- With clause Set_Name_Of (With_Clause, In_Tree, Virtual_Name_Id); Set_Path_Name_Of (With_Clause, In_Tree, Virtual_Path_Id); Set_Project_Node_Of (With_Clause, In_Tree, Virtual_Project); Set_Next_With_Clause_Of (With_Clause, In_Tree, First_With_Clause_Of (Main_Project, In_Tree)); Set_First_With_Clause_Of (Main_Project, In_Tree, With_Clause); -- Virtual project node Set_Name_Of (Virtual_Project, In_Tree, Virtual_Name_Id); Set_Path_Name_Of (Virtual_Project, In_Tree, Virtual_Path_Id); Set_Location_Of (Virtual_Project, In_Tree, Location_Of (Main_Project, In_Tree)); Set_Directory_Of (Virtual_Project, In_Tree, Virtual_Dir_Id); Set_Project_Declaration_Of (Virtual_Project, In_Tree, Project_Declaration); Set_Extended_Project_Path_Of (Virtual_Project, In_Tree, Path_Name_Of (For_Project, In_Tree)); -- Project declaration Set_First_Declarative_Item_Of (Project_Declaration, In_Tree, Source_Dirs_Declaration); Set_Extended_Project_Of (Project_Declaration, In_Tree, For_Project); -- Source_Dirs declaration Set_Current_Item_Node (Source_Dirs_Declaration, In_Tree, Source_Dirs_Attribute); -- Source_Dirs attribute Set_Name_Of (Source_Dirs_Attribute, In_Tree, Snames.Name_Source_Dirs); Set_Expression_Of (Source_Dirs_Attribute, In_Tree, Source_Dirs_Expression); -- Source_Dirs expression Set_First_Term (Source_Dirs_Expression, In_Tree, Source_Dirs_Term); -- Source_Dirs term Set_Current_Term (Source_Dirs_Term, In_Tree, Source_Dirs_List); -- Source_Dirs empty list: nothing to do -- Put virtual project into Projects_Htable Prj.Tree.Tree_Private_Part.Projects_Htable.Set (T => In_Tree.Projects_HT, K => Virtual_Name_Id, E => (Name => Virtual_Name_Id, Node => Virtual_Project, Canonical_Path => No_Name, Extended => False)); end Create_Virtual_Extending_Project; ---------------------------- -- Immediate_Directory_Of -- ---------------------------- function Immediate_Directory_Of (Path_Name : Name_Id) return Name_Id is begin Get_Name_String (Path_Name); for Index in reverse 1 .. Name_Len loop if Name_Buffer (Index) = '/' or else Name_Buffer (Index) = Dir_Sep then -- Remove all chars after last directory separator from name if Index > 1 then Name_Len := Index - 1; else Name_Len := Index; end if; return Name_Find; end if; end loop; -- There is no directory separator in name. Return ""./"" or "".\\"" Name_Len := 2; Name_Buffer (1) := '.'; Name_Buffer (2) := Dir_Sep; return Name_Find; end Immediate_Directory_Of; ----------------------------------- -- Look_For_Virtual_Projects_For -- ----------------------------------- procedure Look_For_Virtual_Projects_For (Proj : Project_Node_Id; In_Tree : Project_Node_Tree_Ref; Potentially_Virtual : Boolean) is Declaration : Project_Node_Id := Empty_Node; -- Node for the project declaration of Proj With_Clause : Project_Node_Id := Empty_Node; -- Node for a with clause of Proj Imported : Project_Node_Id := Empty_Node; -- Node for a project imported by Proj Extended : Project_Node_Id := Empty_Node; -- Node for the eventual project extended by Proj begin -- Nothing to do if Proj is not defined or if it has already been -- processed. if Proj /= Empty_Node and then not Processed_Hash.Get (Proj) then -- Make sure the project will not be processed again Processed_Hash.Set (Proj, True); Declaration := Project_Declaration_Of (Proj, In_Tree); if Declaration /= Empty_Node then Extended := Extended_Project_Of (Declaration, In_Tree); end if; -- If this is a project that may need a virtual extending project -- and it is not itself an extending project, put it in the list. if Potentially_Virtual and then Extended = Empty_Node then Virtual_Hash.Set (Proj, Proj); end if; -- Now check the projects it imports With_Clause := First_With_Clause_Of (Proj, In_Tree); while With_Clause /= Empty_Node loop Imported := Project_Node_Of (With_Clause, In_Tree); if Imported /= Empty_Node then Look_For_Virtual_Projects_For (Imported, In_Tree, Potentially_Virtual => True); end if; With_Clause := Next_With_Clause_Of (With_Clause, In_Tree); end loop; -- Check also the eventual project extended by Proj. As this project -- is already extended, call recursively with Potentially_Virtual -- being False. Look_For_Virtual_Projects_For (Extended, In_Tree, Potentially_Virtual => False); end if; end Look_For_Virtual_Projects_For; ----------- -- Parse -- ----------- procedure Parse (In_Tree : Project_Node_Tree_Ref; Project : out Project_Node_Id; Project_File_Name : String; Always_Errout_Finalize : Boolean; Packages_To_Check : String_List_Access := All_Packages; Store_Comments : Boolean := False) is Current_Directory : constant String := Get_Current_Dir; Dummy : Boolean; begin Project := Empty_Node; if Current_Verbosity >= Medium then Write_Str (""ADA_PROJECT_PATH=""""""); Write_Str (Project_Path); Write_Line (""""""""); end if; declare Path_Name : constant String := Project_Path_Name_Of (Project_File_Name, Directory => Current_Directory); begin Prj.Err.Initialize; Prj.Err.Scanner.Set_Comment_As_Token (Store_Comments); Prj.Err.Scanner.Set_End_Of_Line_As_Token (Store_Comments); -- Parse the main project file if Path_Name = """" then Prj.Com.Fail (""project file """""", Project_File_Name, """""" not found""); Project := Empty_Node; return; end if; Parse_Single_Project (In_Tree => In_Tree, Project => Project, Extends_All => Dummy, Path_Name => Path_Name, Extended => False, From_Extended => None, In_Limited => False, Packages_To_Check => Packages_To_Check); -- If Project is an extending-all project, create the eventual -- virtual extending projects and check that there are no illegally -- imported projects. if Project /= Empty_Node and then Is_Extending_All (Project, In_Tree) then -- First look for projects that potentially need a virtual -- extending project. Virtual_Hash.Reset; Processed_Hash.Reset; -- Mark the extending all project as processed, to avoid checking -- the imported projects in case of a ""limited with"" on this -- extending all project. Processed_Hash.Set (Project, True); declare Declaration : constant Project_Node_Id := Project_Declaration_Of (Project, In_Tree); begin Look_For_Virtual_Projects_For (Extended_Project_Of (Declaration, In_Tree), In_Tree, Potentially_Virtual => False); end; -- Now, check the projects directly imported by the main project. -- Remove from the potentially virtual any project extended by one -- of these imported projects. For non extending imported -- projects, check that they do not belong to the project tree of -- the project being ""extended-all"" by the main project. declare With_Clause : Project_Node_Id; Imported : Project_Node_Id := Empty_Node; Declaration : Project_Node_Id := Empty_Node; begin With_Clause := First_With_Clause_Of (Project, In_Tree); while With_Clause /= Empty_Node loop Imported := Project_Node_Of (With_Clause, In_Tree); if Imported /= Empty_Node then Declaration := Project_Declaration_Of (Imported, In_Tree); if Extended_Project_Of (Declaration, In_Tree) /= Empty_Node then loop Imported := Extended_Project_Of (Declaration, In_Tree); exit when Imported = Empty_Node; Virtual_Hash.Remove (Imported); Declaration := Project_Declaration_Of (Imported, In_Tree); end loop; end if; end if; With_Clause := Next_With_Clause_Of (With_Clause, In_Tree); end loop; end; -- Now create all the virtual extending projects declare Proj : Project_Node_Id := Virtual_Hash.Get_First; begin while Proj /= Empty_Node loop Create_Virtual_Extending_Project (Proj, Project, In_Tree); Proj := Virtual_Hash.Get_Next; end loop; end; end if; -- If there were any kind of error during the parsing, serious -- or not, then the parsing fails. if Err_Vars.Total_Errors_Detected > 0 then Project := Empty_Node; end if; if Project = Empty_Node or else Always_Errout_Finalize then Prj.Err.Finalize; end if; end; exception when X : others => -- Internal error Write_Line (Exception_Information (X)); Write_Str (""Exception ""); Write_Str (Exception_Name (X)); Write_Line ("" raised, while processing project file""); Project := Empty_Node; end Parse; ------------------------------ -- Pre_Parse_Context_Clause -- ------------------------------ procedure Pre_Parse_Context_Clause (In_Tree : Project_Node_Tree_Ref; Context_Clause : out With_Id) is Current_With_Clause : With_Id := No_With; Limited_With : Boolean := False; Current_With : With_Record; Current_With_Node : Project_Node_Id := Empty_Node; begin -- Assume no context clause Context_Clause := No_With; With_Loop : -- If Token is not WITH or LIMITED, there is no context clause, or we -- have exhausted the with clauses. while Token = Tok_With or else Token = Tok_Limited loop Current_With_Node := Default_Project_Node (Of_Kind => N_With_Clause, In_Tree => In_Tree); Limited_With := Token = Tok_Limited; if Limited_With then Scan (In_Tree); -- scan past LIMITED Expect (Tok_With, ""WITH""); exit With_Loop when Token /= Tok_With; end if; Comma_Loop : loop Scan (In_Tree); -- scan past WITH or "","" Expect (Tok_String_Literal, ""literal string""); if Token /= Tok_String_Literal then return; end if; -- Store path and location in table Withs Current_With := (Path => Token_Name, Location => Token_Ptr, Limited_With => Limited_With, Node => Current_With_Node, Next => No_With); Withs.Increment_Last; Withs.Table (Withs.Last) := Current_With; if Current_With_Clause = No_With then Context_Clause := Withs.Last; else Withs.Table (Current_With_Clause).Next := Withs.Last; end if; Current_With_Clause := Withs.Last; Scan (In_Tree); if Token = Tok_Semicolon then Set_End_Of_Line (Current_With_Node); Set_Previous_Line_Node (Current_With_Node); -- End of (possibly multiple) with clause; Scan (In_Tree); -- scan past the semicolon. exit Comma_Loop; elsif Token = Tok_Comma then Set_Is_Not_Last_In_List (Current_With_Node, In_Tree); else Error_Msg (""expected comma or semi colon"", Token_Ptr); exit Comma_Loop; end if; Current_With_Node := Default_Project_Node (Of_Kind => N_With_Clause, In_Tree => In_Tree); end loop Comma_Loop; end loop With_Loop; end Pre_Parse_Context_Clause; ------------------------------- -- Post_Parse_Context_Clause -- ------------------------------- procedure Post_Parse_Context_Clause (Context_Clause : With_Id; In_Tree : Project_Node_Tree_Ref; Imported_Projects : out Project_Node_Id; Project_Directory : Name_Id; From_Extended : Extension_Origin; In_Limited : Boolean; Packages_To_Check : String_List_Access) is Current_With_Clause : With_Id := Context_Clause; Current_Project : Project_Node_Id := Empty_Node; Previous_Project : Project_Node_Id := Empty_Node; Next_Project : Project_Node_Id := Empty_Node; Project_Directory_Path : constant String := Get_Name_String (Project_Directory); Current_With : With_Record; Limited_With : Boolean := False; Extends_All : Boolean := False; begin Imported_Projects := Empty_Node; while Current_With_Clause /= No_With loop Current_With := Withs.Table (Current_With_Clause); Current_With_Clause := Current_With.Next; Limited_With := In_Limited or Current_With.Limited_With; declare Original_Path : constant String := Get_Name_String (Current_With.Path); Imported_Path_Name : constant String := Project_Path_Name_Of (Original_Path, Project_Directory_Path); Resolved_Path : constant String := Normalize_Pathname (Imported_Path_Name, Resolve_Links => True, Case_Sensitive => True); Withed_Project : Project_Node_Id := Empty_Node; begin if Imported_Path_Name = """" then -- The project file cannot be found Error_Msg_Name_1 := Current_With.Path; Error_Msg (""unknown project file: {"", Current_With.Location); -- If this is not imported by the main project file, -- display the import path. if Project_Stack.Last > 1 then for Index in reverse 1 .. Project_Stack.Last loop Error_Msg_Name_1 := Project_Stack.Table (Index).Path_Name; Error_Msg (""\\imported by {"", Current_With.Location); end loop; end if; else -- New with clause Previous_Project := Current_Project; if Current_Project = Empty_Node then -- First with clause of the context clause Current_Project := Current_With.Node; Imported_Projects := Current_Project; else Next_Project := Current_With.Node; Set_Next_With_Clause_Of (Current_Project, In_Tree, Next_Project); Current_Project := Next_Project; end if; Set_String_Value_Of (Current_Project, In_Tree, Current_With.Path); Set_Location_Of (Current_Project, In_Tree, Current_With.Location); -- If this is a ""limited with"", check if we have a circularity. -- If we have one, get the project id of the limited imported -- project file, and do not parse it. if Limited_With and then Project_Stack.Last > 1 then declare Canonical_Path_Name : Name_Id; begin Name_Len := Resolved_Path'Length; Name_Buffer (1 .. Name_Len) := Resolved_Path; Canonical_Case_File_Name (Name_Buffer (1 .. Name_Len)); Canonical_Path_Name := Name_Find; for Index in 1 .. Project_Stack.Last loop if Project_Stack.Table (Index).Canonical_Path_Name = Canonical_Path_Name then -- We have found the limited imported project, -- get its project id, and do not parse it. Withed_Project := Project_Stack.Table (Index).Id; exit; end if; end loop; end; end if; -- Parse the imported project, if its project id is unknown if Withed_Project = Empty_Node then Parse_Single_Project (In_Tree => In_Tree, Project => Withed_Project, Extends_All => Extends_All, Path_Name => Imported_Path_Name, Extended => False, From_Extended => From_Extended, In_Limited => Limited_With, Packages_To_Check => Packages_To_Check); else Extends_All := Is_Extending_All (Withed_Project, In_Tree); end if; if Withed_Project = Empty_Node then -- If parsing was not successful, remove the -- context clause. Current_Project := Previous_Project; if Current_Project = Empty_Node then Imported_Projects := Empty_Node; else Set_Next_With_Clause_Of (Current_Project, In_Tree, Empty_Node); end if; else -- If parsing was successful, record project name -- and path name in with clause Set_Project_Node_Of (Node => Current_Project, In_Tree => In_Tree, To => Withed_Project, Limited_With => Current_With.Limited_With); Set_Name_Of (Current_Project, In_Tree, Name_Of (Withed_Project, In_Tree)); Name_Len := Resolved_Path'Length; Name_Buffer (1 .. Name_Len) := Resolved_Path; Set_Path_Name_Of (Current_Project, In_Tree, Name_Find); if Extends_All then Set_Is_Extending_All (Current_Project, In_Tree); end if; end if; end if; end; end loop; end Post_Parse_Context_Clause; -------------------------- -- Parse_Single_Project -- -------------------------- procedure Parse_Single_Project (In_Tree : Project_Node_Tree_Ref; Project : out Project_Node_Id; Extends_All : out Boolean; Path_Name : String; Extended : Boolean; From_Extended : Extension_Origin; In_Limited : Boolean; Packages_To_Check : String_List_Access) is Normed_Path_Name : Name_Id; Canonical_Path_Name : Name_Id; Project_Directory : Name_Id; Project_Scan_State : Saved_Project_Scan_State; Source_Index : Source_File_Index; Extending : Boolean := False; Extended_Project : Project_Node_Id := Empty_Node; A_Project_Name_And_Node : Tree_Private_Part.Project_Name_And_Node := Tree_Private_Part.Projects_Htable.Get_First (In_Tree.Projects_HT); Name_From_Path : constant Name_Id := Project_Name_From (Path_Name); Name_Of_Project : Name_Id := No_Name; First_With : With_Id; use Tree_Private_Part; Project_Comment_State : Tree.Comment_State; begin Extends_All := False; declare Normed_Path : constant String := Normalize_Pathname (Path_Name, Resolve_Links => False, Case_Sensitive => True); Canonical_Path : constant String := Normalize_Pathname (Normed_Path, Resolve_Links => True, Case_Sensitive => False); begin Name_Len := Normed_Path'Length; Name_Buffer (1 .. Name_Len) := Normed_Path; Normed_Path_Name := Name_Find; Name_Len := Canonical_Path'Length; Name_Buffer (1 .. Name_Len) := Canonical_Path; Canonical_Path_Name := Name_Find; end; -- Check for a circular dependency for Index in 1 .. Project_Stack.Last loop if Canonical_Path_Name = Project_Stack.Table (Index).Canonical_Path_Name then Error_Msg (""circular dependency detected"", Token_Ptr); Error_Msg_Name_1 := Normed_Path_Name; Error_Msg (""\\ { is imported by"", Token_Ptr); for Current in reverse 1 .. Project_Stack.Last loop Error_Msg_Name_1 := Project_Stack.Table (Current).Path_Name; if Project_Stack.Table (Current).Canonical_Path_Name /= Canonical_Path_Name then Error_Msg (""\\ { which itself is imported by"", Token_Ptr); else Error_Msg (""\\ {"", Token_Ptr); exit; end if; end loop; Project := Empty_Node; return; end if; end loop; -- Put the new path name on the stack Project_Stack.Increment_Last; Project_Stack.Table (Project_Stack.Last).Path_Name := Normed_Path_Name; Project_Stack.Table (Project_Stack.Last).Canonical_Path_Name := Canonical_Path_Name; -- Check if the project file has already been parsed while A_Project_Name_And_Node /= Tree_Private_Part.No_Project_Name_And_Node loop if A_Project_Name_And_Node.Canonical_Path = Canonical_Path_Name then if Extended then if A_Project_Name_And_Node.Extended then Error_Msg (""cannot extend the same project file several times"", Token_Ptr); else Error_Msg (""cannot extend an already imported project file"", Token_Ptr); end if; elsif A_Project_Name_And_Node.Extended then Extends_All := Is_Extending_All (A_Project_Name_And_Node.Node, In_Tree); -- If the imported project is an extended project A, -- and we are in an extended project, replace A with the -- ultimate project extending A. if From_Extended /= None then declare Decl : Project_Node_Id := Project_Declaration_Of (A_Project_Name_And_Node.Node, In_Tree); Prj : Project_Node_Id := Extending_Project_Of (Decl, In_Tree); begin loop Decl := Project_Declaration_Of (Prj, In_Tree); exit when Extending_Project_Of (Decl, In_Tree) = Empty_Node; Prj := Extending_Project_Of (Decl, In_Tree); end loop; A_Project_Name_And_Node.Node := Prj; end; else Error_Msg (""cannot import an already extended project file"", Token_Ptr); end if; end if; Project := A_Project_Name_And_Node.Node; Project_Stack.Decrement_Last; return; end if; A_Project_Name_And_Node := Tree_Private_Part.Projects_Htable.Get_Next (In_Tree.Projects_HT); end loop; -- We never encountered this project file -- Save the scan state, load the project file and start to scan it. Save_Project_Scan_State (Project_Scan_State); Source_Index := Load_Project_File (Path_Name); Tree.Save (Project_Comment_State); -- If we cannot find it, we stop if Source_Index = No_Source_File then Project := Empty_Node; Project_Stack.Decrement_Last; return; end if; Prj.Err.Scanner.Initialize_Scanner (Source_Index); Tree.Reset_State; Scan (In_Tree); if Name_From_Path = No_Name then -- The project file name is not correct (no or bad extension, -- or not following Ada identifier's syntax). Error_Msg_Name_1 := Canonical_Path_Name; Error_Msg (""?{ is not a valid path name for a project file"", Token_Ptr); end if; if Current_Verbosity >= Medium then Write_Str (""Parsing """"""); Write_Str (Path_Name); Write_Char ('""'); Write_Eol; end if; -- Is there any imported project? Pre_Parse_Context_Clause (In_Tree, First_With); Project_Directory := Immediate_Directory_Of (Normed_Path_Name); Project := Default_Project_Node (Of_Kind => N_Project, In_Tree => In_Tree); Project_Stack.Table (Project_Stack.Last).Id := Project; Set_Directory_Of (Project, In_Tree, Project_Directory); Set_Path_Name_Of (Project, In_Tree, Normed_Path_Name); Set_Location_Of (Project, In_Tree, Token_Ptr); Expect (Tok_Project, ""PROJECT""); -- Mark location of PROJECT token if present if Token = Tok_Project then Scan (In_Tree); -- scan past PROJECT Set_Location_Of (Project, In_Tree, Token_Ptr); end if; -- Clear the Buffer Buffer_Last := 0; loop Expect (Tok_Identifier, ""identifier""); -- If the token is not an identifier, clear the buffer before -- exiting to indicate that the name of the project is ill-formed. if Token /= Tok_Identifier then Buffer_Last := 0; exit; end if; -- Add the identifier name to the buffer Get_Name_String (Token_Name); Add_To_Buffer (Name_Buffer (1 .. Name_Len), Buffer, Buffer_Last); -- Scan past the identifier Scan (In_Tree); -- If we have a dot, add a dot the the Buffer and look for the next -- identifier. exit when Token /= Tok_Dot; Add_To_Buffer (""."", Buffer, Buffer_Last); -- Scan past the dot Scan (In_Tree); end loop; -- See if this is an extending project if Token = Tok_Extends then -- Make sure that gnatmake will use mapping files Create_Mapping_File := True; -- We are extending another project Extending := True; Scan (In_Tree); -- scan past EXTENDS if Token = Tok_All then Extends_All := True; Set_Is_Extending_All (Project, In_Tree); Scan (In_Tree); -- scan past ALL end if; end if; -- If the name is well formed, Buffer_Last is > 0 if Buffer_Last > 0 then -- The Buffer contains the name of the project Name_Len := Buffer_Last; Name_Buffer (1 .. Name_Len) := Buffer (1 .. Buffer_Last); Name_Of_Project := Name_Find; Set_Name_Of (Project, In_Tree, Name_Of_Project); -- To get expected name of the project file, replace dots by dashes Name_Len := Buffer_Last; Name_Buffer (1 .. Name_Len) := Buffer (1 .. Buffer_Last); for Index in 1 .. Name_Len loop if Name_Buffer (Index) = '.' then Name_Buffer (Index) := '-'; end if; end loop; Canonical_Case_File_Name (Name_Buffer (1 .. Name_Len)); declare Expected_Name : constant Name_Id := Name_Find; begin -- Output a warning if the actual name is not the expected name if Name_From_Path /= No_Name and then Expected_Name /= Name_From_Path then Error_Msg_Name_1 := Expected_Name; Error_Msg (""?file name does not match unit name, "" & ""should be `{"" & Project_File_Extension & ""`"", Token_Ptr); end if; end; declare Imported_Projects : Project_Node_Id := Empty_Node; From_Ext : Extension_Origin := None; begin -- Extending_All is always propagated if From_Extended = Extending_All or else Extends_All then From_Ext := Extending_All; -- Otherwise, From_Extended is set to Extending_Single if the -- current project is an extending project. elsif Extended then From_Ext := Extending_Simple; end if; Post_Parse_Context_Clause (In_Tree => In_Tree, Context_Clause => First_With, Imported_Projects => Imported_Projects, Project_Directory => Project_Directory, From_Extended => From_Ext, In_Limited => In_Limited, Packages_To_Check => Packages_To_Check); Set_First_With_Clause_Of (Project, In_Tree, Imported_Projects); end; declare Name_And_Node : Tree_Private_Part.Project_Name_And_Node := Tree_Private_Part.Projects_Htable.Get_First (In_Tree.Projects_HT); Project_Name : Name_Id := Name_And_Node.Name; begin -- Check if we already have a project with this name while Project_Name /= No_Name and then Project_Name /= Name_Of_Project loop Name_And_Node := Tree_Private_Part.Projects_Htable.Get_Next (In_Tree.Projects_HT); Project_Name := Name_And_Node.Name; end loop; -- Report an error if we already have a project with this name if Project_Name /= No_Name then Error_Msg_Name_1 := Project_Name; Error_Msg (""duplicate project name {"", Location_Of (Project, In_Tree)); Error_Msg_Name_1 := Path_Name_Of (Name_And_Node.Node, In_Tree); Error_Msg (""\\already in {"", Location_Of (Project, In_Tree)); else -- Otherwise, add the name of the project to the hash table, so -- that we can check that no other subsequent project will have -- the same name. Tree_Private_Part.Projects_Htable.Set (T => In_Tree.Projects_HT, K => Name_Of_Project, E => (Name => Name_Of_Project, Node => Project, Canonical_Path => Canonical_Path_Name, Extended => Extended)); end if; end; end if; if Extending then Expect (Tok_String_Literal, ""literal string""); if Token = Tok_String_Literal then Set_Extended_Project_Path_Of (Project, In_Tree, Token_Name); declare Original_Path_Name : constant String := Get_Name_String (Token_Name); Extended_Project_Path_Name : constant String := Project_Path_Name_Of (Original_Path_Name, Get_Name_String (Project_Directory)); begin if Extended_Project_Path_Name = """" then -- We could not find the project file to extend Error_Msg_Name_1 := Token_Name; Error_Msg (""unknown project file: {"", Token_Ptr); -- If we are not in the main project file, display the -- import path. if Project_Stack.Last > 1 then Error_Msg_Name_1 := Project_Stack.Table (Project_Stack.Last).Path_Name; Error_Msg (""\\extended by {"", Token_Ptr); for Index in reverse 1 .. Project_Stack.Last - 1 loop Error_Msg_Name_1 := Project_Stack.Table (Index).Path_Name; Error_Msg (""\\imported by {"", Token_Ptr); end loop; end if; else declare From_Ext : Extension_Origin := None; begin if From_Extended = Extending_All or else Extends_All then From_Ext := Extending_All; end if; Parse_Single_Project (In_Tree => In_Tree, Project => Extended_Project, Extends_All => Extends_All, Path_Name => Extended_Project_Path_Name, Extended => True, From_Extended => From_Ext, In_Limited => In_Limited, Packages_To_Check => Packages_To_Check); end; -- A project that extends an extending-all project is also -- an extending-all project. if Extended_Project /= Empty_Node and then Is_Extending_All (Extended_Project, In_Tree) then Set_Is_Extending_All (Project, In_Tree); end if; end if; end; Scan (In_Tree); -- scan past the extended project path end if; end if; -- Check that a non extending-all project does not import an -- extending-all project. if not Is_Extending_All (Project, In_Tree) then declare With_Clause : Project_Node_Id := First_With_Clause_Of (Project, In_Tree); Imported : Project_Node_Id := Empty_Node; begin With_Clause_Loop : while With_Clause /= Empty_Node loop Imported := Project_Node_Of (With_Clause, In_Tree); if Is_Extending_All (With_Clause, In_Tree) then Error_Msg_Name_1 := Name_Of (Imported, In_Tree); Error_Msg (""cannot import extending-all project {"", Token_Ptr); exit With_Clause_Loop; end if; With_Clause := Next_With_Clause_Of (With_Clause, In_Tree); end loop With_Clause_Loop; end; end if; -- Check that a project with a name including a dot either imports -- or extends the project whose name precedes the last dot. if Name_Of_Project /= No_Name then Get_Name_String (Name_Of_Project); else Name_Len := 0; end if; -- Look for the last dot while Name_Len > 0 and then Name_Buffer (Name_Len) /= '.' loop Name_Len := Name_Len - 1; end loop; -- If a dot was find, check if the parent project is imported -- or extended. if Name_Len > 0 then Name_Len := Name_Len - 1; declare Parent_Name : constant Name_Id := Name_Find; Parent_Found : Boolean := False; With_Clause : Project_Node_Id := First_With_Clause_Of (Project, In_Tree); begin -- If there is an extended project, check its name if Extended_Project /= Empty_Node then Parent_Found := Name_Of (Extended_Project, In_Tree) = Parent_Name; end if; -- If the parent project is not the extended project, -- check each imported project until we find the parent project. while not Parent_Found and then With_Clause /= Empty_Node loop Parent_Found := Name_Of (Project_Node_Of (With_Clause, In_Tree), In_Tree) = Parent_Name; With_Clause := Next_With_Clause_Of (With_Clause, In_Tree); end loop; -- If the parent project was not found, report an error if not Parent_Found then Error_Msg_Name_1 := Name_Of_Project; Error_Msg_Name_2 := Parent_Name; Error_Msg (""project { does not import or extend project {"", Location_Of (Project, In_Tree)); end if; end; end if; Expect (Tok_Is, ""IS""); Set_End_Of_Line (Project); Set_Previous_Line_Node (Project); Set_Next_End_Node (Project); declare Project_Declaration : Project_Node_Id := Empty_Node; begin -- No need to Scan past ""is"", Prj.Dect.Parse will do it Prj.Dect.Parse (In_Tree => In_Tree, Declarations => Project_Declaration, Current_Project => Project, Extends => Extended_Project, Packages_To_Check => Packages_To_Check); Set_Project_Declaration_Of (Project, In_Tree, Project_Declaration); if Extended_Project /= Empty_Node then Set_Extending_Project_Of (Project_Declaration_Of (Extended_Project, In_Tree), In_Tree, To => Project); end if; end; Expect (Tok_End, ""END""); Remove_Next_End_Node; -- Skip ""end"" if present if Token = Tok_End then Scan (In_Tree); end if; -- Clear the Buffer Buffer_Last := 0; -- Store the name following ""end"" in the Buffer. The name may be made of -- several simple names. loop Expect (Tok_Identifier, ""identifier""); -- If we don't have an identifier, clear the buffer before exiting to -- avoid checking the name. if Token /= Tok_Identifier then Buffer_Last := 0; exit; end if; -- Add the identifier to the Buffer Get_Name_String (Token_Name); Add_To_Buffer (Name_Buffer (1 .. Name_Len), Buffer, Buffer_Last); -- Scan past the identifier Scan (In_Tree); exit when Token /= Tok_Dot; Add_To_Buffer (""."", Buffer, Buffer_Last); Scan (In_Tree); end loop; -- If we have a valid name, check if it is the name of the project if Name_Of_Project /= No_Name and then Buffer_Last > 0 then if To_Lower (Buffer (1 .. Buffer_Last)) /= Get_Name_String (Name_Of (Project, In_Tree)) then -- Invalid name: report an error Error_Msg (""expected """""" & Get_Name_String (Name_Of (Project, In_Tree)) & """""""", Token_Ptr); end if; end if; Expect (Tok_Semicolon, ""`;`""); -- Check that there is no more text following the end of the project -- source. if Token = Tok_Semicolon then Set_Previous_End_Node (Project); Scan (In_Tree); if Token /= Tok_EOF then Error_Msg (""unexpected text following end of project"", Token_Ptr); end if; end if; -- Restore the scan state, in case we are not the main project Restore_Project_Scan_State (Project_Scan_State); -- And remove the project from the project stack Project_Stack.Decrement_Last; -- Indicate if there are unkept comments Tree.Set_Project_File_Includes_Unkept_Comments (Node => Project, In_Tree => In_Tree, To => Tree.There_Are_Unkept_Comments); -- And restore the comment state that was saved Tree.Restore (Project_Comment_State); end Parse_Single_Project; ----------------------- -- Project_Name_From -- ----------------------- function Project_Name_From (Path_Name : String) return Name_Id is Canonical : String (1 .. Path_Name'Length) := Path_Name; First : Natural := Canonical'Last; Last : Natural := First; Index : Positive; begin if Current_Verbosity = High then Write_Str (""Project_Name_From (""""""); Write_Str (Canonical); Write_Line ("""""")""); end if; -- If the path name is empty, return No_Name to indicate failure if First = 0 then return No_Name; end if; Canonical_Case_File_Name (Canonical); -- Look for the last dot in the path name while First > 0 and then Canonical (First) /= '.' loop First := First - 1; end loop; -- If we have a dot, check that it is followed by the correct extension if First > 0 and then Canonical (First) = '.' then if Canonical (First .. Last) = Project_File_Extension and then First /= 1 then -- Look for the last directory separator, if any First := First - 1; Last := First; while First > 0 and then Canonical (First) /= '/' and then Canonical (First) /= Dir_Sep loop First := First - 1; end loop; else -- Not the correct extension, return No_Name to indicate failure return No_Name; end if; -- If no dot in the path name, return No_Name to indicate failure else return No_Name; end if; First := First + 1; -- If the extension is the file name, return No_Name to indicate failure if First > Last then return No_Name; end if; -- Put the name in lower case into Name_Buffer Name_Len := Last - First + 1; Name_Buffer (1 .. Name_Len) := To_Lower (Canonical (First .. Last)); Index := 1; -- Check if it is a well formed project name. Return No_Name if it is -- ill formed. loop if not Is_Letter (Name_Buffer (Index)) then return No_Name; else loop Index := Index + 1; exit when Index >= Name_Len; if Name_Buffer (Index) = '_' then if Name_Buffer (Index + 1) = '_' then return No_Name; end if; end if; exit when Name_Buffer (Index) = '-'; if Name_Buffer (Index) /= '_' and then not Is_Alphanumeric (Name_Buffer (Index)) then return No_Name; end if; end loop; end if; if Index >= Name_Len then if Is_Alphanumeric (Name_Buffer (Name_Len)) then -- All checks have succeeded. Return name in Name_Buffer return Name_Find; else return No_Name; end if; elsif Name_Buffer (Index) = '-' then Index := Index + 1; end if; end loop; end Project_Name_From; -------------------------- -- Project_Path_Name_Of -- -------------------------- function Project_Path_Name_Of (Project_File_Name : String; Directory : String) return String is Result : String_Access; begin if Current_Verbosity = High then Write_Str (""Project_Path_Name_Of (""""""); Write_Str (Project_File_Name); Write_Str ("""""", """"""); Write_Str (Directory); Write_Line ("""""");""); end if; if not Is_Absolute_Path (Project_File_Name) then -- First we try /. if Current_Verbosity = High then Write_Str ("" Trying ""); Write_Str (Directory); Write_Char (Directory_Separator); Write_Str (Project_File_Name); Write_Line (Project_File_Extension); end if; Result := Locate_Regular_File (File_Name => Directory & Directory_Separator & Project_File_Name & Project_File_Extension, Path => Project_Path); -- Then we try / if Result = null then if Current_Verbosity = High then Write_Str ("" Trying ""); Write_Str (Directory); Write_Char (Directory_Separator); Write_Line (Project_File_Name); end if; Result := Locate_Regular_File (File_Name => Directory & Directory_Separator & Project_File_Name, Path => Project_Path); end if; end if; if Result = null then -- Then we try . if Current_Verbosity = High then Write_Str ("" Trying ""); Write_Str (Project_File_Name); Write_Line (Project_File_Extension); end if; Result := Locate_Regular_File (File_Name => Project_File_Name & Project_File_Extension, Path => Project_Path); end if; if Result = null then -- Then we try if Current_Verbosity = High then Write_Str ("" Trying ""); Write_Line (Project_File_Name); end if; Result := Locate_Regular_File (File_Name => Project_File_Name, Path => Project_Path); end if; -- If we cannot find the project file, we return an empty string if Result = null then return """"; else declare Final_Result : constant String := GNAT.OS_Lib.Normalize_Pathname (Result.all, Resolve_Links => False, Case_Sensitive => True); begin Free (Result); return Final_Result; end; end if; end Project_Path_Name_Of; end Prj.Part; ",12453,False,2397.576952887369,median "pragma Ada_2012; pragma Style_Checks (Off); with Interfaces.C; use Interfaces.C; with X11; with Interfaces.C.Strings; with Xlib; with System; package Xutil is NoValue : constant := 16#0000#; -- /usr/include/X11/Xutil.h:68 XValue : constant := 16#0001#; -- /usr/include/X11/Xutil.h:69 YValue : constant := 16#0002#; -- /usr/include/X11/Xutil.h:70 WidthValue : constant := 16#0004#; -- /usr/include/X11/Xutil.h:71 HeightValue : constant := 16#0008#; -- /usr/include/X11/Xutil.h:72 AllValues : constant := 16#000F#; -- /usr/include/X11/Xutil.h:73 XNegative : constant := 16#0010#; -- /usr/include/X11/Xutil.h:74 YNegative : constant := 16#0020#; -- /usr/include/X11/Xutil.h:75 USPosition : constant := (2 ** 0); -- /usr/include/X11/Xutil.h:102 USSize : constant := (2 ** 1); -- /usr/include/X11/Xutil.h:103 PPosition : constant := (2 ** 2); -- /usr/include/X11/Xutil.h:105 PSize : constant := (2 ** 3); -- /usr/include/X11/Xutil.h:106 PMinSize : constant := (2 ** 4); -- /usr/include/X11/Xutil.h:107 PMaxSize : constant := (2 ** 5); -- /usr/include/X11/Xutil.h:108 PResizeInc : constant := (2 ** 6); -- /usr/include/X11/Xutil.h:109 PAspect : constant := (2 ** 7); -- /usr/include/X11/Xutil.h:110 PBaseSize : constant := (2 ** 8); -- /usr/include/X11/Xutil.h:111 PWinGravity : constant := (2 ** 9); -- /usr/include/X11/Xutil.h:112 -- unsupported macro: PAllHints (PPosition|PSize|PMinSize|PMaxSize|PResizeInc|PAspect) InputHint : constant := (2 ** 0); -- /usr/include/X11/Xutil.h:134 StateHint : constant := (2 ** 1); -- /usr/include/X11/Xutil.h:135 IconPixmapHint : constant := (2 ** 2); -- /usr/include/X11/Xutil.h:136 IconWindowHint : constant := (2 ** 3); -- /usr/include/X11/Xutil.h:137 IconPositionHint : constant := (2 ** 4); -- /usr/include/X11/Xutil.h:138 IconMaskHint : constant := (2 ** 5); -- /usr/include/X11/Xutil.h:139 WindowGroupHint : constant := (2 ** 6); -- /usr/include/X11/Xutil.h:140 -- unsupported macro: AllHints (InputHint|StateHint|IconPixmapHint|IconWindowHint| IconPositionHint|IconMaskHint|WindowGroupHint) XUrgencyHint : constant := (2 ** 8); -- /usr/include/X11/Xutil.h:143 WithdrawnState : constant := 0; -- /usr/include/X11/Xutil.h:146 NormalState : constant := 1; -- /usr/include/X11/Xutil.h:147 IconicState : constant := 3; -- /usr/include/X11/Xutil.h:148 DontCareState : constant := 0; -- /usr/include/X11/Xutil.h:153 ZoomState : constant := 2; -- /usr/include/X11/Xutil.h:154 InactiveState : constant := 4; -- /usr/include/X11/Xutil.h:155 XNoMemory : constant := -1; -- /usr/include/X11/Xutil.h:170 XLocaleNotSupported : constant := -2; -- /usr/include/X11/Xutil.h:171 XConverterNotFound : constant := -3; -- /usr/include/X11/Xutil.h:172 -- arg-macro: function XDestroyImage (ximage) -- return (*((ximage).f.destroy_image))((ximage)); -- arg-macro: function XGetPixel (ximage, x, y) -- return (*((ximage).f.get_pixel))((ximage), (x), (y)); -- arg-macro: function XPutPixel (ximage, x, y, pixel) -- return (*((ximage).f.put_pixel))((ximage), (x), (y), (pixel)); -- arg-macro: function XSubImage (ximage, x, y, width, height) -- return (*((ximage).f.sub_image))((ximage), (x), (y), (width), (height)); -- arg-macro: function XAddPixel (ximage, value) -- return (*((ximage).f.add_pixel))((ximage), (value)); -- arg-macro: function IsKeypadKey (keysym) -- return ((KeySym)(keysym) >= XK_KP_Space) and then ((KeySym)(keysym) <= XK_KP_Equal); -- arg-macro: function IsPrivateKeypadKey (keysym) -- return ((KeySym)(keysym) >= 16#11000000#) and then ((KeySym)(keysym) <= 16#1100FFFF#); -- arg-macro: function IsCursorKey (keysym) -- return ((KeySym)(keysym) >= XK_Home) and then ((KeySym)(keysym) < XK_Select); -- arg-macro: function IsPFKey (keysym) -- return ((KeySym)(keysym) >= XK_KP_F1) and then ((KeySym)(keysym) <= XK_KP_F4); -- arg-macro: function IsFunctionKey (keysym) -- return ((KeySym)(keysym) >= XK_F1) and then ((KeySym)(keysym) <= XK_F35); -- arg-macro: function IsMiscFunctionKey (keysym) -- return ((KeySym)(keysym) >= XK_Select) and then ((KeySym)(keysym) <= XK_Break); -- arg-macro: function IsModifierKey (keysym) -- return (((KeySym)(keysym) >= XK_Shift_L) and then ((KeySym)(keysym) <= XK_Hyper_R)) or else (((KeySym)(keysym) >= XK_ISO_Lock) and then ((KeySym)(keysym) <= XK_ISO_Level5_Lock)) or else ((KeySym)(keysym) = XK_Mode_switch) or else ((KeySym)(keysym) = XK_Num_Lock); RectangleOut : constant := 0; -- /usr/include/X11/Xutil.h:277 RectangleIn : constant := 1; -- /usr/include/X11/Xutil.h:278 RectanglePart : constant := 2; -- /usr/include/X11/Xutil.h:279 VisualNoMask : constant := 16#0#; -- /usr/include/X11/Xutil.h:304 VisualIDMask : constant := 16#1#; -- /usr/include/X11/Xutil.h:305 VisualScreenMask : constant := 16#2#; -- /usr/include/X11/Xutil.h:306 VisualDepthMask : constant := 16#4#; -- /usr/include/X11/Xutil.h:307 VisualClassMask : constant := 16#8#; -- /usr/include/X11/Xutil.h:308 VisualRedMaskMask : constant := 16#10#; -- /usr/include/X11/Xutil.h:309 VisualGreenMaskMask : constant := 16#20#; -- /usr/include/X11/Xutil.h:310 VisualBlueMaskMask : constant := 16#40#; -- /usr/include/X11/Xutil.h:311 VisualColormapSizeMask : constant := 16#80#; -- /usr/include/X11/Xutil.h:312 VisualBitsPerRGBMask : constant := 16#100#; -- /usr/include/X11/Xutil.h:313 VisualAllMask : constant := 16#1FF#; -- /usr/include/X11/Xutil.h:314 -- unsupported macro: ReleaseByFreeingColormap ((XID) 1L) BitmapSuccess : constant := 0; -- /usr/include/X11/Xutil.h:339 BitmapOpenFailed : constant := 1; -- /usr/include/X11/Xutil.h:340 BitmapFileInvalid : constant := 2; -- /usr/include/X11/Xutil.h:341 BitmapNoMemory : constant := 3; -- /usr/include/X11/Xutil.h:342 XCSUCCESS : constant := 0; -- /usr/include/X11/Xutil.h:353 XCNOMEM : constant := 1; -- /usr/include/X11/Xutil.h:354 XCNOENT : constant := 2; -- /usr/include/X11/Xutil.h:355 -- arg-macro: function XUniqueContext () -- return (XContext) XrmUniqueQuark(); -- arg-macro: function XStringToContext (string) -- return (XContext) XrmStringToQuark(string); --********************************************************** --Copyright 1987, 1998 The Open Group --Permission to use, copy, modify, distribute, and sell this software and its --documentation for any purpose is hereby granted without fee, provided that --the above copyright notice appear in all copies and that both that --copyright notice and this permission notice appear in supporting --documentation. --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 --OPEN GROUP 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. --Except as contained in this notice, the name of The Open Group shall not be --used in advertising or otherwise to promote the sale, use or other dealings --in this Software without prior written authorization from The Open Group. --Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts. -- All Rights Reserved --Permission to use, copy, modify, and distribute this software and its --documentation for any purpose and without fee is hereby granted, --provided that the above copyright notice appear in all copies and that --both that copyright notice and this permission notice appear in --supporting documentation, and that the name of Digital not be --used in advertising or publicity pertaining to distribution of the --software without specific, written prior permission. --DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING --ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL --DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR --ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, --WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, --ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS --SOFTWARE. --***************************************************************** -- You must include before including this file -- The Xlib structs are full of implicit padding to properly align members. -- We can't clean that up without breaking ABI, so tell clang not to bother -- complaining about it. -- * Bitmask returned by XParseGeometry(). Each bit tells if the corresponding -- * value (x, y, width, height) was found in the parsed string. -- -- * new version containing base_width, base_height, and win_gravity fields; -- * used with WM_NORMAL_HINTS. -- -- marks which fields in this structure are defined -- skipped anonymous struct anon_97 type anon_98 is record x : aliased int; -- /usr/include/X11/Xutil.h:89 y : aliased int; -- /usr/include/X11/Xutil.h:90 end record with Convention => C_Pass_By_Copy; type XSizeHints is record flags : aliased long; -- /usr/include/X11/Xutil.h:82 x : aliased int; -- /usr/include/X11/Xutil.h:83 y : aliased int; -- /usr/include/X11/Xutil.h:83 width : aliased int; -- /usr/include/X11/Xutil.h:84 height : aliased int; -- /usr/include/X11/Xutil.h:84 min_width : aliased int; -- /usr/include/X11/Xutil.h:85 min_height : aliased int; -- /usr/include/X11/Xutil.h:85 max_width : aliased int; -- /usr/include/X11/Xutil.h:86 max_height : aliased int; -- /usr/include/X11/Xutil.h:86 width_inc : aliased int; -- /usr/include/X11/Xutil.h:87 height_inc : aliased int; -- /usr/include/X11/Xutil.h:87 min_aspect : aliased anon_98; -- /usr/include/X11/Xutil.h:91 max_aspect : aliased anon_98; -- /usr/include/X11/Xutil.h:91 base_width : aliased int; -- /usr/include/X11/Xutil.h:92 base_height : aliased int; -- /usr/include/X11/Xutil.h:92 win_gravity : aliased int; -- /usr/include/X11/Xutil.h:93 end record with Convention => C_Pass_By_Copy; -- /usr/include/X11/Xutil.h:94 -- obsolete for new window mgrs, but clients -- should set so old wm's don't mess up -- numerator -- denominator -- added by ICCCM version 1 -- added by ICCCM version 1 -- * The next block of definitions are for window manager properties that -- * clients and applications use for communication. -- -- flags argument in size hints -- obsolete -- marks which fields in this structure are defined -- skipped anonymous struct anon_99 type XWMHints is record flags : aliased long; -- /usr/include/X11/Xutil.h:120 input : aliased int; -- /usr/include/X11/Xutil.h:121 initial_state : aliased int; -- /usr/include/X11/Xutil.h:123 icon_pixmap : aliased X11.Pixmap; -- /usr/include/X11/Xutil.h:124 icon_window : aliased X11.Window; -- /usr/include/X11/Xutil.h:125 icon_x : aliased int; -- /usr/include/X11/Xutil.h:126 icon_y : aliased int; -- /usr/include/X11/Xutil.h:126 icon_mask : aliased X11.Pixmap; -- /usr/include/X11/Xutil.h:127 window_group : aliased X11.XID; -- /usr/include/X11/Xutil.h:128 end record with Convention => C_Pass_By_Copy; -- /usr/include/X11/Xutil.h:130 -- does this application rely on the window manager to -- get keyboard input? -- see below -- pixmap to be used as icon -- window to be used as icon -- initial position of icon -- icon mask bitmap -- id of related window group -- this structure may be extended in the future -- definition for flags of XWMHints -- definitions for initial window state -- * Obsolete states no longer defined by ICCCM -- -- some wm's may put it on inactive menu -- * new structure for manipulating TEXT properties; used with WM_NAME, -- * WM_ICON_NAME, WM_CLIENT_MACHINE, and WM_COMMAND. -- -- same as Property routines -- skipped anonymous struct anon_100 type XTextProperty is record value : access unsigned_char; -- /usr/include/X11/Xutil.h:164 encoding : aliased X11.Atom; -- /usr/include/X11/Xutil.h:165 format : aliased int; -- /usr/include/X11/Xutil.h:166 nitems : aliased unsigned_long; -- /usr/include/X11/Xutil.h:167 end record with Convention => C_Pass_By_Copy; -- /usr/include/X11/Xutil.h:168 -- prop type -- prop data format: 8, 16, or 32 -- number of data items in value -- STRING -- COMPOUND_TEXT -- text in owner's encoding (current locale) -- STRING, else COMPOUND_TEXT -- The following is an XFree86 extension, introduced in November 2000 -- UTF8_STRING type XICCEncodingStyle is (XStringStyle, XCompoundTextStyle, XTextStyle, XStdICCTextStyle, XUTF8StringStyle) with Convention => C; -- /usr/include/X11/Xutil.h:181 -- skipped anonymous struct anon_102 type XIconSize is record min_width : aliased int; -- /usr/include/X11/Xutil.h:184 min_height : aliased int; -- /usr/include/X11/Xutil.h:184 max_width : aliased int; -- /usr/include/X11/Xutil.h:185 max_height : aliased int; -- /usr/include/X11/Xutil.h:185 width_inc : aliased int; -- /usr/include/X11/Xutil.h:186 height_inc : aliased int; -- /usr/include/X11/Xutil.h:186 end record with Convention => C_Pass_By_Copy; -- /usr/include/X11/Xutil.h:187 -- skipped anonymous struct anon_103 type XClassHint is record res_name : Interfaces.C.Strings.chars_ptr; -- /usr/include/X11/Xutil.h:190 res_class : Interfaces.C.Strings.chars_ptr; -- /usr/include/X11/Xutil.h:191 end record with Convention => C_Pass_By_Copy; -- /usr/include/X11/Xutil.h:192 -- * These macros are used to give some sugar to the image routines so that -- * naive people are more comfortable with them. -- -- * Compose sequence status structure, used in calling XLookupString. -- -- state table pointer type u_XComposeStatus is record compose_ptr : Xlib.XPointer; -- /usr/include/X11/Xutil.h:232 chars_matched : aliased int; -- /usr/include/X11/Xutil.h:233 end record with Convention => C_Pass_By_Copy; -- /usr/include/X11/Xutil.h:231 -- match state subtype XComposeStatus is u_XComposeStatus; -- /usr/include/X11/Xutil.h:234 -- * Keysym macros, used on Keysyms to test for classes of symbols -- -- * opaque reference to Region data type -- type u_XRegion is null record; -- incomplete struct type Region is access all u_XRegion; -- /usr/include/X11/Xutil.h:273 -- Return values from XRectInRegion() -- * Information used by the visual utility routines to find desired visual -- * type from the many visuals a display may support. -- -- skipped anonymous struct anon_104 type XVisualInfo is record the_visual : access Xlib.Visual; -- /usr/include/X11/Xutil.h:288 the_visualid : aliased X11.VisualID; -- /usr/include/X11/Xutil.h:289 screen : aliased int; -- /usr/include/X11/Xutil.h:290 depth : aliased int; -- /usr/include/X11/Xutil.h:291 c_class : aliased int; -- /usr/include/X11/Xutil.h:293 red_mask : aliased unsigned_long; -- /usr/include/X11/Xutil.h:297 green_mask : aliased unsigned_long; -- /usr/include/X11/Xutil.h:298 blue_mask : aliased unsigned_long; -- /usr/include/X11/Xutil.h:299 colormap_size : aliased int; -- /usr/include/X11/Xutil.h:300 bits_per_rgb : aliased int; -- /usr/include/X11/Xutil.h:301 end record with Convention => C_Pass_By_Copy; -- /usr/include/X11/Xutil.h:302 -- C++ -- * This defines a window manager property that clients may use to -- * share standard color maps of type RGB_COLOR_MAP: -- -- skipped anonymous struct anon_105 type XStandardColormap is record the_colormap : aliased X11.Colormap; -- /usr/include/X11/Xutil.h:321 red_max : aliased unsigned_long; -- /usr/include/X11/Xutil.h:322 red_mult : aliased unsigned_long; -- /usr/include/X11/Xutil.h:323 green_max : aliased unsigned_long; -- /usr/include/X11/Xutil.h:324 green_mult : aliased unsigned_long; -- /usr/include/X11/Xutil.h:325 blue_max : aliased unsigned_long; -- /usr/include/X11/Xutil.h:326 blue_mult : aliased unsigned_long; -- /usr/include/X11/Xutil.h:327 base_pixel : aliased unsigned_long; -- /usr/include/X11/Xutil.h:328 the_visualid : aliased X11.VisualID; -- /usr/include/X11/Xutil.h:329 killid : aliased X11.XID; -- /usr/include/X11/Xutil.h:330 end record with Convention => C_Pass_By_Copy; -- /usr/include/X11/Xutil.h:331 -- added by ICCCM version 1 -- added by ICCCM version 1 -- * return codes for XReadBitmapFile and XWriteBitmapFile -- --*************************************************************** -- * -- * Context Management -- * -- *************************************************************** -- Associative lookup table return codes subtype XContext is int; -- /usr/include/X11/Xutil.h:357 -- The following declarations are alphabetized. function XAllocClassHint return access XClassHint -- /usr/include/X11/Xutil.h:366 with Import => True, Convention => C, External_Name => ""XAllocClassHint""; function XAllocIconSize return access XIconSize -- /usr/include/X11/Xutil.h:370 with Import => True, Convention => C, External_Name => ""XAllocIconSize""; function XAllocSizeHints return access XSizeHints -- /usr/include/X11/Xutil.h:374 with Import => True, Convention => C, External_Name => ""XAllocSizeHints""; function XAllocStandardColormap return access XStandardColormap -- /usr/include/X11/Xutil.h:378 with Import => True, Convention => C, External_Name => ""XAllocStandardColormap""; function XAllocWMHints return access XWMHints -- /usr/include/X11/Xutil.h:382 with Import => True, Convention => C, External_Name => ""XAllocWMHints""; function XClipBox (arg1 : Region; arg2 : access Xlib.XRectangle) return int -- /usr/include/X11/Xutil.h:386 with Import => True, Convention => C, External_Name => ""XClipBox""; -- r -- rect_return function XCreateRegion return Region -- /usr/include/X11/Xutil.h:391 with Import => True, Convention => C, External_Name => ""XCreateRegion""; function XDefaultString return Interfaces.C.Strings.chars_ptr -- /usr/include/X11/Xutil.h:395 with Import => True, Convention => C, External_Name => ""XDefaultString""; function XDeleteContext (arg1 : access Xlib.Display; arg2 : X11.XID; arg3 : XContext) return int -- /usr/include/X11/Xutil.h:397 with Import => True, Convention => C, External_Name => ""XDeleteContext""; -- display -- rid -- context function XDestroyRegion (arg1 : Region) return int -- /usr/include/X11/Xutil.h:403 with Import => True, Convention => C, External_Name => ""XDestroyRegion""; -- r function XEmptyRegion (arg1 : Region) return int -- /usr/include/X11/Xutil.h:407 with Import => True, Convention => C, External_Name => ""XEmptyRegion""; -- r function XEqualRegion (arg1 : Region; arg2 : Region) return int -- /usr/include/X11/Xutil.h:411 with Import => True, Convention => C, External_Name => ""XEqualRegion""; -- r1 -- r2 function XFindContext (arg1 : access Xlib.Display; arg2 : X11.XID; arg3 : XContext; arg4 : System.Address) return int -- /usr/include/X11/Xutil.h:416 with Import => True, Convention => C, External_Name => ""XFindContext""; -- display -- rid -- context -- data_return function XGetClassHint (arg1 : access Xlib.Display; arg2 : X11.Window; arg3 : access XClassHint) return int -- /usr/include/X11/Xutil.h:423 with Import => True, Convention => C, External_Name => ""XGetClassHint""; -- display -- w -- class_hints_return function XGetIconSizes (arg1 : access Xlib.Display; arg2 : X11.Window; arg3 : System.Address; arg4 : access int) return int -- /usr/include/X11/Xutil.h:429 with Import => True, Convention => C, External_Name => ""XGetIconSizes""; -- display -- w -- size_list_return -- count_return function XGetNormalHints (arg1 : access Xlib.Display; arg2 : X11.Window; arg3 : access XSizeHints) return int -- /usr/include/X11/Xutil.h:436 with Import => True, Convention => C, External_Name => ""XGetNormalHints""; -- display -- w -- hints_return function XGetRGBColormaps (arg1 : access Xlib.Display; arg2 : X11.Window; arg3 : System.Address; arg4 : access int; arg5 : X11.Atom) return int -- /usr/include/X11/Xutil.h:442 with Import => True, Convention => C, External_Name => ""XGetRGBColormaps""; -- display -- w -- stdcmap_return -- count_return -- property function XGetSizeHints (arg1 : access Xlib.Display; arg2 : X11.Window; arg3 : access XSizeHints; arg4 : X11.Atom) return int -- /usr/include/X11/Xutil.h:450 with Import => True, Convention => C, External_Name => ""XGetSizeHints""; -- display -- w -- hints_return -- property function XGetStandardColormap (arg1 : access Xlib.Display; arg2 : X11.Window; arg3 : access XStandardColormap; arg4 : X11.Atom) return int -- /usr/include/X11/Xutil.h:457 with Import => True, Convention => C, External_Name => ""XGetStandardColormap""; -- display -- w -- colormap_return -- property function XGetTextProperty (arg1 : access Xlib.Display; arg2 : X11.Window; arg3 : access XTextProperty; arg4 : X11.Atom) return int -- /usr/include/X11/Xutil.h:464 with Import => True, Convention => C, External_Name => ""XGetTextProperty""; -- display -- window -- text_prop_return -- property function XGetVisualInfo (arg1 : access Xlib.Display; arg2 : long; arg3 : access XVisualInfo; arg4 : access int) return access XVisualInfo -- /usr/include/X11/Xutil.h:471 with Import => True, Convention => C, External_Name => ""XGetVisualInfo""; -- display -- vinfo_mask -- vinfo_template -- nitems_return function XGetWMClientMachine (arg1 : access Xlib.Display; arg2 : X11.Window; arg3 : access XTextProperty) return int -- /usr/include/X11/Xutil.h:478 with Import => True, Convention => C, External_Name => ""XGetWMClientMachine""; -- display -- w -- text_prop_return function XGetWMHints (arg1 : access Xlib.Display; arg2 : X11.Window) return access XWMHints -- /usr/include/X11/Xutil.h:484 with Import => True, Convention => C, External_Name => ""XGetWMHints""; -- display -- w function XGetWMIconName (arg1 : access Xlib.Display; arg2 : X11.Window; arg3 : access XTextProperty) return int -- /usr/include/X11/Xutil.h:489 with Import => True, Convention => C, External_Name => ""XGetWMIconName""; -- display -- w -- text_prop_return function XGetWMName (arg1 : access Xlib.Display; arg2 : X11.Window; arg3 : access XTextProperty) return int -- /usr/include/X11/Xutil.h:495 with Import => True, Convention => C, External_Name => ""XGetWMName""; -- display -- w -- text_prop_return function XGetWMNormalHints (arg1 : access Xlib.Display; arg2 : X11.Window; arg3 : access XSizeHints; arg4 : access long) return int -- /usr/include/X11/Xutil.h:501 with Import => True, Convention => C, External_Name => ""XGetWMNormalHints""; -- display -- w -- hints_return -- supplied_return function XGetWMSizeHints (arg1 : access Xlib.Display; arg2 : X11.Window; arg3 : access XSizeHints; arg4 : access long; arg5 : X11.Atom) return int -- /usr/include/X11/Xutil.h:508 with Import => True, Convention => C, External_Name => ""XGetWMSizeHints""; -- display -- w -- hints_return -- supplied_return -- property function XGetZoomHints (arg1 : access Xlib.Display; arg2 : X11.Window; arg3 : access XSizeHints) return int -- /usr/include/X11/Xutil.h:516 with Import => True, Convention => C, External_Name => ""XGetZoomHints""; -- display -- w -- zhints_return function XIntersectRegion (arg1 : Region; arg2 : Region; arg3 : Region) return int -- /usr/include/X11/Xutil.h:522 with Import => True, Convention => C, External_Name => ""XIntersectRegion""; -- sra -- srb -- dr_return procedure XConvertCase (arg1 : X11.KeySym; arg2 : access X11.KeySym; arg3 : access X11.KeySym) -- /usr/include/X11/Xutil.h:528 with Import => True, Convention => C, External_Name => ""XConvertCase""; -- sym -- lower -- upper function XLookupString (arg1 : access Xlib.XKeyEvent; arg2 : Interfaces.C.Strings.chars_ptr; arg3 : int; arg4 : access X11.KeySym; arg5 : access XComposeStatus) return int -- /usr/include/X11/Xutil.h:534 with Import => True, Convention => C, External_Name => ""XLookupString""; -- event_struct -- buffer_return -- bytes_buffer -- keysym_return -- status_in_out function XMatchVisualInfo (arg1 : access Xlib.Display; arg2 : int; arg3 : int; arg4 : int; arg5 : access XVisualInfo) return int -- /usr/include/X11/Xutil.h:542 with Import => True, Convention => C, External_Name => ""XMatchVisualInfo""; -- display -- screen -- depth -- class -- vinfo_return function XOffsetRegion (arg1 : Region; arg2 : int; arg3 : int) return int -- /usr/include/X11/Xutil.h:550 with Import => True, Convention => C, External_Name => ""XOffsetRegion""; -- r -- dx -- dy function XPointInRegion (arg1 : Region; arg2 : int; arg3 : int) return int -- /usr/include/X11/Xutil.h:556 with Import => True, Convention => C, External_Name => ""XPointInRegion""; -- r -- x -- y function XPolygonRegion (arg1 : access Xlib.XPoint; arg2 : int; arg3 : int) return Region -- /usr/include/X11/Xutil.h:562 with Import => True, Convention => C, External_Name => ""XPolygonRegion""; -- points -- n -- fill_rule function XRectInRegion (arg1 : Region; arg2 : int; arg3 : int; arg4 : unsigned; arg5 : unsigned) return int -- /usr/include/X11/Xutil.h:568 with Import => True, Convention => C, External_Name => ""XRectInRegion""; -- r -- x -- y -- width -- height function XSaveContext (arg1 : access Xlib.Display; arg2 : X11.XID; arg3 : XContext; arg4 : Interfaces.C.Strings.chars_ptr) return int -- /usr/include/X11/Xutil.h:576 with Import => True, Convention => C, External_Name => ""XSaveContext""; -- display -- rid -- context -- data function XSetClassHint (arg1 : access Xlib.Display; arg2 : X11.Window; arg3 : access XClassHint) return int -- /usr/include/X11/Xutil.h:583 with Import => True, Convention => C, External_Name => ""XSetClassHint""; -- display -- w -- class_hints function XSetIconSizes (arg1 : access Xlib.Display; arg2 : X11.Window; arg3 : access XIconSize; arg4 : int) return int -- /usr/include/X11/Xutil.h:589 with Import => True, Convention => C, External_Name => ""XSetIconSizes""; -- display -- w -- size_list -- count function XSetNormalHints (arg1 : access Xlib.Display; arg2 : X11.Window; arg3 : access XSizeHints) return int -- /usr/include/X11/Xutil.h:596 with Import => True, Convention => C, External_Name => ""XSetNormalHints""; -- display -- w -- hints procedure XSetRGBColormaps (arg1 : access Xlib.Display; arg2 : X11.Window; arg3 : access XStandardColormap; arg4 : int; arg5 : X11.Atom) -- /usr/include/X11/Xutil.h:602 with Import => True, Convention => C, External_Name => ""XSetRGBColormaps""; -- display -- w -- stdcmaps -- count -- property function XSetSizeHints (arg1 : access Xlib.Display; arg2 : X11.Window; arg3 : access XSizeHints; arg4 : X11.Atom) return int -- /usr/include/X11/Xutil.h:610 with Import => True, Convention => C, External_Name => ""XSetSizeHints""; -- display -- w -- hints -- property function XSetStandardProperties (arg1 : access Xlib.Display; arg2 : X11.Window; arg3 : Interfaces.C.Strings.chars_ptr; arg4 : Interfaces.C.Strings.chars_ptr; arg5 : X11.Pixmap; arg6 : System.Address; arg7 : int; arg8 : access XSizeHints) return int -- /usr/include/X11/Xutil.h:617 with Import => True, Convention => C, External_Name => ""XSetStandardProperties""; -- display -- w -- window_name -- icon_name -- icon_pixmap -- argv -- argc -- hints procedure XSetTextProperty (arg1 : access Xlib.Display; arg2 : X11.Window; arg3 : access XTextProperty; arg4 : X11.Atom) -- /usr/include/X11/Xutil.h:628 with Import => True, Convention => C, External_Name => ""XSetTextProperty""; -- display -- w -- text_prop -- property procedure XSetWMClientMachine (arg1 : access Xlib.Display; arg2 : X11.Window; arg3 : access XTextProperty) -- /usr/include/X11/Xutil.h:635 with Import => True, Convention => C, External_Name => ""XSetWMClientMachine""; -- display -- w -- text_prop function XSetWMHints (arg1 : access Xlib.Display; arg2 : X11.Window; arg3 : access XWMHints) return int -- /usr/include/X11/Xutil.h:641 with Import => True, Convention => C, External_Name => ""XSetWMHints""; -- display -- w -- wm_hints procedure XSetWMIconName (arg1 : access Xlib.Display; arg2 : X11.Window; arg3 : access XTextProperty) -- /usr/include/X11/Xutil.h:647 with Import => True, Convention => C, External_Name => ""XSetWMIconName""; -- display -- w -- text_prop procedure XSetWMName (arg1 : access Xlib.Display; arg2 : X11.Window; arg3 : access XTextProperty) -- /usr/include/X11/Xutil.h:653 with Import => True, Convention => C, External_Name => ""XSetWMName""; -- display -- w -- text_prop procedure XSetWMNormalHints (arg1 : access Xlib.Display; arg2 : X11.Window; arg3 : access XSizeHints) -- /usr/include/X11/Xutil.h:659 with Import => True, Convention => C, External_Name => ""XSetWMNormalHints""; -- display -- w -- hints procedure XSetWMProperties (arg1 : access Xlib.Display; arg2 : X11.Window; arg3 : access XTextProperty; arg4 : access XTextProperty; arg5 : System.Address; arg6 : int; arg7 : access XSizeHints; arg8 : access XWMHints; arg9 : access XClassHint) -- /usr/include/X11/Xutil.h:665 with Import => True, Convention => C, External_Name => ""XSetWMProperties""; -- display -- w -- window_name -- icon_name -- argv -- argc -- normal_hints -- wm_hints -- class_hints procedure XmbSetWMProperties (arg1 : access Xlib.Display; arg2 : X11.Window; arg3 : Interfaces.C.Strings.chars_ptr; arg4 : Interfaces.C.Strings.chars_ptr; arg5 : System.Address; arg6 : int; arg7 : access XSizeHints; arg8 : access XWMHints; arg9 : access XClassHint) -- /usr/include/X11/Xutil.h:677 with Import => True, Convention => C, External_Name => ""XmbSetWMProperties""; -- display -- w -- window_name -- icon_name -- argv -- argc -- normal_hints -- wm_hints -- class_hints procedure Xutf8SetWMProperties (arg1 : access Xlib.Display; arg2 : X11.Window; arg3 : Interfaces.C.Strings.chars_ptr; arg4 : Interfaces.C.Strings.chars_ptr; arg5 : System.Address; arg6 : int; arg7 : access XSizeHints; arg8 : access XWMHints; arg9 : access XClassHint) -- /usr/include/X11/Xutil.h:689 with Import => True, Convention => C, External_Name => ""Xutf8SetWMProperties""; -- display -- w -- window_name -- icon_name -- argv -- argc -- normal_hints -- wm_hints -- class_hints procedure XSetWMSizeHints (arg1 : access Xlib.Display; arg2 : X11.Window; arg3 : access XSizeHints; arg4 : X11.Atom) -- /usr/include/X11/Xutil.h:701 with Import => True, Convention => C, External_Name => ""XSetWMSizeHints""; -- display -- w -- hints -- property function XSetRegion (arg1 : access Xlib.Display; arg2 : Xlib.GC; arg3 : Region) return int -- /usr/include/X11/Xutil.h:708 with Import => True, Convention => C, External_Name => ""XSetRegion""; -- display -- gc -- r procedure XSetStandardColormap (arg1 : access Xlib.Display; arg2 : X11.Window; arg3 : access XStandardColormap; arg4 : X11.Atom) -- /usr/include/X11/Xutil.h:714 with Import => True, Convention => C, External_Name => ""XSetStandardColormap""; -- display -- w -- colormap -- property function XSetZoomHints (arg1 : access Xlib.Display; arg2 : X11.Window; arg3 : access XSizeHints) return int -- /usr/include/X11/Xutil.h:721 with Import => True, Convention => C, External_Name => ""XSetZoomHints""; -- display -- w -- zhints function XShrinkRegion (arg1 : Region; arg2 : int; arg3 : int) return int -- /usr/include/X11/Xutil.h:727 with Import => True, Convention => C, External_Name => ""XShrinkRegion""; -- r -- dx -- dy function XStringListToTextProperty (arg1 : System.Address; arg2 : int; arg3 : access XTextProperty) return int -- /usr/include/X11/Xutil.h:733 with Import => True, Convention => C, External_Name => ""XStringListToTextProperty""; -- list -- count -- text_prop_return function XSubtractRegion (arg1 : Region; arg2 : Region; arg3 : Region) return int -- /usr/include/X11/Xutil.h:739 with Import => True, Convention => C, External_Name => ""XSubtractRegion""; -- sra -- srb -- dr_return function XmbTextListToTextProperty (the_display : access Xlib.Display; list : System.Address; count : int; style : XICCEncodingStyle; text_prop_return : access XTextProperty) return int -- /usr/include/X11/Xutil.h:745 with Import => True, Convention => C, External_Name => ""XmbTextListToTextProperty""; function XwcTextListToTextProperty (the_display : access Xlib.Display; list : System.Address; count : int; style : XICCEncodingStyle; text_prop_return : access XTextProperty) return int -- /usr/include/X11/Xutil.h:753 with Import => True, Convention => C, External_Name => ""XwcTextListToTextProperty""; function Xutf8TextListToTextProperty (the_display : access Xlib.Display; list : System.Address; count : int; style : XICCEncodingStyle; text_prop_return : access XTextProperty) return int -- /usr/include/X11/Xutil.h:761 with Import => True, Convention => C, External_Name => ""Xutf8TextListToTextProperty""; procedure XwcFreeStringList (list : System.Address) -- /usr/include/X11/Xutil.h:769 with Import => True, Convention => C, External_Name => ""XwcFreeStringList""; function XTextPropertyToStringList (arg1 : access XTextProperty; arg2 : System.Address; arg3 : access int) return int -- /usr/include/X11/Xutil.h:773 with Import => True, Convention => C, External_Name => ""XTextPropertyToStringList""; -- text_prop -- list_return -- count_return function XmbTextPropertyToTextList (the_display : access Xlib.Display; text_prop : access constant XTextProperty; list_return : System.Address; count_return : access int) return int -- /usr/include/X11/Xutil.h:779 with Import => True, Convention => C, External_Name => ""XmbTextPropertyToTextList""; function XwcTextPropertyToTextList (the_display : access Xlib.Display; text_prop : access constant XTextProperty; list_return : System.Address; count_return : access int) return int -- /usr/include/X11/Xutil.h:786 with Import => True, Convention => C, External_Name => ""XwcTextPropertyToTextList""; function Xutf8TextPropertyToTextList (the_display : access Xlib.Display; text_prop : access constant XTextProperty; list_return : System.Address; count_return : access int) return int -- /usr/include/X11/Xutil.h:793 with Import => True, Convention => C, External_Name => ""Xutf8TextPropertyToTextList""; function XUnionRectWithRegion (arg1 : access Xlib.XRectangle; arg2 : Region; arg3 : Region) return int -- /usr/include/X11/Xutil.h:800 with Import => True, Convention => C, External_Name => ""XUnionRectWithRegion""; -- rectangle -- src_region -- dest_region_return function XUnionRegion (arg1 : Region; arg2 : Region; arg3 : Region) return int -- /usr/include/X11/Xutil.h:806 with Import => True, Convention => C, External_Name => ""XUnionRegion""; -- sra -- srb -- dr_return function XWMGeometry (arg1 : access Xlib.Display; arg2 : int; arg3 : Interfaces.C.Strings.chars_ptr; arg4 : Interfaces.C.Strings.chars_ptr; arg5 : unsigned; arg6 : access XSizeHints; arg7 : access int; arg8 : access int; arg9 : access int; arg10 : access int; arg11 : access int) return int -- /usr/include/X11/Xutil.h:812 with Import => True, Convention => C, External_Name => ""XWMGeometry""; -- display -- screen_number -- user_geometry -- default_geometry -- border_width -- hints -- x_return -- y_return -- width_return -- height_return -- gravity_return function XXorRegion (arg1 : Region; arg2 : Region; arg3 : Region) return int -- /usr/include/X11/Xutil.h:826 with Import => True, Convention => C, External_Name => ""XXorRegion""; -- sra -- srb -- dr_return end Xutil; ",12330,False,2403.8117731014254,median "------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- E R R O U T C -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2020, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING3. If not, go to -- -- http://www.gnu.org/licenses for a complete copy of the license. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- Warning: Error messages can be generated during Gigi processing by direct -- calls to error message routines, so it is essential that the processing -- in this body be consistent with the requirements for the Gigi processing -- environment, and that in particular, no disallowed table expansion is -- allowed to occur. with Atree; use Atree; with Casing; use Casing; with Csets; use Csets; with Debug; use Debug; with Err_Vars; use Err_Vars; with Fname; use Fname; with Namet; use Namet; with Opt; use Opt; with Output; use Output; with Sinput; use Sinput; with Snames; use Snames; with Stringt; use Stringt; with Targparm; with Uintp; use Uintp; with Widechar; use Widechar; package body Erroutc is ----------------------- -- Local Subprograms -- ----------------------- function Matches (S : String; P : String) return Boolean; -- Returns true if the String S matches the pattern P, which can contain -- wildcard chars (*). The entire pattern must match the entire string. -- Case is ignored in the comparison (so X matches x). function Sloc_In_Range (Loc, Start, Stop : Source_Ptr) return Boolean; -- Return whether Loc is in the range Start .. Stop, taking instantiation -- locations of Loc into account. This is useful for suppressing warnings -- from generic instantiations by using pragma Warnings around generic -- instances, as needed in GNATprove. --------------- -- Add_Class -- --------------- procedure Add_Class is begin if Class_Flag then Class_Flag := False; Set_Msg_Char ('''); Get_Name_String (Name_Class); Set_Casing (Identifier_Casing (Flag_Source)); Set_Msg_Name_Buffer; end if; end Add_Class; ---------------------- -- Buffer_Ends_With -- ---------------------- function Buffer_Ends_With (C : Character) return Boolean is begin return Msglen > 0 and then Msg_Buffer (Msglen) = C; end Buffer_Ends_With; function Buffer_Ends_With (S : String) return Boolean is Len : constant Natural := S'Length; begin return Msglen > Len and then Msg_Buffer (Msglen - Len) = ' ' and then Msg_Buffer (Msglen - Len + 1 .. Msglen) = S; end Buffer_Ends_With; ------------------- -- Buffer_Remove -- ------------------- procedure Buffer_Remove (C : Character) is begin if Buffer_Ends_With (C) then Msglen := Msglen - 1; end if; end Buffer_Remove; procedure Buffer_Remove (S : String) is begin if Buffer_Ends_With (S) then Msglen := Msglen - S'Length; end if; end Buffer_Remove; ----------------------------- -- Check_Duplicate_Message -- ----------------------------- procedure Check_Duplicate_Message (M1, M2 : Error_Msg_Id) is L1, L2 : Error_Msg_Id; N1, N2 : Error_Msg_Id; procedure Delete_Msg (Delete, Keep : Error_Msg_Id); -- Called to delete message Delete, keeping message Keep. Marks msg -- Delete and all its continuations with deleted flag set to True. -- Also makes sure that for the error messages that are retained the -- preferred message is the one retained (we prefer the shorter one in -- the case where one has an Instance tag). Note that we always know -- that Keep has at least as many continuations as Delete (since we -- always delete the shorter sequence). ---------------- -- Delete_Msg -- ---------------- procedure Delete_Msg (Delete, Keep : Error_Msg_Id) is D, K : Error_Msg_Id; begin D := Delete; K := Keep; loop Errors.Table (D).Deleted := True; -- Adjust error message count if Errors.Table (D).Info then if Errors.Table (D).Warn then Warning_Info_Messages := Warning_Info_Messages - 1; Warnings_Detected := Warnings_Detected - 1; else Report_Info_Messages := Report_Info_Messages - 1; end if; elsif Errors.Table (D).Warn or else Errors.Table (D).Style then Warnings_Detected := Warnings_Detected - 1; -- Note: we do not need to decrement Warnings_Treated_As_Errors -- because this only gets incremented if we actually output the -- message, which we won't do if we are deleting it here! elsif Errors.Table (D).Check then Check_Messages := Check_Messages - 1; else Total_Errors_Detected := Total_Errors_Detected - 1; if Errors.Table (D).Serious then Serious_Errors_Detected := Serious_Errors_Detected - 1; end if; end if; -- Substitute shorter of the two error messages if Errors.Table (K).Text'Length > Errors.Table (D).Text'Length then Errors.Table (K).Text := Errors.Table (D).Text; end if; D := Errors.Table (D).Next; K := Errors.Table (K).Next; if D = No_Error_Msg or else not Errors.Table (D).Msg_Cont then return; end if; end loop; end Delete_Msg; -- Start of processing for Check_Duplicate_Message begin -- Both messages must be non-continuation messages and not deleted if Errors.Table (M1).Msg_Cont or else Errors.Table (M2).Msg_Cont or else Errors.Table (M1).Deleted or else Errors.Table (M2).Deleted then return; end if; -- Definitely not equal if message text does not match if not Same_Error (M1, M2) then return; end if; -- Same text. See if all continuations are also identical L1 := M1; L2 := M2; loop N1 := Errors.Table (L1).Next; N2 := Errors.Table (L2).Next; -- If M1 continuations have run out, we delete M1, either the -- messages have the same number of continuations, or M2 has -- more and we prefer the one with more anyway. if N1 = No_Error_Msg or else not Errors.Table (N1).Msg_Cont then Delete_Msg (M1, M2); return; -- If M2 continuations have run out, we delete M2 elsif N2 = No_Error_Msg or else not Errors.Table (N2).Msg_Cont then Delete_Msg (M2, M1); return; -- Otherwise see if continuations are the same, if not, keep both -- sequences, a curious case, but better to keep everything. elsif not Same_Error (N1, N2) then return; -- If continuations are the same, continue scan else L1 := N1; L2 := N2; end if; end loop; end Check_Duplicate_Message; ------------------------ -- Compilation_Errors -- ------------------------ function Compilation_Errors return Boolean is Warnings_Count : constant Int := Warnings_Detected - Warning_Info_Messages; begin if Total_Errors_Detected /= 0 then return True; elsif Warnings_Treated_As_Errors /= 0 then return True; -- We should never treat warnings that originate from a -- Compile_Time_Warning pragma as an error. Warnings_Count is the sum -- of both ""normal"" and Compile_Time_Warning warnings. This means that -- there are only one or more non-Compile_Time_Warning warnings when -- Warnings_Count is greater than Count_Compile_Time_Pragma_Warnings. elsif Warning_Mode = Treat_As_Error and then Warnings_Count > Count_Compile_Time_Pragma_Warnings then return True; end if; return False; end Compilation_Errors; ---------------------------------------- -- Count_Compile_Time_Pragma_Warnings -- ---------------------------------------- function Count_Compile_Time_Pragma_Warnings return Int is Result : Int := 0; begin for J in 1 .. Errors.Last loop begin if Errors.Table (J).Warn and Errors.Table (J).Compile_Time_Pragma then Result := Result + 1; end if; end; end loop; return Result; end Count_Compile_Time_Pragma_Warnings; ------------------ -- Debug_Output -- ------------------ procedure Debug_Output (N : Node_Id) is begin if Debug_Flag_1 then Write_Str (""*** following error message posted on node id = #""); Write_Int (Int (N)); Write_Str ("" ***""); Write_Eol; end if; end Debug_Output; ---------- -- dmsg -- ---------- procedure dmsg (Id : Error_Msg_Id) is E : Error_Msg_Object renames Errors.Table (Id); begin w (""Dumping error message, Id = "", Int (Id)); w ("" Text = "", E.Text.all); w ("" Next = "", Int (E.Next)); w ("" Prev = "", Int (E.Prev)); w ("" Sfile = "", Int (E.Sfile)); Write_Str ("" Sptr = ""); Write_Location (E.Sptr); Write_Eol; Write_Str ("" Optr = ""); Write_Location (E.Optr); Write_Eol; w ("" Line = "", Int (E.Line)); w ("" Col = "", Int (E.Col)); w ("" Warn = "", E.Warn); w ("" Warn_Err = "", E.Warn_Err); w ("" Warn_Chr = '"" & E.Warn_Chr & '''); w ("" Style = "", E.Style); w ("" Serious = "", E.Serious); w ("" Uncond = "", E.Uncond); w ("" Msg_Cont = "", E.Msg_Cont); w ("" Deleted = "", E.Deleted); w ("" Node = "", Int (E.Node)); Write_Eol; end dmsg; ------------------ -- Get_Location -- ------------------ function Get_Location (E : Error_Msg_Id) return Source_Ptr is begin return Errors.Table (E).Sptr; end Get_Location; ---------------- -- Get_Msg_Id -- ---------------- function Get_Msg_Id return Error_Msg_Id is begin return Cur_Msg; end Get_Msg_Id; --------------------- -- Get_Warning_Tag -- --------------------- function Get_Warning_Tag (Id : Error_Msg_Id) return String is Warn : constant Boolean := Errors.Table (Id).Warn; Warn_Chr : constant Character := Errors.Table (Id).Warn_Chr; begin if Warn and then Warn_Chr /= ' ' then if Warn_Chr = '?' then return ""[enabled by default]""; elsif Warn_Chr = '*' then return ""[restriction warning]""; elsif Warn_Chr = '$' then return ""[-gnatel]""; elsif Warn_Chr in 'a' .. 'z' then return ""[-gnatw"" & Warn_Chr & ']'; else pragma Assert (Warn_Chr in 'A' .. 'Z'); return ""[-gnatw."" & Fold_Lower (Warn_Chr) & ']'; end if; else return """"; end if; end Get_Warning_Tag; ------------- -- Matches -- ------------- function Matches (S : String; P : String) return Boolean is Slast : constant Natural := S'Last; PLast : constant Natural := P'Last; SPtr : Natural := S'First; PPtr : Natural := P'First; begin -- Loop advancing through characters of string and pattern SPtr := S'First; PPtr := P'First; loop -- Return True if pattern is a single asterisk if PPtr = PLast and then P (PPtr) = '*' then return True; -- Return True if both pattern and string exhausted elsif PPtr > PLast and then SPtr > Slast then return True; -- Return False, if one exhausted and not the other elsif PPtr > PLast or else SPtr > Slast then return False; -- Case where pattern starts with asterisk elsif P (PPtr) = '*' then -- Try all possible starting positions in S for match with the -- remaining characters of the pattern. This is the recursive -- call that implements the scanner backup. for J in SPtr .. Slast loop if Matches (S (J .. Slast), P (PPtr + 1 .. PLast)) then return True; end if; end loop; return False; -- Dealt with end of string and *, advance if we have a match elsif Fold_Lower (S (SPtr)) = Fold_Lower (P (PPtr)) then SPtr := SPtr + 1; PPtr := PPtr + 1; -- If first characters do not match, that's decisive else return False; end if; end loop; end Matches; ----------------------- -- Output_Error_Msgs -- ----------------------- procedure Output_Error_Msgs (E : in out Error_Msg_Id) is P : Source_Ptr; T : Error_Msg_Id; S : Error_Msg_Id; Flag_Num : Pos; Mult_Flags : Boolean := False; begin S := E; -- Skip deleted messages at start if Errors.Table (S).Deleted then Set_Next_Non_Deleted_Msg (S); end if; -- Figure out if we will place more than one error flag on this line T := S; while T /= No_Error_Msg and then Errors.Table (T).Line = Errors.Table (E).Line and then Errors.Table (T).Sfile = Errors.Table (E).Sfile loop if Errors.Table (T).Sptr > Errors.Table (E).Sptr then Mult_Flags := True; end if; Set_Next_Non_Deleted_Msg (T); end loop; -- Output the error flags. The circuit here makes sure that the tab -- characters in the original line are properly accounted for. The -- eight blanks at the start are to match the line number. if not Debug_Flag_2 then Write_Str ("" ""); P := Line_Start (Errors.Table (E).Sptr); Flag_Num := 1; -- Loop through error messages for this line to place flags T := S; while T /= No_Error_Msg and then Errors.Table (T).Line = Errors.Table (E).Line and then Errors.Table (T).Sfile = Errors.Table (E).Sfile loop declare Src : Source_Buffer_Ptr renames Source_Text (Errors.Table (T).Sfile); begin -- Loop to output blanks till current flag position while P < Errors.Table (T).Sptr loop -- Horizontal tab case, just echo the tab if Src (P) = ASCII.HT then Write_Char (ASCII.HT); P := P + 1; -- Deal with wide character case, but don't include brackets -- notation in this circuit, since we know that this will -- display unencoded (no one encodes brackets notation). elsif Src (P) /= '[' and then Is_Start_Of_Wide_Char (Src, P) then Skip_Wide (Src, P); Write_Char (' '); -- Normal non-wide character case (or bracket) else P := P + 1; Write_Char (' '); end if; end loop; -- Output flag (unless already output, this happens if more -- than one error message occurs at the same flag position). if P = Errors.Table (T).Sptr then if (Flag_Num = 1 and then not Mult_Flags) or else Flag_Num > 9 then Write_Char ('|'); else Write_Char (Character'Val (Character'Pos ('0') + Flag_Num)); end if; -- Skip past the corresponding source text character -- Horizontal tab case, we output a flag at the tab position -- so now we output a tab to match up with the text. if Src (P) = ASCII.HT then Write_Char (ASCII.HT); P := P + 1; -- Skip wide character other than left bracket elsif Src (P) /= '[' and then Is_Start_Of_Wide_Char (Src, P) then Skip_Wide (Src, P); -- Skip normal non-wide character case (or bracket) else P := P + 1; end if; end if; end; Set_Next_Non_Deleted_Msg (T); Flag_Num := Flag_Num + 1; end loop; Write_Eol; end if; -- Now output the error messages T := S; while T /= No_Error_Msg and then Errors.Table (T).Line = Errors.Table (E).Line and then Errors.Table (T).Sfile = Errors.Table (E).Sfile loop Write_Str ("" >>> ""); Output_Msg_Text (T); if Debug_Flag_2 then while Column < 74 loop Write_Char (' '); end loop; Write_Str ("" <<<""); end if; Write_Eol; Set_Next_Non_Deleted_Msg (T); end loop; E := T; end Output_Error_Msgs; ------------------------ -- Output_Line_Number -- ------------------------ procedure Output_Line_Number (L : Logical_Line_Number) is D : Int; -- next digit C : Character; -- next character Z : Boolean; -- flag for zero suppress N, M : Int; -- temporaries begin if L = No_Line_Number then Write_Str ("" ""); else Z := False; N := Int (L); M := 100_000; while M /= 0 loop D := Int (N / M); N := N rem M; M := M / 10; if D = 0 then if Z then C := '0'; else C := ' '; end if; else Z := True; C := Character'Val (D + 48); end if; Write_Char (C); end loop; Write_Str ("". ""); end if; end Output_Line_Number; --------------------- -- Output_Msg_Text -- --------------------- procedure Output_Msg_Text (E : Error_Msg_Id) is Offs : constant Nat := Column - 1; -- Offset to start of message, used for continuations Max : Integer; -- Maximum characters to output on next line Length : Nat; -- Maximum total length of lines E_Msg : Error_Msg_Object renames Errors.Table (E); Text : constant String_Ptr := E_Msg.Text; Ptr : Natural; Split : Natural; Start : Natural; Tag : constant String := Get_Warning_Tag (E); Txt : String_Ptr; Len : Natural; begin -- Postfix warning tag to message if needed if Tag /= """" and then Warning_Doc_Switch then if Include_Subprogram_In_Messages then Txt := new String' (Subprogram_Name_Ptr (E_Msg.Node) & "": "" & Text.all & ' ' & Tag); else Txt := new String'(Text.all & ' ' & Tag); end if; elsif Include_Subprogram_In_Messages and then (E_Msg.Warn or else E_Msg.Style) then Txt := new String'(Subprogram_Name_Ptr (E_Msg.Node) & "": "" & Text.all); else Txt := Text; end if; -- If -gnatdF is used, continuation messages follow the main message -- with only an indentation of two space characters, without repeating -- any prefix. if Debug_Flag_FF and then E_Msg.Msg_Cont then null; -- For info messages, prefix message with ""info: "" elsif E_Msg.Info then Txt := new String'(""info: "" & Txt.all); -- Warning treated as error elsif E_Msg.Warn_Err then -- We prefix with ""error:"" rather than warning: and postfix -- [warning-as-error] at the end. Warnings_Treated_As_Errors := Warnings_Treated_As_Errors + 1; Txt := new String'(""error: "" & Txt.all & "" [warning-as-error]""); -- Normal warning, prefix with ""warning: "" elsif E_Msg.Warn then Txt := new String'(""warning: "" & Txt.all); -- No prefix needed for style message, ""(style)"" is there already elsif E_Msg.Style then null; -- No prefix needed for check message, severity is there already elsif E_Msg.Check then null; -- All other cases, add ""error: "" if unique error tag set elsif Opt.Unique_Error_Tag then Txt := new String'(""error: "" & Txt.all); end if; -- Set error message line length and length of message if Error_Msg_Line_Length = 0 then Length := Nat'Last; else Length := Error_Msg_Line_Length; end if; Max := Integer (Length - Column + 1); Len := Txt'Length; -- Here we have to split the message up into multiple lines Ptr := 1; loop -- Make sure we do not have ludicrously small line Max := Integer'Max (Max, 20); -- If remaining text fits, output it respecting LF and we are done if Len - Ptr < Max then for J in Ptr .. Len loop if Txt (J) = ASCII.LF then Write_Eol; Write_Spaces (Offs); else Write_Char (Txt (J)); end if; end loop; return; -- Line does not fit else Start := Ptr; -- First scan forward looking for a hard end of line for Scan in Ptr .. Ptr + Max - 1 loop if Txt (Scan) = ASCII.LF then Split := Scan - 1; Ptr := Scan + 1; goto Continue; end if; end loop; -- Otherwise scan backwards looking for a space for Scan in reverse Ptr .. Ptr + Max - 1 loop if Txt (Scan) = ' ' then Split := Scan - 1; Ptr := Scan + 1; goto Continue; end if; end loop; -- If we fall through, no space, so split line arbitrarily Split := Ptr + Max - 1; Ptr := Split + 1; end if; <> if Start <= Split then Write_Line (Txt (Start .. Split)); Write_Spaces (Offs); end if; Max := Integer (Length - Column + 1); end loop; end Output_Msg_Text; --------------------- -- Prescan_Message -- --------------------- procedure Prescan_Message (Msg : String) is J : Natural; begin -- Nothing to do for continuation line, unless -gnatdF is set if not Debug_Flag_FF and then Msg (Msg'First) = '\\' then return; -- Some global variables are not set for continuation messages, as they -- only make sense for the initial mesage. elsif Msg (Msg'First) /= '\\' then -- Set initial values of globals (may be changed during scan) Is_Serious_Error := True; Is_Unconditional_Msg := False; Is_Warning_Msg := False; -- Check style message Is_Style_Msg := Msg'Length > 7 and then Msg (Msg'First .. Msg'First + 6) = ""(style)""; -- Check info message Is_Info_Msg := Msg'Length > 6 and then Msg (Msg'First .. Msg'First + 5) = ""info: ""; -- Check check message Is_Check_Msg := (Msg'Length > 8 and then Msg (Msg'First .. Msg'First + 7) = ""medium: "") or else (Msg'Length > 6 and then Msg (Msg'First .. Msg'First + 5) = ""high: "") or else (Msg'Length > 5 and then Msg (Msg'First .. Msg'First + 4) = ""low: ""); end if; Has_Double_Exclam := False; Has_Insertion_Line := False; -- Loop through message looking for relevant insertion sequences J := Msg'First; while J <= Msg'Last loop -- If we have a quote, don't look at following character if Msg (J) = ''' then J := J + 2; -- Warning message (? or < insertion sequence) elsif Msg (J) = '?' or else Msg (J) = '<' then Is_Warning_Msg := Msg (J) = '?' or else Error_Msg_Warn; Warning_Msg_Char := ' '; J := J + 1; if Is_Warning_Msg then declare C : constant Character := Msg (J - 1); begin if J <= Msg'Last then if Msg (J) = C then Warning_Msg_Char := '?'; J := J + 1; elsif J < Msg'Last and then Msg (J + 1) = C and then (Msg (J) in 'a' .. 'z' or else Msg (J) in 'A' .. 'Z' or else Msg (J) = '*' or else Msg (J) = '$') then Warning_Msg_Char := Msg (J); J := J + 2; end if; end if; end; end if; -- Bomb if untagged warning message. This code can be uncommented -- for debugging when looking for untagged warning messages. -- if Is_Warning_Msg and then Warning_Msg_Char = ' ' then -- raise Program_Error; -- end if; -- Unconditional message (! insertion) elsif Msg (J) = '!' then Is_Unconditional_Msg := True; J := J + 1; if J <= Msg'Last and then Msg (J) = '!' then Has_Double_Exclam := True; J := J + 1; end if; -- Insertion line (# insertion) elsif Msg (J) = '#' then Has_Insertion_Line := True; J := J + 1; -- Non-serious error (| insertion) elsif Msg (J) = '|' then Is_Serious_Error := False; J := J + 1; else J := J + 1; end if; end loop; if Is_Info_Msg or Is_Warning_Msg or Is_Style_Msg or Is_Check_Msg then Is_Serious_Error := False; end if; end Prescan_Message; -------------------- -- Purge_Messages -- -------------------- procedure Purge_Messages (From : Source_Ptr; To : Source_Ptr) is E : Error_Msg_Id; function To_Be_Purged (E : Error_Msg_Id) return Boolean; -- Returns True for a message that is to be purged. Also adjusts -- error counts appropriately. ------------------ -- To_Be_Purged -- ------------------ function To_Be_Purged (E : Error_Msg_Id) return Boolean is begin if E /= No_Error_Msg and then Errors.Table (E).Sptr > From and then Errors.Table (E).Sptr < To then if Errors.Table (E).Warn or else Errors.Table (E).Style then Warnings_Detected := Warnings_Detected - 1; else Total_Errors_Detected := Total_Errors_Detected - 1; if Errors.Table (E).Serious then Serious_Errors_Detected := Serious_Errors_Detected - 1; end if; end if; return True; else return False; end if; end To_Be_Purged; -- Start of processing for Purge_Messages begin while To_Be_Purged (First_Error_Msg) loop First_Error_Msg := Errors.Table (First_Error_Msg).Next; end loop; E := First_Error_Msg; while E /= No_Error_Msg loop while To_Be_Purged (Errors.Table (E).Next) loop Errors.Table (E).Next := Errors.Table (Errors.Table (E).Next).Next; end loop; E := Errors.Table (E).Next; end loop; end Purge_Messages; ---------------- -- Same_Error -- ---------------- function Same_Error (M1, M2 : Error_Msg_Id) return Boolean is Msg1 : constant String_Ptr := Errors.Table (M1).Text; Msg2 : constant String_Ptr := Errors.Table (M2).Text; Msg2_Len : constant Integer := Msg2'Length; Msg1_Len : constant Integer := Msg1'Length; begin return Msg1.all = Msg2.all or else (Msg1_Len - 10 > Msg2_Len and then Msg2.all = Msg1.all (1 .. Msg2_Len) and then Msg1 (Msg2_Len + 1 .. Msg2_Len + 10) = "", instance"") or else (Msg2_Len - 10 > Msg1_Len and then Msg1.all = Msg2.all (1 .. Msg1_Len) and then Msg2 (Msg1_Len + 1 .. Msg1_Len + 10) = "", instance""); end Same_Error; ------------------- -- Set_Msg_Blank -- ------------------- procedure Set_Msg_Blank is begin if Msglen > 0 and then Msg_Buffer (Msglen) /= ' ' and then Msg_Buffer (Msglen) /= '(' and then Msg_Buffer (Msglen) /= '-' and then not Manual_Quote_Mode then Set_Msg_Char (' '); end if; end Set_Msg_Blank; ------------------------------- -- Set_Msg_Blank_Conditional -- ------------------------------- procedure Set_Msg_Blank_Conditional is begin if Msglen > 0 and then Msg_Buffer (Msglen) /= ' ' and then Msg_Buffer (Msglen) /= '(' and then Msg_Buffer (Msglen) /= '""' and then not Manual_Quote_Mode then Set_Msg_Char (' '); end if; end Set_Msg_Blank_Conditional; ------------------ -- Set_Msg_Char -- ------------------ procedure Set_Msg_Char (C : Character) is begin -- The check for message buffer overflow is needed to deal with cases -- where insertions get too long (in particular a child unit name can -- be very long). if Msglen < Max_Msg_Length then Msglen := Msglen + 1; Msg_Buffer (Msglen) := C; end if; end Set_Msg_Char; --------------------------------- -- Set_Msg_Insertion_File_Name -- --------------------------------- procedure Set_Msg_Insertion_File_Name is begin if Error_Msg_File_1 = No_File then null; elsif Error_Msg_File_1 = Error_File_Name then Set_Msg_Blank; Set_Msg_Str (""""); else Set_Msg_Blank; Get_Name_String (Error_Msg_File_1); Set_Msg_Quote; Set_Msg_Name_Buffer; Set_Msg_Quote; end if; -- The following assignments ensure that the second and third { -- insertion characters will correspond to the Error_Msg_File_2 and -- Error_Msg_File_3 values and We suppress possible validity checks in -- case operating in -gnatVa mode, and Error_Msg_File_2 or -- Error_Msg_File_3 is not needed and has not been set. declare pragma Suppress (Range_Check); begin Error_Msg_File_1 := Error_Msg_File_2; Error_Msg_File_2 := Error_Msg_File_3; end; end Set_Msg_Insertion_File_Name; ----------------------------------- -- Set_Msg_Insertion_Line_Number -- ----------------------------------- procedure Set_Msg_Insertion_Line_Number (Loc, Flag : Source_Ptr) is Sindex_Loc : Source_File_Index; Sindex_Flag : Source_File_Index; Fname : File_Name_Type; Int_File : Boolean; procedure Set_At; -- Outputs ""at "" unless last characters in buffer are "" from "". Certain -- messages read better with from than at. ------------ -- Set_At -- ------------ procedure Set_At is begin if Msglen < 6 or else Msg_Buffer (Msglen - 5 .. Msglen) /= "" from "" then Set_Msg_Str (""at ""); end if; end Set_At; -- Start of processing for Set_Msg_Insertion_Line_Number begin Set_Msg_Blank; if Loc = No_Location then Set_At; Set_Msg_Str (""unknown location""); elsif Loc = System_Location then Set_Msg_Str (""in package System""); Set_Msg_Insertion_Run_Time_Name; elsif Loc = Standard_Location then Set_Msg_Str (""in package Standard""); elsif Loc = Standard_ASCII_Location then Set_Msg_Str (""in package Standard.ASCII""); else -- Add ""at file-name:"" if reference is to other than the source -- file in which the error message is placed. Note that we check -- full file names, rather than just the source indexes, to -- deal with generic instantiations from the current file. Sindex_Loc := Get_Source_File_Index (Loc); Sindex_Flag := Get_Source_File_Index (Flag); if Full_File_Name (Sindex_Loc) /= Full_File_Name (Sindex_Flag) then Set_At; Fname := Reference_Name (Get_Source_File_Index (Loc)); Int_File := Is_Internal_File_Name (Fname); Get_Name_String (Fname); Set_Msg_Name_Buffer; if not (Int_File and Debug_Flag_Dot_K) then Set_Msg_Char (':'); Set_Msg_Int (Int (Get_Logical_Line_Number (Loc))); end if; -- If in current file, add text ""at line "" else Set_At; Set_Msg_Str (""line ""); Int_File := False; Set_Msg_Int (Int (Get_Logical_Line_Number (Loc))); end if; -- Deal with the instantiation case. We may have a reference to, -- e.g. a type, that is declared within a generic template, and -- what we are really referring to is the occurrence in an instance. -- In this case, the line number of the instantiation is also of -- interest, and we add a notation: -- , instance at xxx -- where xxx is a line number output using this same routine (and -- the recursion can go further if the instantiation is itself in -- a generic template). -- The flag location passed to us in this situation is indeed the -- line number within the template, but as described in Sinput.L -- (file sinput-l.ads, section ""Handling Generic Instantiations"") -- we can retrieve the location of the instantiation itself from -- this flag location value. -- Note: this processing is suppressed if Suppress_Instance_Location -- is set True. This is used to prevent redundant annotations of the -- location of the instantiation in the case where we are placing -- the messages on the instantiation in any case. if Instantiation (Sindex_Loc) /= No_Location and then not Suppress_Instance_Location then Set_Msg_Str ("", instance ""); Set_Msg_Insertion_Line_Number (Instantiation (Sindex_Loc), Flag); end if; end if; end Set_Msg_Insertion_Line_Number; ---------------------------- -- Set_Msg_Insertion_Name -- ---------------------------- procedure Set_Msg_Insertion_Name is begin if Error_Msg_Name_1 = No_Name then null; elsif Error_Msg_Name_1 = Error_Name then Set_Msg_Blank; Set_Msg_Str (""""); else Set_Msg_Blank_Conditional; Get_Unqualified_Decoded_Name_String (Error_Msg_Name_1); -- Remove %s or %b at end. These come from unit names. If the -- caller wanted the (unit) or (body), then they would have used -- the $ insertion character. Certainly no error message should -- ever have %b or %s explicitly occurring. if Name_Len > 2 and then Name_Buffer (Name_Len - 1) = '%' and then (Name_Buffer (Name_Len) = 'b' or else Name_Buffer (Name_Len) = 's') then Name_Len := Name_Len - 2; end if; -- Remove upper case letter at end, again, we should not be getting -- such names, and what we hope is that the remainder makes sense. if Name_Len > 1 and then Name_Buffer (Name_Len) in 'A' .. 'Z' then Name_Len := Name_Len - 1; end if; -- If operator name or character literal name, just print it as is -- Also print as is if it ends in a right paren (case of x'val(nnn)) if Name_Buffer (1) = '""' or else Name_Buffer (1) = ''' or else Name_Buffer (Name_Len) = ')' then Set_Msg_Name_Buffer; -- Else output with surrounding quotes in proper casing mode else Set_Casing (Identifier_Casing (Flag_Source)); Set_Msg_Quote; Set_Msg_Name_Buffer; Set_Msg_Quote; end if; end if; -- The following assignments ensure that the second and third percent -- insertion characters will correspond to the Error_Msg_Name_2 and -- Error_Msg_Name_3 as required. We suppress possible validity checks in -- case operating in -gnatVa mode, and Error_Msg_Name_1/2 is not needed -- and has not been set. declare pragma Suppress (Range_Check); begin Error_Msg_Name_1 := Error_Msg_Name_2; Error_Msg_Name_2 := Error_Msg_Name_3; end; end Set_Msg_Insertion_Name; ------------------------------------ -- Set_Msg_Insertion_Name_Literal -- ------------------------------------ procedure Set_Msg_Insertion_Name_Literal is begin if Error_Msg_Name_1 = No_Name then null; elsif Error_Msg_Name_1 = Error_Name then Set_Msg_Blank; Set_Msg_Str (""""); else Set_Msg_Blank; Get_Name_String (Error_Msg_Name_1); Set_Msg_Quote; Set_Msg_Name_Buffer; Set_Msg_Quote; end if; -- The following assignments ensure that the second and third % or %% -- insertion characters will correspond to the Error_Msg_Name_2 and -- Error_Msg_Name_3 values and We suppress possible validity checks in -- case operating in -gnatVa mode, and Error_Msg_Name_2 or -- Error_Msg_Name_3 is not needed and has not been set. declare pragma Suppress (Range_Check); begin Error_Msg_Name_1 := Error_Msg_Name_2; Error_Msg_Name_2 := Error_Msg_Name_3; end; end Set_Msg_Insertion_Name_Literal; ------------------------------------- -- Set_Msg_Insertion_Reserved_Name -- ------------------------------------- procedure Set_Msg_Insertion_Reserved_Name is begin Set_Msg_Blank_Conditional; Get_Name_String (Error_Msg_Name_1); Set_Msg_Quote; Set_Casing (Keyword_Casing (Flag_Source), All_Lower_Case); Set_Msg_Name_Buffer; Set_Msg_Quote; end Set_Msg_Insertion_Reserved_Name; ------------------------------------- -- Set_Msg_Insertion_Reserved_Word -- ------------------------------------- procedure Set_Msg_Insertion_Reserved_Word (Text : String; J : in out Integer) is begin Set_Msg_Blank_Conditional; Name_Len := 0; while J <= Text'Last and then Text (J) in 'A' .. 'Z' loop Add_Char_To_Name_Buffer (Text (J)); J := J + 1; end loop; -- Here is where we make the special exception for RM if Name_Len = 2 and then Name_Buffer (1 .. 2) = ""RM"" then Set_Msg_Name_Buffer; -- We make a similar exception for SPARK elsif Name_Len = 5 and then Name_Buffer (1 .. 5) = ""SPARK"" then Set_Msg_Name_Buffer; -- Neither RM nor SPARK: case appropriately and add surrounding quotes else Set_Casing (Keyword_Casing (Flag_Source), All_Lower_Case); Set_Msg_Quote; Set_Msg_Name_Buffer; Set_Msg_Quote; end if; end Set_Msg_Insertion_Reserved_Word; ------------------------------------- -- Set_Msg_Insertion_Run_Time_Name -- ------------------------------------- procedure Set_Msg_Insertion_Run_Time_Name is begin if Targparm.Run_Time_Name_On_Target /= No_Name then Set_Msg_Blank_Conditional; Set_Msg_Char ('('); Get_Name_String (Targparm.Run_Time_Name_On_Target); Set_Casing (Mixed_Case); Set_Msg_Str (Name_Buffer (1 .. Name_Len)); Set_Msg_Char (')'); end if; end Set_Msg_Insertion_Run_Time_Name; ---------------------------- -- Set_Msg_Insertion_Uint -- ---------------------------- procedure Set_Msg_Insertion_Uint is begin Set_Msg_Blank; UI_Image (Error_Msg_Uint_1); for J in 1 .. UI_Image_Length loop Set_Msg_Char (UI_Image_Buffer (J)); end loop; -- The following assignment ensures that a second caret insertion -- character will correspond to the Error_Msg_Uint_2 parameter. We -- suppress possible validity checks in case operating in -gnatVa mode, -- and Error_Msg_Uint_2 is not needed and has not been set. declare pragma Suppress (Range_Check); begin Error_Msg_Uint_1 := Error_Msg_Uint_2; end; end Set_Msg_Insertion_Uint; ----------------- -- Set_Msg_Int -- ----------------- procedure Set_Msg_Int (Line : Int) is begin if Line > 9 then Set_Msg_Int (Line / 10); end if; Set_Msg_Char (Character'Val (Character'Pos ('0') + (Line rem 10))); end Set_Msg_Int; ------------------------- -- Set_Msg_Name_Buffer -- ------------------------- procedure Set_Msg_Name_Buffer is begin Set_Msg_Str (Name_Buffer (1 .. Name_Len)); end Set_Msg_Name_Buffer; ------------------- -- Set_Msg_Quote -- ------------------- procedure Set_Msg_Quote is begin if not Manual_Quote_Mode then Set_Msg_Char ('""'); end if; end Set_Msg_Quote; ----------------- -- Set_Msg_Str -- ----------------- procedure Set_Msg_Str (Text : String) is begin -- Do replacement for special x'Class aspect names if Text = ""_Pre"" then Set_Msg_Str (""Pre'Class""); elsif Text = ""_Post"" then Set_Msg_Str (""Post'Class""); elsif Text = ""_Type_Invariant"" then Set_Msg_Str (""Type_Invariant'Class""); elsif Text = ""_pre"" then Set_Msg_Str (""pre'class""); elsif Text = ""_post"" then Set_Msg_Str (""post'class""); elsif Text = ""_type_invariant"" then Set_Msg_Str (""type_invariant'class""); elsif Text = ""_PRE"" then Set_Msg_Str (""PRE'CLASS""); elsif Text = ""_POST"" then Set_Msg_Str (""POST'CLASS""); elsif Text = ""_TYPE_INVARIANT"" then Set_Msg_Str (""TYPE_INVARIANT'CLASS""); -- Normal case with no replacement else for J in Text'Range loop Set_Msg_Char (Text (J)); end loop; end if; end Set_Msg_Str; ------------------------------ -- Set_Next_Non_Deleted_Msg -- ------------------------------ procedure Set_Next_Non_Deleted_Msg (E : in out Error_Msg_Id) is begin if E = No_Error_Msg then return; else loop E := Errors.Table (E).Next; exit when E = No_Error_Msg or else not Errors.Table (E).Deleted; end loop; end if; end Set_Next_Non_Deleted_Msg; ------------------------------ -- Set_Specific_Warning_Off -- ------------------------------ procedure Set_Specific_Warning_Off (Loc : Source_Ptr; Msg : String; Reason : String_Id; Config : Boolean; Used : Boolean := False) is begin Specific_Warnings.Append ((Start => Loc, Msg => new String'(Msg), Stop => Source_Last (Get_Source_File_Index (Loc)), Reason => Reason, Open => True, Used => Used, Config => Config)); end Set_Specific_Warning_Off; ----------------------------- -- Set_Specific_Warning_On -- ----------------------------- procedure Set_Specific_Warning_On (Loc : Source_Ptr; Msg : String; Err : out Boolean) is begin for J in 1 .. Specific_Warnings.Last loop declare SWE : Specific_Warning_Entry renames Specific_Warnings.Table (J); begin if Msg = SWE.Msg.all and then Loc > SWE.Start and then SWE.Open and then Get_Source_File_Index (SWE.Start) = Get_Source_File_Index (Loc) then SWE.Stop := Loc; SWE.Open := False; Err := False; -- If a config pragma is specifically cancelled, consider -- that it is no longer active as a configuration pragma. SWE.Config := False; return; end if; end; end loop; Err := True; end Set_Specific_Warning_On; --------------------------- -- Set_Warnings_Mode_Off -- --------------------------- procedure Set_Warnings_Mode_Off (Loc : Source_Ptr; Reason : String_Id) is begin -- Don't bother with entries from instantiation copies, since we will -- already have a copy in the template, which is what matters. if Instantiation (Get_Source_File_Index (Loc)) /= No_Location then return; end if; -- If all warnings are suppressed by command line switch, this can -- be ignored, unless we are in GNATprove_Mode which requires pragma -- Warnings to be stored for the formal verification backend. if Warning_Mode = Suppress and then not GNATprove_Mode then return; end if; -- If last entry in table already covers us, this is a redundant pragma -- Warnings (Off) and can be ignored. if Warnings.Last >= Warnings.First and then Warnings.Table (Warnings.Last).Start <= Loc and then Loc <= Warnings.Table (Warnings.Last).Stop then return; end if; -- If none of those special conditions holds, establish a new entry, -- extending from the location of the pragma to the end of the current -- source file. This ending point will be adjusted by a subsequent -- corresponding pragma Warnings (On). Warnings.Append ((Start => Loc, Stop => Source_Last (Get_Source_File_Index (Loc)), Reason => Reason)); end Set_Warnings_Mode_Off; -------------------------- -- Set_Warnings_Mode_On -- -------------------------- procedure Set_Warnings_Mode_On (Loc : Source_Ptr) is begin -- Don't bother with entries from instantiation copies, since we will -- already have a copy in the template, which is what matters. if Instantiation (Get_Source_File_Index (Loc)) /= No_Location then return; end if; -- If all warnings are suppressed by command line switch, this can -- be ignored, unless we are in GNATprove_Mode which requires pragma -- Warnings to be stored for the formal verification backend. if Warning_Mode = Suppress and then not GNATprove_Mode then return; end if; -- If the last entry in the warnings table covers this pragma, then -- we adjust the end point appropriately. if Warnings.Last >= Warnings.First and then Warnings.Table (Warnings.Last).Start <= Loc and then Loc <= Warnings.Table (Warnings.Last).Stop then Warnings.Table (Warnings.Last).Stop := Loc; end if; end Set_Warnings_Mode_On; ------------------- -- Sloc_In_Range -- ------------------- function Sloc_In_Range (Loc, Start, Stop : Source_Ptr) return Boolean is Cur_Loc : Source_Ptr := Loc; begin while Cur_Loc /= No_Location loop if Start <= Cur_Loc and then Cur_Loc <= Stop then return True; end if; Cur_Loc := Instantiation_Location (Cur_Loc); end loop; return False; end Sloc_In_Range; -------------------------------- -- Validate_Specific_Warnings -- -------------------------------- procedure Validate_Specific_Warnings (Eproc : Error_Msg_Proc) is begin if not Warn_On_Warnings_Off then return; end if; for J in Specific_Warnings.First .. Specific_Warnings.Last loop declare SWE : Specific_Warning_Entry renames Specific_Warnings.Table (J); begin if not SWE.Config then -- Warn for unmatched Warnings (Off, ...) if SWE.Open then Eproc.all (""?W?pragma Warnings Off with no matching Warnings On"", SWE.Start); -- Warn for ineffective Warnings (Off, ..) elsif not SWE.Used -- Do not issue this warning for -Wxxx messages since the -- back-end doesn't report the information. Note that there -- is always an asterisk at the start of every message. and then not (SWE.Msg'Length > 3 and then SWE.Msg (2 .. 3) = ""-W"") then Eproc.all (""?W?no warning suppressed by this pragma"", SWE.Start); end if; end if; end; end loop; end Validate_Specific_Warnings; ------------------------------------- -- Warning_Specifically_Suppressed -- ------------------------------------- function Warning_Specifically_Suppressed (Loc : Source_Ptr; Msg : String_Ptr; Tag : String := """") return String_Id is begin -- Loop through specific warning suppression entries for J in Specific_Warnings.First .. Specific_Warnings.Last loop declare SWE : Specific_Warning_Entry renames Specific_Warnings.Table (J); begin -- Pragma applies if it is a configuration pragma, or if the -- location is in range of a specific non-configuration pragma. if SWE.Config or else Sloc_In_Range (Loc, SWE.Start, SWE.Stop) then if Matches (Msg.all, SWE.Msg.all) or else Matches (Tag, SWE.Msg.all) then SWE.Used := True; return SWE.Reason; end if; end if; end; end loop; return No_String; end Warning_Specifically_Suppressed; ------------------------------ -- Warning_Treated_As_Error -- ------------------------------ function Warning_Treated_As_Error (Msg : String) return Boolean is begin for J in 1 .. Warnings_As_Errors_Count loop if Matches (Msg, Warnings_As_Errors (J).all) then return True; end if; end loop; return False; end Warning_Treated_As_Error; ------------------------- -- Warnings_Suppressed -- ------------------------- function Warnings_Suppressed (Loc : Source_Ptr) return String_Id is begin -- Loop through table of ON/OFF warnings for J in Warnings.First .. Warnings.Last loop if Sloc_In_Range (Loc, Warnings.Table (J).Start, Warnings.Table (J).Stop) then return Warnings.Table (J).Reason; end if; end loop; if Warning_Mode = Suppress then return Null_String_Id; else return No_String; end if; end Warnings_Suppressed; end Erroutc; ",12507,False,2323.458569262278,median "with SPARKNaCl.Utils; with SPARKNaCl.Hashing; package body SPARKNaCl.Sign with SPARK_Mode => On is pragma Warnings (GNATProve, Off, ""pragma * ignored (not yet supported)""); --============================================ -- Local constants and types --============================================ GF_D : constant Normal_GF := (16#78a3#, 16#1359#, 16#4dca#, 16#75eb#, 16#d8ab#, 16#4141#, 16#0a4d#, 16#0070#, 16#e898#, 16#7779#, 16#4079#, 16#8cc7#, 16#fe73#, 16#2b6f#, 16#6cee#, 16#5203#); GF_I : constant Normal_GF := (16#a0b0#, 16#4a0e#, 16#1b27#, 16#c4ee#, 16#e478#, 16#ad2f#, 16#1806#, 16#2f43#, 16#d7a7#, 16#3dfb#, 16#0099#, 16#2b4d#, 16#df0b#, 16#4fc1#, 16#2480#, 16#2b83#); GF_X : constant Normal_GF := (16#d51a#, 16#8f25#, 16#2d60#, 16#c956#, 16#a7b2#, 16#9525#, 16#c760#, 16#692c#, 16#dc5c#, 16#fdd6#, 16#e231#, 16#c0a4#, 16#53fe#, 16#cd6e#, 16#36d3#, 16#2169#); GF_Y : constant Normal_GF := (16#6658#, 16#6666#, 16#6666#, 16#6666#, 16#6666#, 16#6666#, 16#6666#, 16#6666#, 16#6666#, 16#6666#, 16#6666#, 16#6666#, 16#6666#, 16#6666#, 16#6666#, 16#6666#); -- Original TweetNaCl code computes Q(3) by multiplying GF_X by GF_Y, -- but this is a constant (now called GF_XY), thus: GF_XY : constant Normal_GF := (16#DD90#, 16#A5B7#, 16#8AB3#, 16#6DDE#, 16#52F5#, 16#7751#, 16#9F80#, 16#20F0#, 16#E37D#, 16#64AB#, 16#4E8E#, 16#66EA#, 16#7665#, 16#D78B#, 16#5F0F#, 16#E787#); GF_D2 : constant Normal_GF := (16#f159#, 16#26b2#, 16#9b94#, 16#ebd6#, 16#b156#, 16#8283#, 16#149a#, 16#00e0#, 16#d130#, 16#eef3#, 16#80f2#, 16#198e#, 16#fce7#, 16#56df#, 16#d9dc#, 16#2406#); type GF_Vector_4 is array (Index_4) of Normal_GF; -- MBP = ""Max Byte Product"" MBP : constant := (255 * 255); Max_X_Limb : constant := (32 * MBP) + 255; --============================================ -- Local subprogram declarations --============================================ function ModL (X : in I64_Seq_64) return Bytes_32 with Pure_Function, Global => null, Pre => (for all K in Index_64 => X (K) in 0 .. Max_X_Limb); procedure Sanitize_GF_Vector_4 (R : out GF_Vector_4) with Global => null; -- Replaces function ""add"" in the TweetNaCl sources function ""+"" (Left, Right : in GF_Vector_4) return GF_Vector_4 with Pure_Function, Global => null; function Scalarmult (Q : in GF_Vector_4; S : in Bytes_32) return GF_Vector_4 with Pure_Function, Global => null; function Scalarbase (S : in Bytes_32) return GF_Vector_4 with Pure_Function, Global => null; function Pack (P : in GF_Vector_4) return Bytes_32 with Pure_Function, Global => null; subtype Bit is Byte range 0 .. 1; function Par_25519 (A : in Normal_GF) return Bit with Pure_Function, Global => null; -- SPARKNaCl introduces this function to combine Hash and Reduce into -- a single call. Former procedure Reduce removed. function Hash_Reduce (M : in Byte_Seq) return Bytes_32 with Pure_Function, Global => null; procedure Unpackneg (R : out GF_Vector_4; OK : out Boolean; P : in Bytes_32) with Global => null; --============================================ -- Local subprogram bodies --============================================ procedure Sanitize_GF_Vector_4 (R : out GF_Vector_4) is begin for I in R'Range loop pragma Loop_Optimize (No_Unroll); Sanitize_GF16 (R (I)); end loop; end Sanitize_GF_Vector_4; function ""+"" (Left, Right : in GF_Vector_4) return GF_Vector_4 is A, B, C, D, E, F, G, H : Normal_GF; function Double (X : in Normal_GF) return Normal_GF is (X + X) with Pure_Function, Global => null; begin A := (Left (1) - Left (0)) * (Right (1) - Right (0)); B := (Left (0) + Left (1)) * (Right (0) + Right (1)); C := (Left (3) * Right (3)) * GF_D2; D := Double (Left (2) * Right (2)); E := D - C; F := D + C; G := B - A; H := B + A; return GF_Vector_4'(0 => G * E, 1 => H * F, 2 => F * E, 3 => G * H); end ""+""; function Scalarmult (Q : in GF_Vector_4; S : in Bytes_32) return GF_Vector_4 is CB : Byte; Swap : Boolean; LP, LQ : GF_Vector_4; procedure CSwap (P, Q : in out GF_Vector_4; Swap : in Boolean) with Global => null; procedure CSwap (P, Q : in out GF_Vector_4; Swap : in Boolean) is begin for I in Index_4 loop pragma Loop_Optimize (No_Unroll); Utils.CSwap16 (P (I), Q (I), Swap); end loop; end CSwap; begin LP := (0 => GF_0, 1 => GF_1, 2 => GF_1, 3 => GF_0); LQ := Q; -- For each byte of S, starting at the MSB for I in reverse Index_32 loop pragma Loop_Optimize (No_Unroll); CB := S (I); -- For each bit of CB, starting with bit 7 (the MSB) for J in reverse Natural range 0 .. 7 loop pragma Loop_Optimize (No_Unroll); Swap := Boolean'Val (Shift_Right (CB, J) mod 2); CSwap (LP, LQ, Swap); LQ := LQ + LP; LP := LP + LP; CSwap (LP, LQ, Swap); end loop; end loop; return LP; end Scalarmult; function Scalarbase (S : in Bytes_32) return GF_Vector_4 is begin return Scalarmult (GF_Vector_4'(GF_X, GF_Y, GF_1, GF_XY), S); end Scalarbase; function Par_25519 (A : in Normal_GF) return Bit is D : Bytes_32; begin D := Utils.Pack_25519 (A); return (D (0) mod 2); end Par_25519; function Pack (P : in GF_Vector_4) return Bytes_32 is TX, TY, ZI : Normal_GF; R : Bytes_32; begin ZI := Utils.Inv_25519 (P (2)); TX := P (0) * ZI; TY := P (1) * ZI; R := Utils.Pack_25519 (TY); R (31) := R (31) xor (Par_25519 (TX) * 128); return R; end Pack; -- RFC 7748 says the ""order"" of Curve25519 is -- 2^252 + 0x14def9dea2f79cd65812631a5cf5d3ed -- -- In little-endian radix 2**8 format, this is 256 bits, thus: Max_L : constant := 16#f9#; L0 : constant := 16#ed#; subtype L_Limb is I64_Byte range 0 .. Max_L; type L_Table is array (Index_32) of L_Limb; L : constant L_Table := (L0, 16#d3#, 16#f5#, 16#5c#, 16#1a#, 16#63#, 16#12#, 16#58#, 16#d6#, 16#9c#, 16#f7#, 16#a2#, 16#de#, 16#f9#, 16#de#, 16#14#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#10#); function ModL (X : in I64_Seq_64) return Bytes_32 is Max_Carry : constant := 2**14; Min_Carry : constant := -2**25; subtype Carry_T is I64 range Min_Carry .. Max_Carry; Min_Adjustment : constant := (Min_Carry * 16 * Max_L); Max_Adjustment : constant := ((Max_X_Limb + Max_Carry) * 16 * Max_L); subtype Adjustment_T is I64 range Min_Adjustment .. Max_Adjustment; subtype XL_Limb is I64 range -((Max_X_Limb + Max_Carry + Max_Adjustment) * 16 * Max_L) .. ((Max_X_Limb + Max_Carry + Max_Adjustment) * 16 * Max_L); type XL_Table is array (Index_64) of XL_Limb; XL : XL_Table; -- ""PRL"" = ""Partially Reduced Limb"" subtype PRL is I64 range -129 .. 128; -- ""FRL"" = ""Fully Reduced Limb"" subtype FRL is PRL range -128 .. 127; R : Bytes_32; -- The largest value of Carry is achieved when XL (63) = 0, -- so that -- Max_L63_Carry = ASR_8 (Max_X_Limb + Max_L63_Carry + 128) -- Knowing that all the terms are positive means we can expand -- ASR_8 and simplify. -- This is declared here it can be used to derive subtype -- XL51_T and used in the post-condition of Eliminate_Limb_63 below Max_L63_Carry : constant := (Max_X_Limb + 128) / 255; subtype XL51_T is I64 range 0 .. (Max_X_Limb + Max_L63_Carry); procedure Initialize_XL with Global => (Input => X, Output => XL), Pre => (for all K in Index_64 => X (K) in 0 .. Max_X_Limb), Post => (for all K in Index_64 => XL (K) >= 0) and (for all K in Index_64 => XL (K) <= Max_X_Limb) and (for all K in Index_64 => XL (K) = XL_Limb (X (K))); procedure Eliminate_Limb_63 with Global => (Proof_In => X, In_Out => XL), Pre => (for all K in Index_64 => X (K) in 0 .. Max_X_Limb) and then (for all K in Index_64 => XL (K) >= 0) and then (for all K in Index_64 => XL (K) <= Max_X_Limb) and then (for all K in Index_64 => XL (K) = XL_Limb (X (K))), Post => (for all K in Index_64 range 0 .. 30 => XL (K) = X (K)) and (for all K in Index_64 range 31 .. 50 => XL (K) in FRL) and (XL (51) in XL51_T) and (for all K in Index_64 range 52 .. 62 => XL (K) = X (K)) and (XL (63) = 0); procedure Eliminate_Limbs_62_To_32 with Global => (Proof_In => X, In_Out => XL), Pre => ((for all K in Index_64 range 0 .. 30 => XL (K) = X (K) and XL (K) in 0 .. Max_X_Limb) and (for all K in Index_64 range 31 .. 50 => XL (K) in FRL) and (XL (51) in XL51_T) and (for all K in Index_64 range 52 .. 62 => XL (K) = X (K) and XL (K) in 0 .. Max_X_Limb) and (XL (63) = 0)), Post => ((for all K in Index_64 range 0 .. 19 => XL (K) in FRL) and (for all K in Index_64 range 20 .. 31 => XL (K) in PRL) and (for all K in Index_64 range 32 .. 63 => XL (K) = 0)); procedure Finalize with Global => (In_Out => XL, Output => R), Pre => ((for all K in Index_64 range 0 .. 19 => XL (K) in FRL) and (for all K in Index_64 range 20 .. 31 => XL (K) in PRL) and (for all K in Index_64 range 32 .. 63 => XL (K) = 0)); procedure Initialize_XL is begin XL := (others => 0); for K in Index_64 loop pragma Loop_Optimize (No_Unroll); XL (K) := XL_Limb (X (K)); pragma Loop_Invariant (for all A in Index_64 range 0 .. K => XL (A) = XL_Limb (X (A))); end loop; end Initialize_XL; procedure Eliminate_Limb_63 is Max_L63_Adjustment : constant := 16 * Max_L * Max_X_Limb; subtype L63_Adjustment_T is I64 range 0 .. Max_L63_Adjustment; -- The most negative value of Carry is when XL (63) = Max_X_Limb and -- L (J - 31) = Max_L and XL (J) = 0 -- so that -- Min_L63_Carry = -- ASR_8 (0 + Min_L63_Carry - Max_L63_Adjustment + 128) Min_L63_Carry : constant := ((128 - Max_L63_Adjustment) / 255) - 1; subtype L63_Carry_T is I64 range Min_L63_Carry .. Max_L63_Carry; Carry : L63_Carry_T; Adjustment : L63_Adjustment_T; begin Carry := 0; -- In the TweetNaCl sources, this loop interates 20 times -- covering elements of L from L (0) to L (19). -- In this implementation, though, we choose to loop over the -- first 16 elements of L first, since these are all non-zero, -- and manually unroll the final 4 iterations where L (16) -- through L (19) are all zero. for J in I32 range 31 .. 46 loop pragma Loop_Optimize (No_Unroll); Adjustment := (16 * L (J - 31)) * XL (63); XL (J) := XL (J) + Carry - Adjustment; Carry := ASR_8 (XL (J) + 128); XL (J) := XL (J) - (Carry * 256); pragma Loop_Invariant ((for all K in Index_64 range 0 .. 30 => XL (K) = XL'Loop_Entry (K)) and (for all K in Index_64 range 31 .. J => XL (K) in FRL) and (for all K in Index_64 range J + 1 .. 63 => XL (K) = XL'Loop_Entry (K))); end loop; pragma Assert ((for all K in Index_64 range 0 .. 30 => XL (K) = X (K)) and (for all K in Index_64 range 31 .. 46 => XL (K) in FRL) and (for all K in Index_64 range 47 .. 63 => XL (K) = X (K))); -- Final 4 limbs of XL (47) through XL (50) -- For these limbs, we know that L (16) through L (19) -- is zero, so the calculation of Adjustment can be eliminated. -- -- As these final four limbs are processed, the upper bound -- on Carry stays the same at Max_L63_Carry, but the lower bound -- converges towards 0. declare -- Expand the definition of ASR_8 for values gives... Min_XL47_Carry : constant := ((Min_L63_Carry + 128 + 1) / 2**8) - 1; pragma Assert (Min_XL47_Carry = -127006); Min_XL48_Carry : constant := ((Min_XL47_Carry + 128 + 1) / 2**8) - 1; pragma Assert (Min_XL48_Carry = -496); Min_XL49_Carry : constant := ((Min_XL48_Carry + 128 + 1) / 2**8) - 1; pragma Assert (Min_XL49_Carry = -2); Min_XL50_Carry : constant := ((Min_XL49_Carry + 128) / 2**8); pragma Assert (Min_XL50_Carry = 0); begin XL (47) := XL (47) + Carry; Carry := ASR_8 (XL (47) + 128); XL (47) := XL (47) - (Carry * 256); pragma Assert (Carry >= Min_XL47_Carry); XL (48) := XL (48) + Carry; Carry := ASR_8 (XL (48) + 128); XL (48) := XL (48) - (Carry * 256); pragma Assert (Carry >= Min_XL48_Carry); XL (49) := XL (49) + Carry; Carry := ASR_8 (XL (49) + 128); XL (49) := XL (49) - (Carry * 256); pragma Assert (Carry >= Min_XL49_Carry); XL (50) := XL (50) + Carry; Carry := ASR_8 (XL (50) + 128); XL (50) := XL (50) - (Carry * 256); -- Lower bound on Carry should have converged to 0 pragma Assert (Min_XL50_Carry = 0); pragma Assert (Carry >= Min_XL50_Carry); end; pragma Assert ((for all K in Index_64 range 0 .. 30 => XL (K) = X (K)) and (for all K in Index_64 range 31 .. 50 => XL (K) in FRL) and (for all K in Index_64 range 51 .. 63 => XL (K) = X (K))); -- Note XL (51) is adjusted here but is NOT normalized -- to be in FRL... hence it's a special case in the post- -- condition above. XL (51) := XL (51) + Carry; pragma Assert (XL (51) in XL51_T); XL (63) := 0; end Eliminate_Limb_63; procedure Eliminate_Limbs_62_To_32 is Carry : Carry_T; Adjustment : Adjustment_T; begin for I in reverse I32 range 32 .. 62 loop pragma Loop_Optimize (No_Unroll); Carry := 0; -- As above, this loop iterates over limbs 0 .. 15 of L -- leaving the final four (zero) limbs unrolled below. for J in I32 range (I - 32) .. (I - 17) loop pragma Loop_Optimize (No_Unroll); Adjustment := (16 * L (J - (I - 32))) * XL (I); XL (J) := XL (J) + Carry - Adjustment; Carry := ASR_8 (XL (J) + 128); XL (J) := XL (J) - (Carry * 256); pragma Loop_Invariant (for all K in Index_64 range 0 .. I - 33 => XL (K) = XL'Loop_Entry (K)); pragma Loop_Invariant (for all K in Index_64 range I - 32 .. J => XL (K) in FRL); pragma Loop_Invariant (for all K in Index_64 range J + 1 .. I32'Min (50, I - 1) => XL (K) = XL'Loop_Entry (K)); pragma Loop_Invariant (for all K in Index_64 range J + 1 .. I32'Min (50, I - 1) => XL (K) in PRL); pragma Loop_Invariant (for all K in Index_64 range I32'Max (I - 11, 52) .. I - 1 => XL (K) = XL'Loop_Entry (K)); pragma Loop_Invariant (for all K in Index_64 range I + 1 .. 63 => XL (K) = 0); pragma Loop_Invariant (for all K in Index_64 => XL (K) in PRL'First .. XL51_T'Last); end loop; -- 16 elements of XL(I-32) .. XL(I-17) are in now FRL pragma Assert (for all K in Index_64 range I - 32 .. I - 17 => XL (K) in FRL); pragma Assert (XL (I - 16) in FRL); -- Carry is in Carry_T here XL (I - 16) := XL (I - 16) + Carry; Carry := ASR_8 (XL (I - 16) + 128); XL (I - 16) := XL (I - 16) - (Carry * 256); -- 17 elements of XL are in FRL pragma Assert (for all K in Index_64 range I - 32 .. I - 16 => XL (K) in FRL); pragma Assert (XL (I - 15) in FRL); -- Now we can start to prove that Carry is converging. -- Each further reduction reduces the lower and upper bound -- of Carry by about 2**8, except that the addition of 128 and -- ASR_8 actually mean that Carry converges on the range -1 .. 1 pragma Assert (Carry in -2**17 .. 64); XL (I - 15) := XL (I - 15) + Carry; Carry := ASR_8 (XL (I - 15) + 128); XL (I - 15) := XL (I - 15) - (Carry * 256); -- 18 elements of XL are in FRL pragma Assert (for all K in Index_64 range I - 32 .. I - 15 => XL (K) in FRL); pragma Assert (XL (I - 14) in FRL); pragma Assert (Carry in -512 .. 1); XL (I - 14) := XL (I - 14) + Carry; Carry := ASR_8 (XL (I - 14) + 128); XL (I - 14) := XL (I - 14) - (Carry * 256); -- 19 elements of XL are in FRL pragma Assert (for all K in Index_64 range I - 32 .. I - 14 => XL (K) in FRL); pragma Assert (XL (I - 13) in FRL); pragma Assert (Carry in -2 .. 1); XL (I - 13) := XL (I - 13) + Carry; Carry := ASR_8 (XL (I - 13) + 128); XL (I - 13) := XL (I - 13) - (Carry * 256); -- 20 elements of XL are in FRL pragma Assert (for all K in Index_64 range I - 32 .. I - 13 => XL (K) in FRL); pragma Assert (XL (I - 12) in FRL); pragma Assert (Carry in -1 .. 1); -- If Carry in -1 .. 1, then the final adjustment of -- XL (I - 12) means that this limb can end up being -- -129 or +128, so in PRL but not in FRL XL (I - 12) := XL (I - 12) + Carry; pragma Assert (XL (I - 12) in PRL); -- XL (I) is now eliminated, so it gets zeroed out now. XL (I) := 0; pragma Loop_Invariant (for all K in Index_64 range 0 .. I - 33 => XL (K) = XL'Loop_Entry (K)); pragma Loop_Invariant (for all K in Index_64 range I - 32 .. I - 13 => XL (K) in FRL); pragma Loop_Invariant (XL (I - 12) in PRL); pragma Loop_Invariant (for all K in Index_64 range I - 11 .. I32'Min (50, I - 1) => XL (K) in PRL); -- This is XL (51) for I in 52 .. 63 pragma Loop_Invariant (if I >= 52 then XL (51) >= XL'Loop_Entry (51) + Min_Carry); pragma Loop_Invariant (if I >= 52 then XL (51) <= XL'Loop_Entry (51) + Max_Carry); pragma Loop_Invariant (for all K in Index_64 range I32'Max (I - 11, 52) .. I - 1 => XL (K) = XL'Loop_Entry (K)); pragma Loop_Invariant (for all K in Index_64 range I .. 63 => XL (K) = 0); pragma Loop_Invariant (for all K in Index_64 => XL (K) in PRL'First .. XL51_T'Last); end loop; end Eliminate_Limbs_62_To_32; procedure Finalize is Final_Carry_Min : constant := -9; Final_Carry_Max : constant := 9; subtype Final_Carry_T is I64 range Final_Carry_Min .. Final_Carry_Max; subtype Step1_XL_Limb is I64 range (Final_Carry_Min * 256) .. ((Final_Carry_Max + 1) * 256) - 1; subtype Step2_XL_Limb is I64 range I64_Byte'First - (Final_Carry_Max * Max_L) .. I64_Byte'Last - (Final_Carry_Min * Max_L); Carry : Final_Carry_T; begin -- Step 1 Carry := 0; for J in Index_32 loop pragma Loop_Optimize (No_Unroll); pragma Assert (XL (31) in PRL); XL (J) := XL (J) + (Carry - ASR_4 (XL (31)) * L (J)); pragma Assert (XL (J) >= Step1_XL_Limb'First); pragma Assert (XL (J) <= Step1_XL_Limb'Last); Carry := ASR_8 (XL (J)); XL (J) := XL (J) mod 256; -- Modified limbs 0 .. J are all in I64_Byte pragma Loop_Invariant (for all K in Index_64 range 0 .. J => XL (K) in I64_Byte); -- Limbs J + 1 .. 31 are unmodified and in PRL pragma Loop_Invariant (for all K in Index_64 range J + 1 .. 31 => XL (K) = XL'Loop_Entry (K)); pragma Loop_Invariant (for all K in Index_64 range J + 1 .. 31 => XL (K) in PRL); -- Trailing 32 limbs are all 0 pragma Loop_Invariant (for all K in Index_64 range 32 .. 63 => XL (K) = 0); end loop; -- Check first 32 limbs in I64_Byte pragma Assert (for all K in Index_64 range 0 .. 31 => XL (K) in I64_Byte); -- Check later 32 limbs all 0 pragma Assert (for all K in Index_64 range 32 .. 63 => XL (K) = 0); -- Step 2 for J in Index_32 loop pragma Loop_Optimize (No_Unroll); XL (J) := XL (J) - Carry * L (J); pragma Loop_Invariant (for all K in Index_32 range 0 .. J => XL (K) in Step2_XL_Limb); pragma Loop_Invariant (for all K in Index_64 range 32 .. 63 => XL (K) = 0); end loop; pragma Assert (for all K in Index_64 => XL (K) in Step2_XL_Limb); pragma Assert (for all K in Index_64 range 32 .. 63 => XL (K) = 0); -- Step 3 - final carry chain from X (0) to X (32) and reduce -- each limb mod 256 declare -- In Step 3, XL(I+1) is added to ASR_8(XL(I)), so we need to know -- the range of the ASR_8(XL(I)). A precise characterisation -- of the bounds on XL (I+1) would be non-linear, so we fall -- back on a linear over-approximation here, which suffices. -- Max XL Carry - max magnitude of carry from XL(I) to XL(I+1) MXLC : constant := 10; -- Step 3 Carry subtype S3CT is I64 range -MXLC .. MXLC; S3C : S3CT; begin for I in Index_32 loop pragma Loop_Optimize (No_Unroll); pragma Assert (XL (I) >= Step2_XL_Limb'First - MXLC * I64 (I)); S3C := ASR_8 (XL (I)); XL (I + 1) := XL (I + 1) + S3C; R (I) := Byte (XL (I) mod 256); pragma Loop_Invariant (XL (0) = XL'Loop_Entry (0)); pragma Loop_Invariant (XL (0) in Step2_XL_Limb); pragma Loop_Invariant (if I <= 30 then XL (32) = 0); pragma Loop_Invariant (for all K in Index_32 range 1 .. 31 => XL (K) >= Step2_XL_Limb'First - (MXLC * I64 (K))); pragma Loop_Invariant (for all K in Index_32 range 1 .. 31 => XL (K) <= Step2_XL_Limb'Last + (MXLC * I64 (K))); pragma Loop_Invariant (for all K in Index_32 range I + 2 .. 31 => XL (K) in Step2_XL_Limb); end loop; end; end Finalize; begin Initialize_XL; Eliminate_Limb_63; Eliminate_Limbs_62_To_32; pragma Warnings (GNATProve, Off, ""unused assignment""); -- Unused assignment to XL here expected Finalize; return R; end ModL; function Hash_Reduce (M : in Byte_Seq) return Bytes_32 is R : Hashing.Digest; X : I64_Seq_64; begin Hashing.Hash (R, M); X := (others => 0); for I in Index_64 loop pragma Loop_Optimize (No_Unroll); X (I) := I64 (R (I)); pragma Loop_Invariant (for all K in Index_64 range 0 .. I => X (K) in I64_Byte); end loop; pragma Assert (for all K in Index_64 => X (K) in I64_Byte); return ModL (X); end Hash_Reduce; procedure Unpackneg (R : out GF_Vector_4; OK : out Boolean; P : in Bytes_32) is -- Local, time-constant equality test for GF -- In the original TweetNaCl sources, this is called eq25519 function ""="" (Left, Right : in Normal_GF) return Boolean with Pure_Function, Global => null; function Pow_2523 (I : in Normal_GF) return Normal_GF with Pure_Function, Global => null; function ""="" (Left, Right : in Normal_GF) return Boolean is begin return Equal (Bytes_32'(Utils.Pack_25519 (Left)), Bytes_32'(Utils.Pack_25519 (Right))); end ""=""; function Pow_2523 (I : in Normal_GF) return Normal_GF is C, C2 : Normal_GF; begin C := I; -- Note that 2**252 - 3 = 16#1111_1111 .. 1101# -- with only ""bit 1"" set to 0 for A in reverse 0 .. 250 loop pragma Loop_Optimize (No_Unroll); C2 := Square (C); if A = 1 then C := C2; else C := C2 * I; end if; end loop; return C; end Pow_2523; -- Note: refactoring here to functional/SSA form reduces the -- number of calls to ""*"" from 8 in the original TweetNaCl code -- to 5 from here until the initialization of R0, but only if -- ""*"" on GF is commutative. R1 : constant Normal_GF := Utils.Unpack_25519 (P); R2 : Normal_GF renames GF_1; R1_Squared : constant Normal_GF := Square (R1); Num : constant Normal_GF := R1_Squared - R2; Den : constant Normal_GF := R2 + (R1_Squared * GF_D); Den_Power_2 : constant Normal_GF := Square (Den); Den_Power_4 : constant Normal_GF := Square (Den_Power_2); Num_Den2 : constant Normal_GF := (Num * Den) * Den_Power_2; R0 : Normal_GF := Pow_2523 ((Den_Power_4 * Num_Den2)) * Num_Den2; Check : Normal_GF; begin Check := Square (R0) * Den; if Check /= Num then R0 := R0 * GF_I; end if; Check := Square (R0) * Den; if Check /= Num then R := (others => GF_0); OK := False; return; end if; if Par_25519 (R0) = (P (31) / 128) then R0 := GF_0 - R0; end if; R := (0 => R0, 1 => R1, 2 => R2, 3 => R0 * R1); OK := True; end Unpackneg; --============================================ -- Exported subprogram bodies --============================================ function Serialize (K : in Signing_SK) return Bytes_64 is begin return K.F; end Serialize; function Serialize (K : in Signing_PK) return Bytes_32 is begin return K.F; end Serialize; procedure Sanitize (K : out Signing_PK) is begin SPARKNaCl.Sanitize (K.F); end Sanitize; procedure Sanitize (K : out Signing_SK) is begin SPARKNaCl.Sanitize (K.F); end Sanitize; procedure Keypair (SK_Raw : in Bytes_32; -- random please! PK : out Signing_PK; SK : out Signing_SK) is D : Bytes_64; LPK : Bytes_32; begin Hashing.Hash (D, SK_Raw); D (0) := D (0) and 248; D (31) := (D (31) and 127) or 64; LPK := Pack (Scalarbase (D (0 .. 31))); PK.F := LPK; SK.F := SK_Raw & LPK; -- Sanitize intermediate values used in key generation pragma Warnings (GNATProve, Off, ""statement has no effect""); Sanitize (D); Sanitize (LPK); pragma Unreferenced (D); pragma Unreferenced (LPK); end Keypair; procedure PK_From_Bytes (PK_Raw : in Bytes_32; PK : out Signing_PK) is begin PK.F := PK_Raw; end PK_From_Bytes; procedure Sign (SM : out Byte_Seq; M : in Byte_Seq; SK : in Signing_SK) is subtype Byte_Product is I64 range 0 .. MBP; D : Bytes_64; H, R : Bytes_32; X : I64_Seq_64; T : Byte_Product; P : GF_Vector_4; procedure Initialize_SM (X : out Byte_Seq) with Global => (Input => (M, D)), Depends => (X => (X, M, D)), Pre => (M'First = 0 and X'First = 0 and M'Last <= N32'Last - Sign_Bytes) and then (X'Length = M'Length + Sign_Bytes and X'Last = M'Last + Sign_Bytes), Post => (X = Zero_Bytes_32 & D (32 .. 63) & M) and X'Initialized, Relaxed_Initialization => X, Inline; procedure Initialize_SM (X : out Byte_Seq) is begin -- Precondition ensures SM is exactly 64 bytes longer than M. -- Don't use ""&"" here to avoid allocation of a dynamic-sized -- object on the stack. X (0 .. 31) := Zero_Bytes_32; X (32 .. 63) := D (32 .. 63); X (64 .. X'Last) := M; end Initialize_SM; begin Hashing.Hash (D, Serialize (SK) (0 .. 31)); D (0) := D (0) and 248; D (31) := (D (31) and 127) or 64; Initialize_SM (SM); R := Hash_Reduce (SM (32 .. SM'Last)); P := Scalarbase (R); SM (0 .. 31) := Pack (P); SM (32 .. 63) := Serialize (SK) (32 .. 63); H := Hash_Reduce (SM); X := (others => 0); for I in Index_32 loop pragma Loop_Optimize (No_Unroll); X (I) := I64 (R (I)); pragma Loop_Invariant ((for all K in N32 range 0 .. I => X (K) in I64_Byte) and (for all K in N32 range I + 1 .. 63 => X (K) = 0)); end loop; pragma Assert ((for all K in N32 range 0 .. 31 => X (K) in I64_Byte) and (for all K in N32 range 32 .. 63 => X (K) = 0) and (for all K in Index_64 => X (K) in I64_Byte) ); pragma Warnings (Off, ""explicit membership test may be optimized""); for I in Index_32 loop pragma Loop_Optimize (No_Unroll); for J in Index_32 loop pragma Loop_Optimize (No_Unroll); T := Byte_Product (H (I)) * Byte_Product (D (J)); X (I + J) := X (I + J) + T; -- This loop invariant follows the same pattern -- as that in SPARKNaCl.""*"" pragma Loop_Invariant ( T in Byte_Product and -- Lower bound (for all K in Index_64 => X (K) >= 0) and -- rising from 1 to I (for all K in Index_64 range 0 .. (I - 1) => X (K) <= (I64 (K + 1) * MBP + 255)) and -- flat at I + 1, just written (for all K in Index_64 range I .. I32'Min (31, I + J) => X (K) <= (I64 (I + 1) * MBP + 255)) and -- flat at I, not written yet (for all K in Index_64 range I + J + 1 .. 31 => X (K) <= (I64 (I) * MBP + 255)) and -- falling from I to 1, just written (for all K in Index_64 range 32 .. (I + J) => X (K) <= (I64 (32 + I) - I64 (K)) * MBP + 255) and -- falling, from I to 1, but not written yet (for all K in Index_64 range I32'Max (32, I + J + 1) .. (I + 31) => X (K) <= (I64 (31 + I) - I64 (K)) * MBP + 255) and -- Zeroes - never written (for all K in Index_64 range I + 32 .. 63 => X (K) = 0) ); end loop; -- Substitute J = 31 into the above yields pragma Loop_Invariant ( T in Byte_Product and -- Lower bound (for all K in Index_64 => X (K) >= 0) and -- rising from 1 to I (for all K in Index_64 range 0 .. (I - 1) => X (K) <= (I64 (K + 1) * MBP + 255)) and -- flat at I + 1, just written (for all K in Index_64 range I .. 31 => X (K) <= (I64 (I + 1) * MBP + 255)) and -- falling from I to 1, just written (for all K in Index_64 range 32 .. (I + 31) => X (K) <= (I64 (32 + I) - I64 (K)) * MBP + 255) and -- Zeroes - never written (for all K in Index_64 range I + 32 .. 63 => X (K) = 0) ); end loop; -- Substitute I = 31 pragma Assert ( -- Lower bound (for all K in Index_64 => X (K) >= 0) and -- Upper bounds (for all K in Index_64 range 0 .. 30 => X (K) <= (I64 (K + 1) * MBP + 255)) and X (31) <= (32 * MBP + 255) and (for all K in Index_64 range 32 .. 62 => X (K) <= (63 - I64 (K)) * MBP + 255) and X (63) = 0 ); -- Simplify - this assert is equivalent to the precondition of ModL pragma Assert (for all K in Index_64 => X (K) in 0 .. (32 * MBP + 255)); SM (32 .. 63) := ModL (X); Sanitize (D); Sanitize (H); Sanitize (R); Sanitize_I64_Seq (X); pragma Unreferenced (D, H, R, X); end Sign; procedure Open (M : out Byte_Seq; Status : out Boolean; MLen : out I32; SM : in Byte_Seq; PK : in Signing_PK) is T : Bytes_32; P, Q : GF_Vector_4; LN : I32; begin MLen := -1; if SM'Length < 64 then M := (others => 0); Status := False; -- No sanitization required before this return return; end if; Unpackneg (Q, Status, Serialize (PK)); if not Status then M := (others => 0); Sanitize_GF_Vector_4 (Q); return; end if; M := SM; -- precondition ensures lengths match M (32 .. 63) := Serialize (PK); P := Scalarmult (Q, Hash_Reduce (M)); Q := Scalarbase (SM (32 .. 63)); -- Call to user-defined ""+"" for GF_Vector_4 P := P + Q; T := Pack (P); if not Equal (SM (0 .. 31), T) then M := (others => 0); Status := False; Sanitize (T); Sanitize_GF_Vector_4 (P); Sanitize_GF_Vector_4 (Q); return; end if; LN := I32 (I64 (SM'Length) - 64); M (0 .. LN - 1) := SM (64 .. LN + 63); MLen := LN; Status := True; Sanitize (T); Sanitize_GF_Vector_4 (P); Sanitize_GF_Vector_4 (Q); pragma Unreferenced (T, P, Q); end Open; end SPARKNaCl.Sign; ",12321,False,2278.130650157361,median "// document metadata = ENGR 727-001 Advanced Mechanics of Materials: Homework 4 Joby M. Anthony III :affiliation: PhD Student :document_version: 1.0 :revdate: February 16, 2022 // :description: // :keywords: :imagesdir: ./ENGR727_Homework4_JobyAnthonyIII :bibtex-file: ENGR727_Homework4_JobyAnthonyIII.bib :toc: auto :xrefstyle: short :sectnums: |,all| :chapter-refsig: Chap. :section-refsig: Sec. :stem: latexmath :eqnums: AMS :stylesdir: C:/Users/jmanthony1/Documents/GitHub/WeCANDoIt/Asciidoc/Testing/ENGR527-727 HW4 :stylesheet: asme.css :noheader: :nofooter: :docinfo: private :docinfodir: C:/Users/jmanthony1/Documents/GitHub/WeCANDoIt/Asciidoc/Testing/ENGR527-727 HW4 :front-matter: any :!last-update-label: // example variable // :fn-1: footnote:[] // Python modules <%! from engineering_notation import EngNumber as engr from joby_m_anthony_iii import numerical_methods as nm import numpy as np import sympy as sp %> // end document metadata // begin document // [abstract] // .Abstract // // *Keywords:* _{keywords}_ Problems: * [x] Problem 1 * [x] Problem 2 * [x] Problem 3 * [x] Problem 4 * [x] Problem 5 * [x] Problem 6 * [x] Problem 7 * [x] Problem 8 * [ ] Problem 9 * [x] Problem 10 * [x] Problem 11 * [x] Problem 12 [#sec-1, {counter:secs}, {counter:subs},{counter:figs}] == Problem 1 :subs: 0 :figs: 0 > A square, glass block in the side of a skyscraper is loaded so that the block is in a state of plane strain (stem:[\\epsilon_{zx} = \\epsilon_{zy} = \\epsilon_{zz} = 0]). > (a) Determine the displacements for the block for the deformations shown and the strain components for the stem:[xy]-coordinate axes. > (b) Determine the strain components for the stem:[XY]-axes. > [#fig-1-problem_statement] > .Adapted from assignment instructions. > image::./1-problem_statement_220221_192020_EST.png[caption=Figure {secs}-{counter:figs}. , reftext=""Fig. {secs}-{figs}""] > -- Problem Statement .Solution // solution codes <%! A0_1, B0_1, C0_1, D0_1 = (0, 1), (1, 1), (1, 0), (0, 0) # m A1_1, B1_1, C1_1, D1_1 = (-0.003, 0.0025), (-0.005, 0.0035), (-0.002, 0.001), (0, 0) # m theta_1 = np.radians(30) # rad sym_c_1 = [sp.Symbol(""c1""), sp.Symbol(""c2""), sp.Symbol(""c3""), sp.Symbol(""c4"")] sym_d_1 = [sp.Symbol(""d1""), sp.Symbol(""d2""), sp.Symbol(""d3""), sp.Symbol(""d4"")] u_1 = lambda c, x, y: c[0] + c[1]*x + c[2]*y + c[3]*x*y v_1 = lambda d, x, y: d[0] + d[1]*x + d[2]*y + d[3]*x*y sym_xy_1 = sym_x_1, sym_y_1 = sp.Symbol(""x""), sp.Symbol(""y"") sym_u_1 = sp.expand(u_1(sym_c_1, *sym_xy_1)) sym_v_1 = sp.expand(v_1(sym_d_1, *sym_xy_1)) Auv_1 = np.array([\\ # at A [1, A0_1[0], A0_1[1], A0_1[0]*A0_1[1]], \\ # at B [1, B0_1[0], B0_1[1], B0_1[0]*B0_1[1]], \\ # at C [1, C0_1[0], C0_1[1], C0_1[0]*C0_1[1]], \\ # at D [1, D0_1[0], D0_1[1], D0_1[0]*D0_1[1]], \\ ]) bu_1 = np.array([A1_1[0], B1_1[0], C1_1[0], D1_1[0]]).reshape((len(Auv_1), 1)) x0u_1 = np.ones_like(bu_1) c_1 = np.linalg.lstsq(Auv_1, bu_1)[0].reshape(1, len(x0u_1))[0] bv_1 = np.array([A1_1[1], B1_1[1], C1_1[1], D1_1[1]]).reshape((len(Auv_1), 1)) x0v_1 = np.ones_like(bv_1) d_1 = np.linalg.lstsq(Auv_1, bv_1)[0].reshape(1, len(x0v_1))[0] # build string function from constants f_1 = lambda sym_function, sym_variables, constants: sp.lambdify(sym_xy_1, sp.lambdify(sym_variables, sym_function)(*constants)) u_1 = lambda point: f_1(sym_u_1, (sym_c_1), c_1)(*point) sym_u_1 = sp.expand(u_1(sym_xy_1)) v_1 = lambda point: f_1(sym_v_1, (sym_d_1), d_1)(*point) sym_v_1 = sp.expand(v_1(sym_xy_1)) # determine form of derivative df_1 = lambda sym_function, sym_variable, point: sp.lambdify(sym_xy_1, sp.diff(sym_function, sym_variable))(*point) epsilon_1 = lambda point: np.array([\\ [df_1(sym_u_1, sym_x_1, point), df_1(sym_u_1, sym_y_1, point) + df_1(sym_v_1, sym_x_1, point)], \\ [df_1(sym_u_1, sym_y_1, point) + df_1(sym_v_1, sym_x_1, point), df_1(sym_v_1, sym_y_1, point)], \\ ]) epsA_1 = epsilon_1(A0_1) epsB_1 = epsilon_1(B0_1) epsC_1 = epsilon_1(C0_1) epsD_1 = epsilon_1(D0_1) eps_1a = epsA_1 # m/m eps_nO1a = np.linalg.norm(np.diag(eps_1a)) eps_tO1a = np.linalg.norm(eps_1a) - eps_nO1a s_1 = lambda p, dc: np.matmul(p, dc) t_1 = lambda p, s: np.sqrt(p**2 - s**2) # i_1b, j_1b = -4, -3 # ijk_1b = np.array([i_1b, j_1b]) # s_1b = s_1(eps_1a, ijk_1b) # dem_1b = np.sqrt(np.sum(np.power(ijk_1b, 2))) dc_1b = l_1b, m_1b = np.cos(theta_1), np.sin(theta_1) # ijk_1b/dem_1b # s_1b = s_1(eps_1a, dc_1b) s_1b = np.array([\\ [(eps_1a[0][0] + eps_1a[1][1])/2 + (eps_1a[0][0] + eps_1a[1][1])/2*np.cos(2*theta_1) + eps_1a[0][1]/2*np.sin(2*theta_1), -(eps_1a[0][0] - eps_1a[1][1])*np.sin(2*theta_1) + eps_1a[0][1]*np.cos(2*theta_1)], \\ [-(eps_1a[0][0] - eps_1a[1][1])*np.sin(2*(theta_1 + np.pi/2)) + eps_1a[0][1]*np.cos(2*(theta_1 + np.pi/2)), (eps_1a[0][0] + eps_1a[1][1])/2 + (eps_1a[0][0] + eps_1a[1][1])/2*np.cos(2*(theta_1 + np.pi/2)) + eps_1a[0][1]/2*np.sin(2*(theta_1 + np.pi/2))], \\ ]) t_1b = t_1(np.linalg.norm(s_1b), s_1b) %> The displacement for the block are as shown in xref:fig-1-problem_statement[]. The strain components along the stem:[xy]-axes can be found from building the strain state in matrix notation: [stem#eq-1-strain_state_form, reftext=""Eq. {secs}-{counter:eqs}""] ++++ \\begin{equation} [\\epsilon] = \\begin{bmatrix}\\frac{\\partial u}{\\partial x} & \\frac{\\partial u}{\\partial y} + \\frac{\\partial v}{\\partial x} \\\\\\ \\frac{\\partial u}{\\partial y} + \\frac{\\partial v}{\\partial x} & \\frac{\\partial v}{\\partial y}\\end{bmatrix} \\end{equation} ++++ Equations stem:[u(x, y)] and stem:[v(x, y)] can be found from solving a linear system of equations for which there are four equations and four unknowns: [stem#eq-1-equation_forms, reftext=""Eq. {secs}-{counter:eqs}""] ++++ \\begin{equation} \\begin{split} u(x, y) &:= \\begin{bmatrix}1 & x_{1} & y_{1} & xy_{1} \\\\\\ 1 & x_{2} & y_{2} & xy_{2} \\\\\\ 1 & x_{3} & y_{3} & xy_{3} \\\\\\ 1 & x_{4} & y_{4} & xy_{4}\\end{bmatrix}\\begin{bmatrix}c_{1} \\\\\\ c_{2} \\\\\\ c_{3} \\\\\\ c_{4}\\end{bmatrix} &= \\begin{bmatrix}\\delta_{x1} \\\\\\ \\delta_{x2} \\\\\\ \\delta_{x3} \\\\\\ \\delta_{x4}\\end{bmatrix} \\\\\\ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% d(x, y) &:= \\begin{bmatrix}1 & x_{1} & y_{1} & xy_{1} \\\\\\ 1 & x_{2} & y_{2} & xy_{2} \\\\\\ 1 & x_{3} & y_{3} & xy_{3} \\\\\\ 1 & x_{4} & y_{4} & xy_{4}\\end{bmatrix}\\begin{bmatrix}d_{1} \\\\\\ d_{2} \\\\\\ d_{3} \\\\\\ d_{4}\\end{bmatrix} &= \\begin{bmatrix}\\delta_{y1} \\\\\\ \\delta_{y2} \\\\\\ \\delta_{y3} \\\\\\ \\delta_{y4}\\end{bmatrix} \\end{split} \\end{equation} ++++ Solving xref:eq-1-equation_forms[] with input data from the appropriate points lends to xref:eq-1-equations[]. [stem#eq-1-equations, reftext=""Eq. {secs}-{counter:eqs}""] ++++ \\begin{equation} \\begin{split} u(x, y) &= ${sym_u_1} \\\\\\ v(x, y) &= ${sym_v_1} \\end{split} \\end{equation} ++++ This means that xref:eq-1-strain_state_form[] can now be solved to reveal the strain state of the glass block: stem:[[\\epsilon_{xy}\\] = \\begin{bmatrix}${engr(eps_1a[0][0])} & ${engr(eps_1a[0][1])} \\\\\\ ${engr(eps_1a[1][0])} & ${engr(eps_1a[1][1])}\\end{bmatrix}]. To find the strain components projected onto the stem:[XY]-axes, which is at some angle offset from the stem:[xy]-axes, xref:eq-1-strain_offset[] must be implemented. [stem#eq-1-strain_offset, reftext=""Eq. {secs}-{counter:eqs}""] ++++ \\begin{equation} \\begin{split} \\epsilon_{x'} &= \\epsilon_{x}\\cos^{2}(\\theta) + \\epsilon_{y}\\sin^{2}(\\theta) + \\gamma_{xy}\\sin(\\theta)\\cos(\\theta) \\\\\\ \\gamma_{x'y'} &= -(\\epsilon_{x} - \\epsilon_{y})\\sin(2\\theta) + \\gamma_{xy}\\cos(2\\theta) \\end{split} \\end{equation} ++++ , wherein stem:[\\epsilon_{y'}] can be found by replacing stem:[\\theta] with stem:[\\theta + \\frac{\\pi}{2}] in the equation for stem:[\\epsilon_{x'}]. This yields stem:[[\\epsilon_{XY}\\] = \\begin{bmatrix}${engr(s_1b[0][0])} & ${engr(s_1b[0][1])} \\\\\\ ${engr(s_1b[1][0])} & ${engr(s_1b[1][1])}\\end{bmatrix}] [#sec-2, {counter:secs}, {counter:subs},{counter:figs}] == Problem 2 :subs: 0 :figs: 0 > A square plate, stem:[1~m] on a long side, is loaded in a state of plane strain and is deformed as shown. > (a) Write expressions for the stem:[u] and stem:[v] displacements for any point on the plate. > (b) Determine the components of *Green Strain* in the plate. > (c) Determine the total *Green Strain* at point stem:[B] for a line element in the direction of line stem:[OB]. > (d) For point stem:[B], compare the components of strain from part (b) to the components of strain for *Small-Displacement Theory*. > (e) Compare the strain determined in part (c) to the corresponding strain using *Small-Displacement Theory*. > [#fig-2-problem_statement] > .Adapted from assignment instructions. > image::./2-problem_statement_220221_192420_EST.png[caption=Figure {secs}-{counter:figs}. , reftext=""Fig. {secs}-{figs}""] > -- Problem Statement .Solution // solution codes <%! A0_2, B0_2, C0_2, D0_2 = (0, 1), (1, 1), (1, 0), (0, 0) # m A1_2, B1_2, C1_2, D1_2 = (0, 0.0125), (-0.0125, 0.0125), (0.025, 0.0125), (0, 0) # m sym_c_2 = [sp.Symbol(""c1""), sp.Symbol(""c2""), sp.Symbol(""c3""), sp.Symbol(""c4"")] sym_d_2 = [sp.Symbol(""d1""), sp.Symbol(""d2""), sp.Symbol(""d3""), sp.Symbol(""d4"")] u_2 = lambda c, x, y: c[0] + c[1]*x + c[2]*y + c[3]*x*y v_2 = lambda d, x, y: d[0] + d[1]*x + d[2]*y + d[3]*x*y sym_xy_2 = sym_x_2, sym_y_2 = sp.Symbol(""x""), sp.Symbol(""y"") sym_u_2 = sp.expand(u_2(sym_c_2, *sym_xy_2)) sym_v_2 = sp.expand(v_2(sym_d_2, *sym_xy_2)) Auv_2 = np.array([\\ # at A [1, A0_2[0], A0_2[1], A0_2[0]*A0_2[1]], \\ # at B [1, B0_2[0], B0_2[1], B0_2[0]*B0_2[1]], \\ # at C [1, C0_2[0], C0_2[1], C0_2[0]*C0_2[1]], \\ # at D [1, D0_2[0], D0_2[1], D0_2[0]*D0_2[1]], \\ ]) bu_2 = np.array([A1_2[0], B1_2[0], C1_2[0], D1_2[0]]).reshape((len(Auv_2), 1)) x0u_2 = np.ones_like(bu_2) c_2 = np.linalg.lstsq(Auv_2, bu_2)[0].reshape(1, len(x0u_2))[0] bv_2 = np.array([A1_2[1], B1_2[1], C1_2[1], D1_2[1]]).reshape((len(Auv_2), 1)) x0v_2 = np.ones_like(bv_2) d_2 = np.linalg.lstsq(Auv_2, bv_2)[0].reshape(1, len(x0v_2))[0] # build string function from constants f_2 = lambda sym_function, sym_variables, constants: sp.lambdify(sym_xy_2, sp.lambdify(sym_variables, sym_function)(*constants)) u_2 = lambda point: f_2(sym_u_2, (sym_c_2), c_2)(*point) sym_u_2 = sp.expand(u_2(sym_xy_2)) v_2 = lambda point: f_2(sym_v_2, (sym_d_2), d_2)(*point) sym_v_2 = sp.expand(v_2(sym_xy_2)) # determine form of derivative df_2 = lambda sym_function, sym_variable, point: sp.lambdify(sym_xy_2, sp.diff(sym_function, sym_variable))(*point) epsilon_2 = lambda point: np.array([\\ [df_2(sym_u_2, sym_x_2, point), df_2(sym_u_2, sym_y_2, point) + df_2(sym_v_2, sym_x_2, point)], \\ [df_2(sym_u_2, sym_y_2, point) + df_2(sym_v_2, sym_x_2, point), df_2(sym_v_2, sym_y_2, point)], \\ ]) epsA_2a = epsilon_2(A0_2) epsB_2a = epsilon_2(B0_2) epsC_2a = epsilon_2(C0_2) epsD_2a = epsilon_2(D0_2) eps_2a = epsA_2a # m/m eps_nO2a = np.linalg.norm(np.diag(eps_2a)) eps_tO2a = np.linalg.norm(eps_2a) - eps_nO2a green_strain_2 = lambda point: np.array([\\ [df_2(sym_u_2, sym_x_2, point) + 0.5*(df_2(sym_u_2, sym_x_2, point)**2 + df_2(sym_v_2, sym_x_2, point)**2), df_2(sym_v_2, sym_x_2, point) + df_2(sym_u_2, sym_y_2, point) + df_2(sym_u_2, sym_x_2, point)*df_2(sym_u_2, sym_y_2, point) + df_2(sym_v_2, sym_x_2, point)*df_2(sym_v_2, sym_y_2, point)], \\ [df_2(sym_v_2, sym_x_2, point) + df_2(sym_u_2, sym_y_2, point) + df_2(sym_u_2, sym_x_2, point)*df_2(sym_u_2, sym_y_2, point) + df_2(sym_v_2, sym_x_2, point)*df_2(sym_v_2, sym_y_2, point), df_2(sym_v_2, sym_y_2, point) + 0.5*(df_2(sym_u_2, sym_y_2, point)**2 + df_2(sym_v_2, sym_y_2, point)**2)], \\ ]) epsA_2b = green_strain_2(A0_2) epsB_2b = green_strain_2(B0_2) epsC_2b = green_strain_2(C0_2) epsD_2b = green_strain_2(D0_2) eps_2b = epsA_2b # m/m s_2 = lambda p, dc: p*dc#np.matmul(p, dc) t_2 = lambda p, s: np.sqrt(p**2 - s**2) i_2c, j_2c = 1, 1 ijk_2c = np.array([i_2c, j_2c]) eps_2c = s_2(eps_2b, ijk_2c) dem_2c = np.sqrt(np.sum(np.power(ijk_2c, 2))) dc_2c = l_2c, m_2c = ijk_2c/dem_2c s_2c = s_2(eps_2b, dc_2c) t_2c = t_2(np.linalg.norm(s_2c), s_2c) norm_a = nm.norms(eps_2a).l_two() norm_b = nm.norms(eps_2b).l_two() norm_avg = (norm_a + norm_b)/2 perc_err_2d = np.abs((norm_a - norm_b)/norm_avg) norm_c = nm.norms(s_2c).l_two() perc_err_2e = np.abs((norm_a - norm_c)/norm_avg) %> As demonstrated in xref:sec-1[], expressions for displacement for any point on the plate may be found by solving xref:eq-1-equation_forms[]. This yields the following expressions: [stem] ++++ \\begin{split} u(x, y) &= ${sym_u_2} \\\\\\ v(x, y) &= ${sym_v_2} \\end{split} ++++ The strain state of the plate may be found by solving xref:eq-2-green_strain_form[] with the developed displacement equations. [stem#eq-2-green_strain_form, reftext=""Eq. {secs}-{counter:eqs}""] ++++ \\begin{equation} \\begin{split} \\epsilon_{x} &= \\frac{\\partial u}{\\partial x} + \\frac{1}{2}\\Bigl[\\Bigl(\\frac{\\partial u}{\\partial x}\\Bigr)^{2} + \\Bigl(\\frac{\\partial v}{\\partial x}\\Bigr)^{2}\\Bigr] \\\\\\ \\epsilon_{y} &= \\frac{\\partial v}{\\partial y} + \\frac{1}{2}\\Bigl[\\Bigl(\\frac{\\partial u}{\\partial y}\\Bigr)^{2} + \\Bigl(\\frac{\\partial v}{\\partial y}\\Bigr)^{2}\\Bigr] \\\\\\ \\gamma_{xy} &= \\frac{\\partial v}{\\partial x} + \\frac{\\partial u}{\\partial y} + \\frac{\\partial u}{\\partial x}\\frac{\\partial u}{\\partial y} + \\frac{\\partial v}{\\partial x}\\frac{\\partial v}{\\partial y} \\end{split} \\end{equation} ++++ The strain state, then, becomes: stem:[\\epsilon_{Green} = \\begin{bmatrix}${engr(eps_2b[0][0])} & ${engr(eps_2b[0][1])} \\\\\\ ${engr(eps_2b[1][0])} & ${engr(eps_2b[1][1])}\\end{bmatrix}]. The percent error between stem:[\\epsilon_{Green}] and stem:[\\epsilon_{Small} = \\begin{bmatrix}${engr(eps_2a[0][0])} & ${engr(eps_2a[0][1])} \\\\\\ ${engr(eps_2a[1][0])} & ${engr(eps_2a[1][1])}\\end{bmatrix}] is stem:[${round(perc_err_2d, 4)}~\\%]. Projecting this strain state along the line stem:[OB] can be found by the _direction of cosines_ for this stem:[<1, 1>] vector (stem:[l = ${round(l_2c, 4)}] and stem:[m = ${round(m_2c, 4)}]): stem:[(\\epsilon_{Green})_{OB} = \\begin{bmatrix}${engr(s_2c[0][0])} & ${engr(s_2c[0][1])} \\\\\\ ${engr(s_2c[1][0])} & ${engr(s_2c[1][1])}\\end{bmatrix}]. The percent error between stem:[\\epsilon_{Small}] and stem:[(\\epsilon_{Green})_{OB}] is stem:[${round(perc_err_2e, 4)}~\\%]. [#sec-3, {counter:secs}, {counter:subs},{counter:figs}] == Problem 3 :subs: 0 :figs: 0 > Solve Problem 2.3 from the textbook. > -- Problem Statement .Problem 2.3 A displacement field in a body is given by [stem#eq-3-problem_statement, reftext=""Eq. {secs}-{counter:eqs}""] ++++ \\begin{equation} \\begin{split} u = c(x^{2} + 10), &\\quad v = 2cyz, &\\quad w = c(-xy + z^{2}) \\end{split} \\end{equation} ++++ where stem:[c = 10^{-4}]. Determine the state of strain on an element positioned at stem:[(0, 2, 1)]. .Solution // solution codes <%! c_3 = 1e-4 point_3 = x_3, y_3, z_3 = 0, 2, 1 # m u_3 = lambda x, y, z: (x**2 + 10)*c_3 v_3 = lambda x, y, z: 2*(y*z)*c_3 w_3 = lambda x, y, z: (z**2 - x*y)*c_3 variables_3 = sym_x_3, sym_y_3, sym_z_3 = sp.Symbol(""x""), sp.Symbol(""y""), sp.Symbol(""z"") sym_u_3 = sp.expand(u_3(*variables_3)) sym_v_3 = sp.expand(v_3(*variables_3)) sym_w_3 = sp.expand(w_3(*variables_3)) # determine form of derivative df_3 = lambda sym_function, variable, point: sp.lambdify(variables_3, sp.diff(sym_function, variable))(*point) epsilon_3 = np.array([\\ [df_3(sym_u_3, sym_x_3, point_3), df_3(sym_u_3, sym_y_3, point_3) + df_3(sym_v_3, sym_x_3, point_3), df_3(sym_w_3, sym_x_3, point_3) + df_3(sym_u_3, sym_z_3, point_3)], \\ [0, df_3(sym_v_3, sym_y_3, point_3), df_3(sym_v_3, sym_z_3, point_3) + df_3(sym_w_3, sym_y_3, point_3)], \\ [0, 0, df_3(sym_w_3, sym_z_3, point_3)], \\ ]) %> The strain state can be found from determining the strain state at the point in the displacement field: [stem#eq-3-strain_state, reftext=""Eq. {secs}-{counter:eqs}""] ++++ \\begin{equation} [\\epsilon] = \\begin{bmatrix}\\epsilon_{x} = \\frac{\\partial u}{\\partial x} & \\gamma_{xy} = \\frac{\\partial u}{\\partial y} + \\frac{\\partial v}{\\partial x} & \\gamma_{xz} = \\frac{\\partial w}{\\partial x} + \\frac{\\partial u}{\\partial z} \\\\\\ 0 & \\epsilon_{y} = \\frac{\\partial v}{\\partial y} & \\gamma_{yz} = \\frac{\\partial v}{\\partial z} + \\frac{\\partial w}{\\partial y} \\\\\\ 0 & 0 & \\epsilon_{z} = \\frac{\\partial w}{\\partial z}\\end{bmatrix} \\end{equation} ++++ When xref:eq-3-problem_statement[] is plugged into xref:eq-3-strain_state[], this takes the form [stem] ++++ [\\epsilon] = \\begin{bmatrix}2x & 0 & -y \\\\\\ 0 & 2z & 2y - x \\\\\\ 0 & 0 & 2z\\end{bmatrix}\\times 10^{-4} ++++ which further yields xref:eq-5-strain_p[] for stem:[\\mathbf{\\epsilon}(x = 0, y = 2, z = 1)]. [stem#eq-3-strain_p, reftext=""Eq. {secs}-{counter:eqs}""] ++++ \\begin{equation} [\\epsilon] = \\begin{bmatrix}2 & 0 & -1 \\\\\\ 0 & 4 & 1 \\\\\\ 0 & 0 & 4\\end{bmatrix}\\times 10^{-4} \\end{equation} ++++ .Answer The strain tensor at point stem:[(0, 2, 1)], stem:[\\epsilon = \\begin{bmatrix}${engr(epsilon_3[0][0])} & ${engr(epsilon_3[0][1])} & ${engr(epsilon_3[0][2])} \\\\\\ ${engr(epsilon_3[1][0])} & ${engr(epsilon_3[1][1])} & ${engr(epsilon_3[1][2])} \\\\\\ ${engr(epsilon_3[2][0])} & ${engr(epsilon_3[2][1])} & ${engr(epsilon_3[2][2])}\\end{bmatrix}]. [#sec-4, {counter:secs}, {counter:subs},{counter:figs}] == Problem 4 :subs: 0 :figs: 0 > Solve Problem 2.4 from the textbook. > -- Problem Statement .Problem 2.4 The displacement field and strain distribution in a member have the form [stem#eq-4-problem_statement, reftext=""Eq. {secs}-{counter:eqs}""] ++++ \\begin{equation} \\begin{split} u &= a_{0}x^{2}y^{2} + a_{1}xy^{2} + a_{2}x^{2}y \\\\\\ v &= b_{0}x^{2}y + b_{1}xy \\\\\\ \\gamma_{xy} &= c_{0}x^{2}y + c_{1}xy + c_{2}x^{2} + c_{3}y^{2} \\end{split} \\end{equation} ++++ Which relationships connecting the constraints (stem:[a]'s, stem:[b]'s, and stem:[c]'s) make the foregoing expressions (xref:eq-4-problem_statement[]) possible? .Answer These equations assume _plane-strain_; therefore, the constants can be found from the contribution of the respective derivatives of each displacement field equation. [#sec-5, {counter:secs}, {counter:subs},{counter:figs}] == Problem 5 :subs: 0 :figs: 0 > Solve Problem 2.9 from the textbook. > -- Problem Statement .Problem 2.9 A stem:[100~mm] by stem:[150~mm] rectangular plate stem:[QABC] is deformed into the shape shown by the dashed lines in xref:fig-5-problem_statement[]. All dimensions shown in the figure are in millimeters. Determine at point stem:[Q] (a) the strain components stem:[\\epsilon_{x}], stem:[\\epsilon_{y}], and stem:[\\gamma_{xy}] and (b) the principal strains and the direction of the principal axes. [#fig-5-problem_statement] .Adapted from cite:[uguralAdvancedMechanicsMaterials2019]. image::./5-problem_statement_220221_194927_EST.png[caption=Figure {secs}-{counter:figs}. , reftext=""Fig. {secs}-{figs}""] .Solution // solution codes <%! A0_5, B0_5, C0_5, D0_5 = (0, 1), (1, 1), (1, 0), (0, 0) # m A1_5, B1_5, C1_5, D1_5 = (0, 0.0125), (-0.0125, 0.0125), (0.025, 0.0125), (0, 0) # m sym_c_5 = [sp.Symbol(""c1""), sp.Symbol(""c2""), sp.Symbol(""c3""), sp.Symbol(""c4"")] sym_d_5 = [sp.Symbol(""d1""), sp.Symbol(""d2""), sp.Symbol(""d3""), sp.Symbol(""d4"")] u_5 = lambda c, x, y: c[0] + c[1]*x + c[2]*y + c[3]*x*y v_5 = lambda d, x, y: d[0] + d[1]*x + d[2]*y + d[3]*x*y sym_xy_5 = sym_x_5, sym_y_5 = sp.Symbol(""x""), sp.Symbol(""y"") sym_u_5 = sp.expand(u_5(sym_c_5, *sym_xy_5)) sym_v_5 = sp.expand(v_5(sym_d_5, *sym_xy_5)) Auv_5 = np.array([\\ # at A [1, A0_5[0], A0_5[1], A0_5[0]*A0_5[1]], \\ # at B [1, B0_5[0], B0_5[1], B0_5[0]*B0_5[1]], \\ # at C [1, C0_5[0], C0_5[1], C0_5[0]*C0_5[1]], \\ # at D [1, D0_5[0], D0_5[1], D0_5[0]*D0_5[1]], \\ ]) bu_5 = np.array([A1_5[0], B1_5[0], C1_5[0], D1_5[0]]).reshape((len(Auv_5), 1)) x0u_5 = np.ones_like(bu_5) c_5 = np.linalg.lstsq(Auv_5, bu_5)[0].reshape(1, len(x0u_5))[0] bv_5 = np.array([A1_5[1], B1_5[1], C1_5[1], D1_5[1]]).reshape((len(Auv_5), 1)) x0v_5 = np.ones_like(bv_5) d_5 = np.linalg.lstsq(Auv_5, bv_5)[0].reshape(1, len(x0v_5))[0] # build string function from constants f_5 = lambda sym_function, sym_variables, constants: sp.lambdify(sym_xy_5, sp.lambdify(sym_variables, sym_function)(*constants)) u_5 = lambda point: f_5(sym_u_5, (sym_c_5), c_5)(*point) sym_u_5 = sp.expand(u_5(sym_xy_5)) v_5 = lambda point: f_5(sym_v_5, (sym_d_5), d_5)(*point) sym_v_5 = sp.expand(v_5(sym_xy_5)) # determine form of derivative df_5 = lambda sym_function, sym_variable, point: sp.lambdify(sym_xy_5, sp.diff(sym_function, sym_variable))(*point) epsilon_5 = lambda point: np.array([\\ [df_5(sym_u_5, sym_x_5, point), df_5(sym_u_5, sym_y_5, point) + df_5(sym_v_5, sym_x_5, point), 0], \\ [df_5(sym_u_5, sym_y_5, point) + df_5(sym_v_5, sym_x_5, point), df_5(sym_v_5, sym_y_5, point), 0], \\ [0, 0, 0] \\ ]) epsA_5 = epsilon_5(A0_5) epsB_5 = epsilon_5(B0_5) epsC_5 = epsilon_5(C0_5) epsD_5 = epsilon_5(D0_5) eps_5 = epsA_5 # m/m dir_5 = 0.5*np.arctan(eps_5[0][1]/(eps_5[0][0] - eps_5[1][1])) # rad j1_5 = np.trace(eps_5) j2_5 = eps_5[0][0]*eps_5[1][1] + eps_5[0][0]*eps_5[2][2] + eps_5[1][1]*eps_5[2][2] - eps_5[0][1]**2 - eps_5[2][1]**2 - eps_5[0][2]**2 j3_5 = sp.det(sp.Matrix(eps_5)) eps_sym = sp.Symbol(""eps"") f_5 = eps_sym**3 - j1_5*eps_sym**2 - j2_5*eps_sym - j3_5 principals_5 = [] for p in sp.solve(f_5, eps_sym): principals_5.append(complex(p)) principals_5 = np.sort(np.abs(principals_5))[::-1] mag_5 = 0 for p in principals_5: if np.abs(p) >= mag_5: mag_5 = np.abs(p) t_max_5 = np.average(principals_5[:1]) %> Following a procedure similar to that displayed in xref:sec-1[] yields the strain state: stem:[\\begin{bmatrix}${engr(eps_5[0][0])} & ${engr(eps_5[0][1])} \\\\\\ ${engr(eps_5[1][0])} & ${engr(eps_5[1][1])}\\end{bmatrix}] which yields the principal strains: stem:[\\epsilon_{1}, \\epsilon_{2}, \\epsilon_{3} = ${engr(principals_5[0])}, ${engr(principals_5[1])}, ${engr(principals_5[2])}] in the stem:[\\theta_{p} = ${engr(dir_5)}~rad] direction. [#sec-6, {counter:secs}, {counter:subs},{counter:figs}] == Problem 6 :subs: 0 :figs: 0 > Solve Problem 2.12 from the textbook. > -- Problem Statement .Problem 2.12 A thin, rectangular plate stem:[a = 20~mm \\times b = 12~mm] (xref:fig-6-problem_statement[]) is acted upon by a stress distribution resulting in the uniform strains stem:[\\epsilon_{x} = 300\\mu], stem:[\\epsilon_{y} = 500\\mu], and stem:[\\gamma_{xy} = 200\\mu]. Determine the changes in length of diagonals stem:[QB] and stem:[AC]. [#fig-6-problem_statement] .Adapted from cite:[uguralAdvancedMechanicsMaterials2019]. image::./6-problem_statement_220221_195504_EST.png[caption=Figure {secs}-{counter:figs}. , reftext=""Fig. {secs}-{figs}""] .Solution // solution codes <%! a0_6, b0_6 = 20, 12 # mm, mm eps_6 = np.array([\\ [300, 200, 0], \\ [200, 500, 0], \\ [0, 0, 0], \\ ])/1e6 # strain AC0_6 = QB0_6 = np.sqrt(a0_6**2 + b0_6**2) delta_a_6, delta_b_6 = eps_6[0][0]*a0_6, eps_6[1][1]*b0_6 # mm, mm a1_6, b1_6 = a0_6 + delta_a_6, b0_6 + delta_b_6 AC1_6 = QB1_6 = np.sqrt(a1_6**2 + b1_6**2) deltaAC_6 = deltaQB_6 = AC1_6 - AC0_6 %> Because the plate undergoes a displacement that yields a symmetric strain state, the change in length for diagonals stem:[AC] and stem:[QB] are equal and found by finding the difference of the hypotenuse: e.g. stem:[a' = (1 + \\epsilon_{x})a_{0} = ${engr(a1_6)}]. Therefore, stem:[\\Delta l_{AC} = ${engr(deltaAC_6)}~m] and stem:[\\Delta l_{QB} = ${engr(deltaQB_6)}~m]. [#sec-7, {counter:secs}, {counter:subs},{counter:figs}] == Problem 7 :subs: 0 :figs: 0 > Solve Problem 2.22 from the textbook. > -- Problem Statement .Problem 2.22 Solve Problem 2.21 cite:[uguralAdvancedMechanicsMaterials2019] for a state of strain given by [stem#eq-7-problem_statement, reftext=""Eq. {secs}-{counter:eqs}""] ++++ \\begin{equation} \\begin{bmatrix}400 & 100 & 0 \\\\\\ 100 & 0 & -200 \\\\\\ 0 & -200 & 600\\end{bmatrix}~\\mu \\end{equation} ++++ Problem 2.21 asks to determine (a) the strain invariants; (b) the normal strain in the stem:[x'] direction which is directed at an angle stem:[\\theta = 30~^{\\circ}] from the stem:[x]-axis; (c) the principal strains stem:[\\epsilon_{1}], stem:[\\epsilon_{2}], and stem:[\\epsilon_{3}]; and, (d) the maximum shear strain. .Solution // solution codes <%! eps_7 = np.array([\\ [400, 100, 0], \\ [100, 0, -200], \\ [0, -200, 600], \\ ])/1e6 n_7 = lambda p, dc: np.matmul(p, dc) t_7 = lambda p, s: np.sqrt(p**2 - s**2) j1_7 = np.trace(eps_7) # MPa j2_7 = eps_7[0][0]*eps_7[1][1] + eps_7[0][0]*eps_7[2][2] + eps_7[1][1]*eps_7[2][2] - eps_7[0][1]**2 - eps_7[2][1]**2 - eps_7[0][2]**2 # MPa**2 j3_7 = sp.det(sp.Matrix(eps_7)) # MPa**3 eps_sym = sp.Symbol(""eps"") f_7 = eps_sym**3 - j1_7*eps_sym**2 - j2_7*eps_sym - j3_7 principals_7 = [] for p in sp.solve(f_7, eps_sym): principals_7.append(complex(p)) mag_7 = 0 for p in principals_7: if np.abs(p) >= mag_7: mag_7 = np.abs(p) dir_7 = np.arctan(p.imag/p.real) t_max_7 = np.average(np.sort(np.abs(principals_7))[:1]) theta1_b = np.radians(30) # rad i_7b, j_7b, k_7b = 1, 1, 1 i_7b, j_7b, k_7b = i_7b*np.cos(theta1_b), j_7b*np.sin(theta1_b), k_7b ijk_7b = np.array([i_7b, j_7b, k_7b]) eps_7b = n_7(eps_7, ijk_7b) dem_7b = np.sqrt(np.sum(np.power(ijk_7b, 2))) dc_7b = l_7b, m_7b, n_7b = ijk_7b/dem_7b s_7b = n_7(eps_7b, dc_7b) t_7b= t_7(np.linalg.norm(eps_7b), s_7b) %> // i_2a, j_2a, k_2a = 2, 1, 2 // ijk_2a = np.array([i_2a, j_2a, k_2a]) // eps_7a = s_2(eps_7, ijk_2a) // dem_2a = np.sqrt(np.sum(np.power(ijk_2a, 2))) // dc_2a = l_2a, m_2a, n_2a = ijk_2a/dem_2a // s_2a = s_2(eps_7a, dc_2a) // t_2a = t_2(np.linalg.norm(eps_7a), s_2a) .Answers The strain invariants of given strain state (xref:eq-7-problem_statement[]): [stem] ++++ \\begin{split} J_{1} &= p_{x} + p_{y} + p_{z} = ${engr(j1_7)} \\\\\\ J_{2} &= p_{x}p_{y} + p_{x}p_{z} + p_{y}p_{z} \\\\\\ &\\quad- p_{xy}^{2} - p_{yz}^{2} - p_{xz}^{2} \\\\\\ J_{2} &= ${engr(j2_7)} \\\\\\ J_{3} &= \\|\\mathbf{p}\\| = ${round(j3_7, 4)} \\end{split} ++++ The normal strain along stem:[x'], which is stem:[\\theta = 30~^{\\circ}] up from the stem:[x]-axis, is stem:[\\epsilon_{x'} = ${engr(s_7b)}]. The principal strains come from solving stem:[\\epsilon_{p}^{3} - J_{1}\\epsilon_{p}^{2} + J_{2}\\epsilon_{p} - J_{3} = 0]: * stem:[\\epsilon_{1} = ${engr(np.sort(np.abs(principals_7))[::-1][0])}] * stem:[\\epsilon_{2} = ${engr(np.sort(np.abs(principals_7))[::-1][1])}] * stem:[\\epsilon_{3} = ${engr(np.sort(np.abs(principals_7))[::-1][2])}] The maximum principal strain (magnitude and direction), stem:[\\epsilon_{1} = ${engr(mag_7)}~\\angle~${engr(dir_7)}~rad]. The magnitude of the shear strain is the average of the principal strains (from *Mohr's Circle*): stem:[\\gamma_{max} = ${engr(t_max_7)}]. [#sec-8, {counter:secs}, {counter:subs},{counter:figs}] == Problem 8 :subs: 0 :figs: 0 > Solve Problem 2.24 from the textbook. > -- Problem Statement .Problem 2.24 At a point in a loaded frame, the strain with respect to the coordinate set stem:[xyz] is [stem#eq-8-problem_statement, reftext=""Eq. {secs}-{counter:eqs}""] ++++ \\begin{equation} \\begin{bmatrix}-300 & -583 & -300 \\\\\\ -583 & 200 & -67 \\\\\\ -300 & -67 & -200\\end{bmatrix}~\\mu \\end{equation} ++++ Determine (a) the magnitudes and directions of the principal strains and (b) the maxmimum shear strains. .Solution // solution codes <%! eps_8 = np.array([\\ [-300, -583, -300], \\ [-583, 200, -67], \\ [-300, -67, -200], \\ ])/1e6 n_8 = lambda p, dc: np.matmul(p, dc) t_8 = lambda p, s: np.sqrt(p**2 - s**2) j1_8 = np.trace(eps_8) # MPa j2_8 = eps_8[0][0]*eps_8[1][1] + eps_8[0][0]*eps_8[2][2] + eps_8[1][1]*eps_8[2][2] - eps_8[0][1]**2 - eps_8[2][1]**2 - eps_8[0][2]**2 # MPa**2 j3_8 = sp.det(sp.Matrix(eps_8)) # MPa**3 eps_sym = sp.Symbol(""eps"") f_8 = eps_sym**3 - j1_8*eps_sym**2 - j2_8*eps_sym - j3_8 principals_8 = [] for p in sp.solve(f_8, eps_sym): principals_8.append(complex(p)) mag_8 = 0 for p in principals_8: if np.abs(p) >= mag_8: mag_8 = np.abs(p) dir_8 = np.arctan(p.imag/p.real) t_max_8 = np.average(np.sort(np.abs(principals_8))[:1]) %> .Answers The principal strains come from solving stem:[\\epsilon_{p}^{3} - J_{1}\\epsilon_{p}^{2} + J_{2}\\epsilon_{p} - J_{3} = 0]: The strain invariants of given strain state (xref:eq-8-problem_statement[]): [stem] ++++ \\begin{split} J_{1} &= p_{x} + p_{y} + p_{z} = ${engr(j1_8)} \\\\\\ J_{2} &= p_{x}p_{y} + p_{x}p_{z} + p_{y}p_{z} \\\\\\ &\\quad- p_{xy}^{2} - p_{yz}^{2} - p_{xz}^{2} \\\\\\ J_{2} &= ${engr(j2_8)} \\\\\\ J_{3} &= \\|\\mathbf{p}\\| = ${round(j3_8, 4)} \\end{split} ++++ * stem:[\\epsilon_{1} = ${engr(np.sort(np.abs(principals_8))[::-1][0])}] * stem:[\\epsilon_{2} = ${engr(np.sort(np.abs(principals_8))[::-1][1])}] * stem:[\\epsilon_{3} = ${engr(np.sort(np.abs(principals_8))[::-1][2])}] The maximum principal strain (magnitude and direction), stem:[\\epsilon_{1} = ${engr(mag_8)}~\\angle~${engr(dir_8)}~rad]. The magnitude of the shear strain is the average of the principal strains (from *Mohr's Circle*): stem:[\\gamma_{max} = ${engr(t_max_8)}]. [#sec-9, {counter:secs}, {counter:subs},{counter:figs}] == Problem 9 :subs: 0 :figs: 0 > Solve Problem 2.28 from the textbook. > -- Problem Statement .Problem 2.28 A stem:[16~mm \\times 16~mm] square stem:[ABCD] is sketched on a plate before loading. Subsequent to loading, the square becomes the rhombus illustrated in xref:fig-9-problem_statement[]. Determine the (a) modulus of elasticity, (b) Poisson's Ratio, and (c) the shear modulus of elasticity. [#fig-9-problem_statement] .Adapted from cite:[uguralAdvancedMechanicsMaterials2019]. image::./9-problem_statement_220221_200917_EST.png[caption=Figure {secs}-{counter:figs}. , reftext=""Fig. {secs}-{figs}""] [#sec-10, {counter:secs}, {counter:subs},{counter:figs}] == Problem 10 :subs: 0 :figs: 0 > Solve Problem 2.52 from the textbook. > -- Problem Statement .Problem 2.52 The distribution of stress in a structural member is given (in megapascals) by Eqs. (d) of Example 1.2 of Chapter 1 (xref:eq-10-problem_statement[]). Calculate the strains at the specified point stem:[Q(\\frac{3}{4}, \\frac{1}{4}, \\frac{1}{2})] for stem:[E = 200~GPa] and stem:[\\nu = 0.25]. [stem#eq-10-problem_statement, reftext=""Eq. {secs}-{counter:eqs}""] ++++ \\begin{equation} \\begin{split} \\sigma_{x} = -x^{3} + y^{2}, &\\quad \\tau_{xy} = 5z + 2y^{2} \\\\\\ \\sigma_{y} = 2x^{2} + \\frac{1}{2}y^{2}, &\\quad \\tau_{xz} = xz^{3} + x^{2}y \\\\\\ \\sigma_{z} = 4y^{2} - z^{3}, &\\quad \\tau_{yz} = 0 \\end{split} \\end{equation} ++++ .Solution // solution codes <%! point_10 = x_10, y_10, z_10 = 3/4, 1/4, 1/2 # mm E_10, nu_10 = 200e3, 0.25 # MPa, ~ G_10 = E_10/(2*(1 + nu_10)) # MPa sx_10 = lambda x, y, z: -(x**3) + y**2 sy_10 = lambda x, y, z: 2*(x**2) + (y**2)/2 sz_10 = lambda x, y, z: 4*(y**2) - z**3 txy_10 = lambda x, y, z: 5*z + 2*(y**2) txz_10 = lambda x, y, z: x*(z**3) + (x**2)*y tyz_10 = lambda x, y, z: 0 f_10 = lambda point: np.array([\\ [(sx_10(*point) - nu_10*(sy_10(*point) + sz_10(*point)))/E_10, txy_10(*point)/G_10, txz_10(*point)/G_10], \\ [0, (sy_10(*point) - nu_10*(sx_10(*point) + sz_10(*point)))/E_10, tyz_10(*point)/G_10], \\ [0, 0, (sz_10(*point) - nu_10*(sx_10(*point) + sy_10(*point)))/E_10], \\ ]) epsilon_10 = f_10(point_10) %> The strain state can be found from determining the strain state at the point in the displacement field: [stem#eq-10-strain_state, reftext=""Eq. {secs}-{counter:eqs}""] ++++ \\begin{equation} [\\epsilon] = \\begin{bmatrix}\\epsilon_{x} = \\frac{1}{E}[\\sigma_{x} - \\nu(\\sigma_{y} + \\sigma_{z})] & \\gamma_{xy} = \\frac{\\tau_{xy}}{G} & \\gamma_{xz} = \\frac{\\tau_{xz}}{G} \\\\\\ 0 & \\epsilon_{y} = \\frac{1}{E}[\\sigma_{y} - \\nu(\\sigma_{x} + \\sigma_{z})] & \\gamma_{yz} = \\frac{\\tau_{yz}}{G} \\\\\\ 0 & 0 & \\epsilon_{z} = \\frac{1}{E}[\\sigma_{z} - \\nu(\\sigma_{x} + \\sigma_{y})]\\end{bmatrix} \\end{equation} ++++ When xref:eq-10-problem_statement[] and point stem:[Q] are plugged into xref:eq-10-strain_state[], this yields xref:eq-5-strain_p[] for stem:[\\mathbf{\\epsilon}(x = 0, y = 2, z = 1)]. [stem#eq-10-strain_p, reftext=""Eq. {secs}-{counter:eqs}""] ++++ \\begin{equation} [\\epsilon] = \\begin{bmatrix}${engr(epsilon_10[0][0])} & ${engr(epsilon_10[0][1])} & ${engr(epsilon_10[0][2])} \\\\\\ ${engr(epsilon_10[1][0])} & ${engr(epsilon_10[1][1])} & ${engr(epsilon_10[1][2])} \\\\\\ ${engr(epsilon_10[2][0])} & ${engr(epsilon_10[2][1])} & ${engr(epsilon_10[2][2])}\\end{bmatrix} \\end{equation} ++++ .Answer The strain tensor at point stem:[(0, 2, 1)], stem:[[\\epsilon\\] = \\begin{bmatrix}${engr(epsilon_10[0][0])} & ${engr(epsilon_10[0][1])} & ${engr(epsilon_10[0][2])} \\\\\\ ${engr(epsilon_10[1][0])} & ${engr(epsilon_10[1][1])} & ${engr(epsilon_10[1][2])} \\\\\\ ${engr(epsilon_10[2][0])} & ${engr(epsilon_10[2][1])} & ${engr(epsilon_10[2][2])}\\end{bmatrix}]. [#sec-11, {counter:secs}, {counter:subs},{counter:figs}] == Problem 11 :subs: 0 :figs: 0 > Solve Problem 2.53 from the textbook. > -- Problem Statement .Problem 2.53 An aluminum alloy plate (stem:[E = 70~GPa], stem:[\\nu = \\frac{1}{3}]) of dimensions stem:[a = 300~mm], stem:[b = 400~mm], and thickness stem:[t = 10~mm] is subjected to biaxial stresses as shown in xref:fig-11-problem_statement[]. Calculate the change in (a) the length stem:[AB] and (b) the volume of the plate. [#fig-11-problem_statement] .Adapted from cite:[uguralAdvancedMechanicsMaterials2019]. image::./11-problem_statement_220221_201834_EST.png[caption=Figure {secs}-{counter:figs}. , reftext=""Fig. {secs}-{figs}""] .Solution // solution codes <%! def strain_tensor_11(sigma, E, nu): G = E/(2*(1 + nu)) e = np.trace(sigma)*(1 - 2*nu)/E strain = np.diagflat(sigma.diagonal()/E) strain -= np.array([\\ [sigma[1][1] + sigma[2][2]], \\ [sigma[0][0] + sigma[2][2]], \\ [sigma[0][0] + sigma[1][1]], \\ ])*nu/E strain += np.diagflat(np.diag(sigma, k=1)/G, k=1) strain += np.diagflat(np.diag(sigma, k=2)/G, k=2) return G, e, strain a0_11, b0_11, t0_11 = 300, 400, 10 # mm, mm, mm E_11, nu_11 = 70e3, 1/3 # MPa, ~ sigma_11 = np.array([\\ [30, 0, 0], \\ [0, 90, 0], \\ [0, 0, 0], \\ ]) V0_11 = a0_11*b0_11*t0_11 # mm3 G_11, e_11, epsilon_11 = strain_tensor_11(sigma_11, E_11, nu_11) delta_b_11, deltaV1_11 = epsilon_11[1][1]*b0_11, e_11*V0_11 # mm, mm3 %> [stem#eq-11-strain_state_form, reftext=""Eq. {secs}-{counter:eqs}""] ++++ \\begin{equation} \\begin{split} \\epsilon_{x} &= \\frac{\\sigma_{x}}{E} - \\nu\\frac{\\sigma_{y}}{E} \\\\\\ \\epsilon_{y} &= \\frac{\\sigma_{y}}{E} - \\nu\\frac{\\sigma_{x}}{E} \\\\\\ \\gamma_{xy} &= \\frac{\\tau_{xy}}{G} \\end{split} \\end{equation} ++++ Using the provided stress tensor, the strain state may be found by solving xref:eq-11-strain_state_form[] which yields: stem:[[\\epsilon\\] = \\begin{bmatrix}${engr(epsilon_11[0][0])} & ${engr(epsilon_11[0][1])} \\\\\\ ${engr(epsilon_11[1][0])} & ${engr(epsilon_11[1][1])}\\end{bmatrix}]. Therefore, stem:[\\Delta b = \\epsilon_{y}b = ${engr(delta_b_11)}~mm] and stem:[\\Delta V = (\\epsilon_{x} + \\epsilon_{y})V_{0} = ${engr(deltaV1_11)}~mm^{3}]. [#sec-12, {counter:secs}, {counter:subs},{counter:figs}] == Problem 12 :subs: 0 :figs: 0 > Solve Problem 2.54 from the textbook. > -- Problem Statement .Problem 2.54 The steel, rectangular parallelepiped (stem:[E = 200~GPa] and stem:[\\nu = 0.3]) shown in xref:fig-12-problem_statement[] has dimensions stem:[a = 250~mm], stem:[b = 200~mm], and stem:[c = 150~mm]. It is subjected to triaxial stresses stem:[\\sigma_{x} = -60~MPa], stem:[\\sigma_{y} = -50~MPa], and stem:[\\sigma_{z} = -40~MPa] acting on the stem:[x], stem:[y], and stem:[z] faces. Determine (a) the changes stem:[\\Delta a], stem:[\\Delta b], and stem:[\\Delta c] in the dimensions of the block, and (b) the change stem:[\\Delta V] in the volume. [#fig-12-problem_statement] .Adapted from cite:[uguralAdvancedMechanicsMaterials2019]. image::./12-problem_statement_220221_202215_EST.png[caption=Figure {secs}-{counter:figs}. , reftext=""Fig. {secs}-{figs}""] .Solution // solution codes <%! def strain_tensor_12(sigma, E, nu): G = E/(2*(1 + nu)) e = np.trace(sigma)*(1 - 2*nu)/E strain = np.diagflat(sigma.diagonal()/E) strain -= np.array([\\ [sigma[1][1] + sigma[2][2]], \\ [sigma[0][0] + sigma[2][2]], \\ [sigma[0][0] + sigma[1][1]], \\ ])*nu/E strain += np.diagflat(np.diag(sigma, k=1)/G, k=1) strain += np.diagflat(np.diag(sigma, k=2)/G, k=2) return G, e, strain a0_12, b0_12, c0_12 = D0_12 = np.array([250, 200, 150]) # mm, mm, mm E_12, nu_12 = 200e3, 0.3 # MPa, ~ sigma_12 = np.array([\\ [-60, 0, 0], \\ [0, -50, 0], \\ [0, 0, -40], \\ ]) V0_12 = a0_12*b0_12*c0_12 # mm3 G_12, e_12, epsilon_12 = strain_tensor_12(sigma_12, E_12, nu_12) delta_a_12, delta_b_12, delta_c_12 = np.matmul(epsilon_12, D0_12) # mm deltaV1_12 = e_12*V0_12 # mm3 %> Following a similar procedure as in xref:sec-11[], the changes in length for each side and the final volume of the parallelepiped are: stem:[\\Delta a = ${round(delta_a_12, 4)}~mm], stem:[\\Delta b = ${round(delta_b_12, 4)}~mm], stem:[\\Delta c = ${round(delta_c_12, 4)}~mm], and stem:[V_{f} = [1 + (\\epsilon_{x} - 2\\nu\\epsilon_{x})\\]dxdydz = V_{0} + \\Delta V = ${engr(deltaV1_12)}~mm^{3}]. // [appendix#sec-appendix-Figures] // == Figures [bibliography] == Bibliography bibliography::[] // end document // that's all folks",16182,True,3047.1072589313376,median "pragma Ada_2005; pragma Style_Checks (Off); pragma Warnings (Off); with Interfaces.C; use Interfaces.C; with GLIB; -- with GStreamer.GST_Low_Level.glibconfig_h; with glib; with glib.Values; with System; limited with GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstbuffer_h; with System; package GStreamer.GST_Low_Level.gstreamer_0_10_gst_base_gstbytereader_h is -- arg-macro: function GST_BYTE_READER (reader) -- return (GstByteReader *) (reader); -- arg-macro: procedure gst_byte_reader_dup_string (reader, str) -- gst_byte_reader_dup_string_utf8(reader,str) -- arg-macro: procedure gst_byte_reader_skip_string (reader) -- gst_byte_reader_skip_string_utf8(reader) -- arg-macro: procedure gst_byte_reader_get_string (reader, str) -- gst_byte_reader_get_string_utf8(reader,str) -- arg-macro: procedure gst_byte_reader_peek_string (reader, str) -- gst_byte_reader_peek_string_utf8(reader,str) -- arg-macro: procedure GST_BYTE_READER_INIT (data, size) -- {data, size, 0} -- arg-macro: procedure GST_BYTE_READER_INIT_FROM_BUFFER (buffer) -- {GST_BUFFER_DATA (buffer), GST_BUFFER_SIZE (buffer), 0} -- arg-macro: procedure gst_byte_reader_get_remaining (reader) -- _gst_byte_reader_get_remaining_inline(reader) -- arg-macro: procedure gst_byte_reader_get_size (reader) -- _gst_byte_reader_get_size_inline(reader) -- arg-macro: procedure gst_byte_reader_get_pos (reader) -- _gst_byte_reader_get_pos_inline(reader) -- arg-macro: procedure gst_byte_reader_get_uint8 (reader, val) -- G_LIKELY(_gst_byte_reader_get_uint8_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_get_int8 (reader, val) -- G_LIKELY(_gst_byte_reader_get_int8_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_get_uint16_le (reader, val) -- G_LIKELY(_gst_byte_reader_get_uint16_le_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_get_int16_le (reader, val) -- G_LIKELY(_gst_byte_reader_get_int16_le_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_get_uint16_be (reader, val) -- G_LIKELY(_gst_byte_reader_get_uint16_be_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_get_int16_be (reader, val) -- G_LIKELY(_gst_byte_reader_get_int16_be_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_get_uint24_le (reader, val) -- G_LIKELY(_gst_byte_reader_get_uint24_le_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_get_int24_le (reader, val) -- G_LIKELY(_gst_byte_reader_get_int24_le_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_get_uint24_be (reader, val) -- G_LIKELY(_gst_byte_reader_get_uint24_be_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_get_int24_be (reader, val) -- G_LIKELY(_gst_byte_reader_get_int24_be_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_get_uint32_le (reader, val) -- G_LIKELY(_gst_byte_reader_get_uint32_le_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_get_int32_le (reader, val) -- G_LIKELY(_gst_byte_reader_get_int32_le_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_get_uint32_be (reader, val) -- G_LIKELY(_gst_byte_reader_get_uint32_be_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_get_int32_be (reader, val) -- G_LIKELY(_gst_byte_reader_get_int32_be_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_get_uint64_le (reader, val) -- G_LIKELY(_gst_byte_reader_get_uint64_le_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_get_int64_le (reader, val) -- G_LIKELY(_gst_byte_reader_get_int64_le_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_get_uint64_be (reader, val) -- G_LIKELY(_gst_byte_reader_get_uint64_be_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_get_int64_be (reader, val) -- G_LIKELY(_gst_byte_reader_get_int64_be_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_peek_uint8 (reader, val) -- G_LIKELY(_gst_byte_reader_peek_uint8_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_peek_int8 (reader, val) -- G_LIKELY(_gst_byte_reader_peek_int8_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_peek_uint16_le (reader, val) -- G_LIKELY(_gst_byte_reader_peek_uint16_le_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_peek_int16_le (reader, val) -- G_LIKELY(_gst_byte_reader_peek_int16_le_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_peek_uint16_be (reader, val) -- G_LIKELY(_gst_byte_reader_peek_uint16_be_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_peek_int16_be (reader, val) -- G_LIKELY(_gst_byte_reader_peek_int16_be_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_peek_uint24_le (reader, val) -- G_LIKELY(_gst_byte_reader_peek_uint24_le_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_peek_int24_le (reader, val) -- G_LIKELY(_gst_byte_reader_peek_int24_le_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_peek_uint24_be (reader, val) -- G_LIKELY(_gst_byte_reader_peek_uint24_be_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_peek_int24_be (reader, val) -- G_LIKELY(_gst_byte_reader_peek_int24_be_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_peek_uint32_le (reader, val) -- G_LIKELY(_gst_byte_reader_peek_uint32_le_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_peek_int32_le (reader, val) -- G_LIKELY(_gst_byte_reader_peek_int32_le_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_peek_uint32_be (reader, val) -- G_LIKELY(_gst_byte_reader_peek_uint32_be_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_peek_int32_be (reader, val) -- G_LIKELY(_gst_byte_reader_peek_int32_be_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_peek_uint64_le (reader, val) -- G_LIKELY(_gst_byte_reader_peek_uint64_le_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_peek_int64_le (reader, val) -- G_LIKELY(_gst_byte_reader_peek_int64_le_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_peek_uint64_be (reader, val) -- G_LIKELY(_gst_byte_reader_peek_uint64_be_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_peek_int64_be (reader, val) -- G_LIKELY(_gst_byte_reader_peek_int64_be_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_get_float32_le (reader, val) -- G_LIKELY(_gst_byte_reader_get_float32_le_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_get_float32_be (reader, val) -- G_LIKELY(_gst_byte_reader_get_float32_be_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_get_float64_le (reader, val) -- G_LIKELY(_gst_byte_reader_get_float64_le_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_get_float64_be (reader, val) -- G_LIKELY(_gst_byte_reader_get_float64_be_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_peek_float32_le (reader, val) -- G_LIKELY(_gst_byte_reader_peek_float32_le_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_peek_float32_be (reader, val) -- G_LIKELY(_gst_byte_reader_peek_float32_be_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_peek_float64_le (reader, val) -- G_LIKELY(_gst_byte_reader_peek_float64_le_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_peek_float64_be (reader, val) -- G_LIKELY(_gst_byte_reader_peek_float64_be_inline(reader,val)) -- arg-macro: procedure gst_byte_reader_dup_data (reader, size, val) -- G_LIKELY(_gst_byte_reader_dup_data_inline(reader,size,val)) -- arg-macro: procedure gst_byte_reader_get_data (reader, size, val) -- G_LIKELY(_gst_byte_reader_get_data_inline(reader,size,val)) -- arg-macro: procedure gst_byte_reader_peek_data (reader, size, val) -- G_LIKELY(_gst_byte_reader_peek_data_inline(reader,size,val)) -- arg-macro: procedure gst_byte_reader_skip (reader, nbytes) -- G_LIKELY(_gst_byte_reader_skip_inline(reader,nbytes)) -- GStreamer byte reader -- * -- * Copyright (C) 2008 Sebastian Dröge . -- * Copyright (C) 2009 Tim-Philipp Müller -- * -- * This library is free software; you can redistribute it and/or -- * modify it under the terms of the GNU Library General Public -- * License as published by the Free Software Foundation; either -- * version 2 of the License, or (at your option) any later version. -- * -- * This library is distributed in the hope that it will be useful, -- * but WITHOUT ANY WARRANTY; without even the implied warranty of -- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- * Library General Public License for more details. -- * -- * You should have received a copy of the GNU Library General Public -- * License along with this library; if not, write to the -- * Free Software Foundation, Inc., 59 Temple Place - Suite 330, -- * Boston, MA 02111-1307, USA. -- --* -- * GstByteReader: -- * @data: Data from which the bit reader will read -- * @size: Size of @data in bytes -- * @byte: Current byte position -- * -- * A byte reader instance. -- type GstByteReader is record data : access GLIB.guint8; -- gst/base/gstbytereader.h:40 size : aliased GLIB.guint; -- gst/base/gstbytereader.h:41 byte : aliased GLIB.guint; -- gst/base/gstbytereader.h:43 end record; pragma Convention (C_Pass_By_Copy, GstByteReader); -- gst/base/gstbytereader.h:44 -- skipped anonymous struct anon_309 -- Byte position function gst_byte_reader_new (data : access GLIB.guint8; size : GLIB.guint) return access GstByteReader; -- gst/base/gstbytereader.h:46 pragma Import (C, gst_byte_reader_new, ""gst_byte_reader_new""); function gst_byte_reader_new_from_buffer (buffer : access constant GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstbuffer_h.GstBuffer) return access GstByteReader; -- gst/base/gstbytereader.h:47 pragma Import (C, gst_byte_reader_new_from_buffer, ""gst_byte_reader_new_from_buffer""); procedure gst_byte_reader_free (reader : access GstByteReader); -- gst/base/gstbytereader.h:48 pragma Import (C, gst_byte_reader_free, ""gst_byte_reader_free""); procedure gst_byte_reader_init (reader : access GstByteReader; data : access GLIB.guint8; size : GLIB.guint); -- gst/base/gstbytereader.h:50 pragma Import (C, gst_byte_reader_init, ""gst_byte_reader_init""); procedure gst_byte_reader_init_from_buffer (reader : access GstByteReader; buffer : access constant GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstbuffer_h.GstBuffer); -- gst/base/gstbytereader.h:51 pragma Import (C, gst_byte_reader_init_from_buffer, ""gst_byte_reader_init_from_buffer""); function gst_byte_reader_set_pos (reader : access GstByteReader; pos : GLIB.guint) return GLIB.gboolean; -- gst/base/gstbytereader.h:53 pragma Import (C, gst_byte_reader_set_pos, ""gst_byte_reader_set_pos""); function gst_byte_reader_get_pos (reader : access constant GstByteReader) return GLIB.guint; -- gst/base/gstbytereader.h:55 pragma Import (C, gst_byte_reader_get_pos, ""gst_byte_reader_get_pos""); function gst_byte_reader_get_remaining (reader : access constant GstByteReader) return GLIB.guint; -- gst/base/gstbytereader.h:56 pragma Import (C, gst_byte_reader_get_remaining, ""gst_byte_reader_get_remaining""); function gst_byte_reader_get_size (reader : access constant GstByteReader) return GLIB.guint; -- gst/base/gstbytereader.h:58 pragma Import (C, gst_byte_reader_get_size, ""gst_byte_reader_get_size""); function gst_byte_reader_skip (reader : access GstByteReader; nbytes : GLIB.guint) return GLIB.gboolean; -- gst/base/gstbytereader.h:60 pragma Import (C, gst_byte_reader_skip, ""gst_byte_reader_skip""); function gst_byte_reader_get_uint8 (reader : access GstByteReader; val : access GLIB.guint8) return GLIB.gboolean; -- gst/base/gstbytereader.h:62 pragma Import (C, gst_byte_reader_get_uint8, ""gst_byte_reader_get_uint8""); function gst_byte_reader_get_int8 (reader : access GstByteReader; val : access GLIB.gint8) return GLIB.gboolean; -- gst/base/gstbytereader.h:63 pragma Import (C, gst_byte_reader_get_int8, ""gst_byte_reader_get_int8""); function gst_byte_reader_get_uint16_le (reader : access GstByteReader; val : access GLIB.guint16) return GLIB.gboolean; -- gst/base/gstbytereader.h:64 pragma Import (C, gst_byte_reader_get_uint16_le, ""gst_byte_reader_get_uint16_le""); function gst_byte_reader_get_int16_le (reader : access GstByteReader; val : access GLIB.gint16) return GLIB.gboolean; -- gst/base/gstbytereader.h:65 pragma Import (C, gst_byte_reader_get_int16_le, ""gst_byte_reader_get_int16_le""); function gst_byte_reader_get_uint16_be (reader : access GstByteReader; val : access GLIB.guint16) return GLIB.gboolean; -- gst/base/gstbytereader.h:66 pragma Import (C, gst_byte_reader_get_uint16_be, ""gst_byte_reader_get_uint16_be""); function gst_byte_reader_get_int16_be (reader : access GstByteReader; val : access GLIB.gint16) return GLIB.gboolean; -- gst/base/gstbytereader.h:67 pragma Import (C, gst_byte_reader_get_int16_be, ""gst_byte_reader_get_int16_be""); function gst_byte_reader_get_uint24_le (reader : access GstByteReader; val : access GLIB.guint32) return GLIB.gboolean; -- gst/base/gstbytereader.h:68 pragma Import (C, gst_byte_reader_get_uint24_le, ""gst_byte_reader_get_uint24_le""); function gst_byte_reader_get_int24_le (reader : access GstByteReader; val : access GLIB.gint32) return GLIB.gboolean; -- gst/base/gstbytereader.h:69 pragma Import (C, gst_byte_reader_get_int24_le, ""gst_byte_reader_get_int24_le""); function gst_byte_reader_get_uint24_be (reader : access GstByteReader; val : access GLIB.guint32) return GLIB.gboolean; -- gst/base/gstbytereader.h:70 pragma Import (C, gst_byte_reader_get_uint24_be, ""gst_byte_reader_get_uint24_be""); function gst_byte_reader_get_int24_be (reader : access GstByteReader; val : access GLIB.gint32) return GLIB.gboolean; -- gst/base/gstbytereader.h:71 pragma Import (C, gst_byte_reader_get_int24_be, ""gst_byte_reader_get_int24_be""); function gst_byte_reader_get_uint32_le (reader : access GstByteReader; val : access GLIB.guint32) return GLIB.gboolean; -- gst/base/gstbytereader.h:72 pragma Import (C, gst_byte_reader_get_uint32_le, ""gst_byte_reader_get_uint32_le""); function gst_byte_reader_get_int32_le (reader : access GstByteReader; val : access GLIB.gint32) return GLIB.gboolean; -- gst/base/gstbytereader.h:73 pragma Import (C, gst_byte_reader_get_int32_le, ""gst_byte_reader_get_int32_le""); function gst_byte_reader_get_uint32_be (reader : access GstByteReader; val : access GLIB.guint32) return GLIB.gboolean; -- gst/base/gstbytereader.h:74 pragma Import (C, gst_byte_reader_get_uint32_be, ""gst_byte_reader_get_uint32_be""); function gst_byte_reader_get_int32_be (reader : access GstByteReader; val : access GLIB.gint32) return GLIB.gboolean; -- gst/base/gstbytereader.h:75 pragma Import (C, gst_byte_reader_get_int32_be, ""gst_byte_reader_get_int32_be""); function gst_byte_reader_get_uint64_le (reader : access GstByteReader; val : access GLIB.guint64) return GLIB.gboolean; -- gst/base/gstbytereader.h:76 pragma Import (C, gst_byte_reader_get_uint64_le, ""gst_byte_reader_get_uint64_le""); function gst_byte_reader_get_int64_le (reader : access GstByteReader; val : access GLIB.gint64) return GLIB.gboolean; -- gst/base/gstbytereader.h:77 pragma Import (C, gst_byte_reader_get_int64_le, ""gst_byte_reader_get_int64_le""); function gst_byte_reader_get_uint64_be (reader : access GstByteReader; val : access GLIB.guint64) return GLIB.gboolean; -- gst/base/gstbytereader.h:78 pragma Import (C, gst_byte_reader_get_uint64_be, ""gst_byte_reader_get_uint64_be""); function gst_byte_reader_get_int64_be (reader : access GstByteReader; val : access GLIB.gint64) return GLIB.gboolean; -- gst/base/gstbytereader.h:79 pragma Import (C, gst_byte_reader_get_int64_be, ""gst_byte_reader_get_int64_be""); function gst_byte_reader_peek_uint8 (reader : access constant GstByteReader; val : access GLIB.guint8) return GLIB.gboolean; -- gst/base/gstbytereader.h:81 pragma Import (C, gst_byte_reader_peek_uint8, ""gst_byte_reader_peek_uint8""); function gst_byte_reader_peek_int8 (reader : access constant GstByteReader; val : access GLIB.gint8) return GLIB.gboolean; -- gst/base/gstbytereader.h:82 pragma Import (C, gst_byte_reader_peek_int8, ""gst_byte_reader_peek_int8""); function gst_byte_reader_peek_uint16_le (reader : access constant GstByteReader; val : access GLIB.guint16) return GLIB.gboolean; -- gst/base/gstbytereader.h:83 pragma Import (C, gst_byte_reader_peek_uint16_le, ""gst_byte_reader_peek_uint16_le""); function gst_byte_reader_peek_int16_le (reader : access constant GstByteReader; val : access GLIB.gint16) return GLIB.gboolean; -- gst/base/gstbytereader.h:84 pragma Import (C, gst_byte_reader_peek_int16_le, ""gst_byte_reader_peek_int16_le""); function gst_byte_reader_peek_uint16_be (reader : access constant GstByteReader; val : access GLIB.guint16) return GLIB.gboolean; -- gst/base/gstbytereader.h:85 pragma Import (C, gst_byte_reader_peek_uint16_be, ""gst_byte_reader_peek_uint16_be""); function gst_byte_reader_peek_int16_be (reader : access constant GstByteReader; val : access GLIB.gint16) return GLIB.gboolean; -- gst/base/gstbytereader.h:86 pragma Import (C, gst_byte_reader_peek_int16_be, ""gst_byte_reader_peek_int16_be""); function gst_byte_reader_peek_uint24_le (reader : access constant GstByteReader; val : access GLIB.guint32) return GLIB.gboolean; -- gst/base/gstbytereader.h:87 pragma Import (C, gst_byte_reader_peek_uint24_le, ""gst_byte_reader_peek_uint24_le""); function gst_byte_reader_peek_int24_le (reader : access constant GstByteReader; val : access GLIB.gint32) return GLIB.gboolean; -- gst/base/gstbytereader.h:88 pragma Import (C, gst_byte_reader_peek_int24_le, ""gst_byte_reader_peek_int24_le""); function gst_byte_reader_peek_uint24_be (reader : access constant GstByteReader; val : access GLIB.guint32) return GLIB.gboolean; -- gst/base/gstbytereader.h:89 pragma Import (C, gst_byte_reader_peek_uint24_be, ""gst_byte_reader_peek_uint24_be""); function gst_byte_reader_peek_int24_be (reader : access constant GstByteReader; val : access GLIB.gint32) return GLIB.gboolean; -- gst/base/gstbytereader.h:90 pragma Import (C, gst_byte_reader_peek_int24_be, ""gst_byte_reader_peek_int24_be""); function gst_byte_reader_peek_uint32_le (reader : access constant GstByteReader; val : access GLIB.guint32) return GLIB.gboolean; -- gst/base/gstbytereader.h:91 pragma Import (C, gst_byte_reader_peek_uint32_le, ""gst_byte_reader_peek_uint32_le""); function gst_byte_reader_peek_int32_le (reader : access constant GstByteReader; val : access GLIB.gint32) return GLIB.gboolean; -- gst/base/gstbytereader.h:92 pragma Import (C, gst_byte_reader_peek_int32_le, ""gst_byte_reader_peek_int32_le""); function gst_byte_reader_peek_uint32_be (reader : access constant GstByteReader; val : access GLIB.guint32) return GLIB.gboolean; -- gst/base/gstbytereader.h:93 pragma Import (C, gst_byte_reader_peek_uint32_be, ""gst_byte_reader_peek_uint32_be""); function gst_byte_reader_peek_int32_be (reader : access constant GstByteReader; val : access GLIB.gint32) return GLIB.gboolean; -- gst/base/gstbytereader.h:94 pragma Import (C, gst_byte_reader_peek_int32_be, ""gst_byte_reader_peek_int32_be""); function gst_byte_reader_peek_uint64_le (reader : access constant GstByteReader; val : access GLIB.guint64) return GLIB.gboolean; -- gst/base/gstbytereader.h:95 pragma Import (C, gst_byte_reader_peek_uint64_le, ""gst_byte_reader_peek_uint64_le""); function gst_byte_reader_peek_int64_le (reader : access constant GstByteReader; val : access GLIB.gint64) return GLIB.gboolean; -- gst/base/gstbytereader.h:96 pragma Import (C, gst_byte_reader_peek_int64_le, ""gst_byte_reader_peek_int64_le""); function gst_byte_reader_peek_uint64_be (reader : access constant GstByteReader; val : access GLIB.guint64) return GLIB.gboolean; -- gst/base/gstbytereader.h:97 pragma Import (C, gst_byte_reader_peek_uint64_be, ""gst_byte_reader_peek_uint64_be""); function gst_byte_reader_peek_int64_be (reader : access constant GstByteReader; val : access GLIB.gint64) return GLIB.gboolean; -- gst/base/gstbytereader.h:98 pragma Import (C, gst_byte_reader_peek_int64_be, ""gst_byte_reader_peek_int64_be""); function gst_byte_reader_get_float32_le (reader : access GstByteReader; val : access GLIB.gfloat) return GLIB.gboolean; -- gst/base/gstbytereader.h:100 pragma Import (C, gst_byte_reader_get_float32_le, ""gst_byte_reader_get_float32_le""); function gst_byte_reader_get_float32_be (reader : access GstByteReader; val : access GLIB.gfloat) return GLIB.gboolean; -- gst/base/gstbytereader.h:101 pragma Import (C, gst_byte_reader_get_float32_be, ""gst_byte_reader_get_float32_be""); function gst_byte_reader_get_float64_le (reader : access GstByteReader; val : access GLIB.gdouble) return GLIB.gboolean; -- gst/base/gstbytereader.h:102 pragma Import (C, gst_byte_reader_get_float64_le, ""gst_byte_reader_get_float64_le""); function gst_byte_reader_get_float64_be (reader : access GstByteReader; val : access GLIB.gdouble) return GLIB.gboolean; -- gst/base/gstbytereader.h:103 pragma Import (C, gst_byte_reader_get_float64_be, ""gst_byte_reader_get_float64_be""); function gst_byte_reader_peek_float32_le (reader : access constant GstByteReader; val : access GLIB.gfloat) return GLIB.gboolean; -- gst/base/gstbytereader.h:105 pragma Import (C, gst_byte_reader_peek_float32_le, ""gst_byte_reader_peek_float32_le""); function gst_byte_reader_peek_float32_be (reader : access constant GstByteReader; val : access GLIB.gfloat) return GLIB.gboolean; -- gst/base/gstbytereader.h:106 pragma Import (C, gst_byte_reader_peek_float32_be, ""gst_byte_reader_peek_float32_be""); function gst_byte_reader_peek_float64_le (reader : access constant GstByteReader; val : access GLIB.gdouble) return GLIB.gboolean; -- gst/base/gstbytereader.h:107 pragma Import (C, gst_byte_reader_peek_float64_le, ""gst_byte_reader_peek_float64_le""); function gst_byte_reader_peek_float64_be (reader : access constant GstByteReader; val : access GLIB.gdouble) return GLIB.gboolean; -- gst/base/gstbytereader.h:108 pragma Import (C, gst_byte_reader_peek_float64_be, ""gst_byte_reader_peek_float64_be""); function gst_byte_reader_dup_data (reader : access GstByteReader; size : GLIB.guint; val : System.Address) return GLIB.gboolean; -- gst/base/gstbytereader.h:110 pragma Import (C, gst_byte_reader_dup_data, ""gst_byte_reader_dup_data""); function gst_byte_reader_get_data (reader : access GstByteReader; size : GLIB.guint; val : System.Address) return GLIB.gboolean; -- gst/base/gstbytereader.h:111 pragma Import (C, gst_byte_reader_get_data, ""gst_byte_reader_get_data""); function gst_byte_reader_peek_data (reader : access constant GstByteReader; size : GLIB.guint; val : System.Address) return GLIB.gboolean; -- gst/base/gstbytereader.h:112 pragma Import (C, gst_byte_reader_peek_data, ""gst_byte_reader_peek_data""); function gst_byte_reader_dup_string_utf8 (reader : access GstByteReader; str : System.Address) return GLIB.gboolean; -- gst/base/gstbytereader.h:117 pragma Import (C, gst_byte_reader_dup_string_utf8, ""gst_byte_reader_dup_string_utf8""); function gst_byte_reader_dup_string_utf16 (reader : access GstByteReader; str : System.Address) return GLIB.gboolean; -- gst/base/gstbytereader.h:118 pragma Import (C, gst_byte_reader_dup_string_utf16, ""gst_byte_reader_dup_string_utf16""); function gst_byte_reader_dup_string_utf32 (reader : access GstByteReader; str : System.Address) return GLIB.gboolean; -- gst/base/gstbytereader.h:119 pragma Import (C, gst_byte_reader_dup_string_utf32, ""gst_byte_reader_dup_string_utf32""); function gst_byte_reader_skip_string_utf8 (reader : access GstByteReader) return GLIB.gboolean; -- gst/base/gstbytereader.h:124 pragma Import (C, gst_byte_reader_skip_string_utf8, ""gst_byte_reader_skip_string_utf8""); function gst_byte_reader_skip_string_utf16 (reader : access GstByteReader) return GLIB.gboolean; -- gst/base/gstbytereader.h:125 pragma Import (C, gst_byte_reader_skip_string_utf16, ""gst_byte_reader_skip_string_utf16""); function gst_byte_reader_skip_string_utf32 (reader : access GstByteReader) return GLIB.gboolean; -- gst/base/gstbytereader.h:126 pragma Import (C, gst_byte_reader_skip_string_utf32, ""gst_byte_reader_skip_string_utf32""); function gst_byte_reader_get_string_utf8 (reader : access GstByteReader; str : System.Address) return GLIB.gboolean; -- gst/base/gstbytereader.h:134 pragma Import (C, gst_byte_reader_get_string_utf8, ""gst_byte_reader_get_string_utf8""); function gst_byte_reader_peek_string_utf8 (reader : access constant GstByteReader; str : System.Address) return GLIB.gboolean; -- gst/base/gstbytereader.h:135 pragma Import (C, gst_byte_reader_peek_string_utf8, ""gst_byte_reader_peek_string_utf8""); function gst_byte_reader_masked_scan_uint32 (reader : access constant GstByteReader; mask : GLIB.guint32; pattern : GLIB.guint32; offset : GLIB.guint; size : GLIB.guint) return GLIB.guint; -- gst/base/gstbytereader.h:137 pragma Import (C, gst_byte_reader_masked_scan_uint32, ""gst_byte_reader_masked_scan_uint32""); --* -- * GST_BYTE_READER_INIT: -- * @data: Data from which the #GstByteReader should read -- * @size: Size of @data in bytes -- * -- * A #GstByteReader must be initialized with this macro, before it can be -- * used. This macro can used be to initialize a variable, but it cannot -- * be assigned to a variable. In that case you have to use -- * gst_byte_reader_init(). -- * -- * Since: 0.10.22 -- --* -- * GST_BYTE_READER_INIT_FROM_BUFFER: -- * @buffer: Buffer from which the #GstByteReader should read -- * -- * A #GstByteReader must be initialized with this macro, before it can be -- * used. This macro can used be to initialize a variable, but it cannot -- * be assigned to a variable. In that case you have to use -- * gst_byte_reader_init(). -- * -- * Since: 0.10.22 -- -- unchecked variants procedure gst_byte_reader_skip_unchecked (reader : access GstByteReader; nbytes : GLIB.guint); -- gst/base/gstbytereader.h:173 pragma Import (C, gst_byte_reader_skip_unchecked, ""gst_byte_reader_skip_unchecked""); -- function gst_byte_reader_get_uint8_unchecked (reader : access GstByteReader) return GLIB.guint8; -- gst/base/gstbytereader.h:196 pragma Import (C, gst_byte_reader_get_uint8_unchecked, ""gst_byte_reader_get_uint8_unchecked""); function gst_byte_reader_peek_uint8_unchecked (reader : access constant GstByteReader) return GLIB.guint8; -- gst/base/gstbytereader.h:196 pragma Import (C, gst_byte_reader_peek_uint8_unchecked, ""gst_byte_reader_peek_uint8_unchecked""); -- function gst_byte_reader_get_int8_unchecked (reader : access GstByteReader) return GLIB.gint8; -- gst/base/gstbytereader.h:197 pragma Import (C, gst_byte_reader_get_int8_unchecked, ""gst_byte_reader_get_int8_unchecked""); function gst_byte_reader_peek_int8_unchecked (reader : access constant GstByteReader) return GLIB.gint8; -- gst/base/gstbytereader.h:197 pragma Import (C, gst_byte_reader_peek_int8_unchecked, ""gst_byte_reader_peek_int8_unchecked""); -- function gst_byte_reader_get_uint16_le_unchecked (reader : access GstByteReader) return GLIB.guint16; -- gst/base/gstbytereader.h:199 pragma Import (C, gst_byte_reader_get_uint16_le_unchecked, ""gst_byte_reader_get_uint16_le_unchecked""); function gst_byte_reader_peek_uint16_le_unchecked (reader : access constant GstByteReader) return GLIB.guint16; -- gst/base/gstbytereader.h:199 pragma Import (C, gst_byte_reader_peek_uint16_le_unchecked, ""gst_byte_reader_peek_uint16_le_unchecked""); -- function gst_byte_reader_get_uint16_be_unchecked (reader : access GstByteReader) return GLIB.guint16; -- gst/base/gstbytereader.h:200 pragma Import (C, gst_byte_reader_get_uint16_be_unchecked, ""gst_byte_reader_get_uint16_be_unchecked""); function gst_byte_reader_peek_uint16_be_unchecked (reader : access constant GstByteReader) return GLIB.guint16; -- gst/base/gstbytereader.h:200 pragma Import (C, gst_byte_reader_peek_uint16_be_unchecked, ""gst_byte_reader_peek_uint16_be_unchecked""); -- function gst_byte_reader_get_int16_le_unchecked (reader : access GstByteReader) return GLIB.gint16; -- gst/base/gstbytereader.h:201 pragma Import (C, gst_byte_reader_get_int16_le_unchecked, ""gst_byte_reader_get_int16_le_unchecked""); function gst_byte_reader_peek_int16_le_unchecked (reader : access constant GstByteReader) return GLIB.gint16; -- gst/base/gstbytereader.h:201 pragma Import (C, gst_byte_reader_peek_int16_le_unchecked, ""gst_byte_reader_peek_int16_le_unchecked""); -- function gst_byte_reader_get_int16_be_unchecked (reader : access GstByteReader) return GLIB.gint16; -- gst/base/gstbytereader.h:202 pragma Import (C, gst_byte_reader_get_int16_be_unchecked, ""gst_byte_reader_get_int16_be_unchecked""); function gst_byte_reader_peek_int16_be_unchecked (reader : access constant GstByteReader) return GLIB.gint16; -- gst/base/gstbytereader.h:202 pragma Import (C, gst_byte_reader_peek_int16_be_unchecked, ""gst_byte_reader_peek_int16_be_unchecked""); -- function gst_byte_reader_get_uint32_le_unchecked (reader : access GstByteReader) return GLIB.guint32; -- gst/base/gstbytereader.h:204 pragma Import (C, gst_byte_reader_get_uint32_le_unchecked, ""gst_byte_reader_get_uint32_le_unchecked""); function gst_byte_reader_peek_uint32_le_unchecked (reader : access constant GstByteReader) return GLIB.guint32; -- gst/base/gstbytereader.h:204 pragma Import (C, gst_byte_reader_peek_uint32_le_unchecked, ""gst_byte_reader_peek_uint32_le_unchecked""); -- function gst_byte_reader_get_uint32_be_unchecked (reader : access GstByteReader) return GLIB.guint32; -- gst/base/gstbytereader.h:205 pragma Import (C, gst_byte_reader_get_uint32_be_unchecked, ""gst_byte_reader_get_uint32_be_unchecked""); function gst_byte_reader_peek_uint32_be_unchecked (reader : access constant GstByteReader) return GLIB.guint32; -- gst/base/gstbytereader.h:205 pragma Import (C, gst_byte_reader_peek_uint32_be_unchecked, ""gst_byte_reader_peek_uint32_be_unchecked""); -- function gst_byte_reader_get_int32_le_unchecked (reader : access GstByteReader) return GLIB.gint32; -- gst/base/gstbytereader.h:206 pragma Import (C, gst_byte_reader_get_int32_le_unchecked, ""gst_byte_reader_get_int32_le_unchecked""); function gst_byte_reader_peek_int32_le_unchecked (reader : access constant GstByteReader) return GLIB.gint32; -- gst/base/gstbytereader.h:206 pragma Import (C, gst_byte_reader_peek_int32_le_unchecked, ""gst_byte_reader_peek_int32_le_unchecked""); -- function gst_byte_reader_get_int32_be_unchecked (reader : access GstByteReader) return GLIB.gint32; -- gst/base/gstbytereader.h:207 pragma Import (C, gst_byte_reader_get_int32_be_unchecked, ""gst_byte_reader_get_int32_be_unchecked""); function gst_byte_reader_peek_int32_be_unchecked (reader : access constant GstByteReader) return GLIB.gint32; -- gst/base/gstbytereader.h:207 pragma Import (C, gst_byte_reader_peek_int32_be_unchecked, ""gst_byte_reader_peek_int32_be_unchecked""); -- function gst_byte_reader_get_uint24_le_unchecked (reader : access GstByteReader) return GLIB.guint32; -- gst/base/gstbytereader.h:209 pragma Import (C, gst_byte_reader_get_uint24_le_unchecked, ""gst_byte_reader_get_uint24_le_unchecked""); function gst_byte_reader_peek_uint24_le_unchecked (reader : access constant GstByteReader) return GLIB.guint32; -- gst/base/gstbytereader.h:209 pragma Import (C, gst_byte_reader_peek_uint24_le_unchecked, ""gst_byte_reader_peek_uint24_le_unchecked""); -- function gst_byte_reader_get_uint24_be_unchecked (reader : access GstByteReader) return GLIB.guint32; -- gst/base/gstbytereader.h:210 pragma Import (C, gst_byte_reader_get_uint24_be_unchecked, ""gst_byte_reader_get_uint24_be_unchecked""); function gst_byte_reader_peek_uint24_be_unchecked (reader : access constant GstByteReader) return GLIB.guint32; -- gst/base/gstbytereader.h:210 pragma Import (C, gst_byte_reader_peek_uint24_be_unchecked, ""gst_byte_reader_peek_uint24_be_unchecked""); -- fix up the sign for 24-bit signed ints stored in 32-bit signed ints function gst_byte_reader_get_int24_le_unchecked (reader : access GstByteReader) return GLIB.gint32; -- gst/base/gstbytereader.h:213 pragma Import (C, gst_byte_reader_get_int24_le_unchecked, ""gst_byte_reader_get_int24_le_unchecked""); function gst_byte_reader_peek_int24_le_unchecked (reader : access constant GstByteReader) return GLIB.gint32; -- gst/base/gstbytereader.h:213 pragma Import (C, gst_byte_reader_peek_int24_le_unchecked, ""gst_byte_reader_peek_int24_le_unchecked""); function gst_byte_reader_get_int24_be_unchecked (reader : access GstByteReader) return GLIB.gint32; -- gst/base/gstbytereader.h:215 pragma Import (C, gst_byte_reader_get_int24_be_unchecked, ""gst_byte_reader_get_int24_be_unchecked""); function gst_byte_reader_peek_int24_be_unchecked (reader : access constant GstByteReader) return GLIB.gint32; -- gst/base/gstbytereader.h:215 pragma Import (C, gst_byte_reader_peek_int24_be_unchecked, ""gst_byte_reader_peek_int24_be_unchecked""); -- function gst_byte_reader_get_uint64_le_unchecked (reader : access GstByteReader) return GLIB.guint64; -- gst/base/gstbytereader.h:218 pragma Import (C, gst_byte_reader_get_uint64_le_unchecked, ""gst_byte_reader_get_uint64_le_unchecked""); function gst_byte_reader_peek_uint64_le_unchecked (reader : access constant GstByteReader) return GLIB.guint64; -- gst/base/gstbytereader.h:218 pragma Import (C, gst_byte_reader_peek_uint64_le_unchecked, ""gst_byte_reader_peek_uint64_le_unchecked""); -- function gst_byte_reader_get_uint64_be_unchecked (reader : access GstByteReader) return GLIB.guint64; -- gst/base/gstbytereader.h:219 pragma Import (C, gst_byte_reader_get_uint64_be_unchecked, ""gst_byte_reader_get_uint64_be_unchecked""); function gst_byte_reader_peek_uint64_be_unchecked (reader : access constant GstByteReader) return GLIB.guint64; -- gst/base/gstbytereader.h:219 pragma Import (C, gst_byte_reader_peek_uint64_be_unchecked, ""gst_byte_reader_peek_uint64_be_unchecked""); -- function gst_byte_reader_get_int64_le_unchecked (reader : access GstByteReader) return GLIB.gint64; -- gst/base/gstbytereader.h:220 pragma Import (C, gst_byte_reader_get_int64_le_unchecked, ""gst_byte_reader_get_int64_le_unchecked""); function gst_byte_reader_peek_int64_le_unchecked (reader : access constant GstByteReader) return GLIB.gint64; -- gst/base/gstbytereader.h:220 pragma Import (C, gst_byte_reader_peek_int64_le_unchecked, ""gst_byte_reader_peek_int64_le_unchecked""); -- function gst_byte_reader_get_int64_be_unchecked (reader : access GstByteReader) return GLIB.gint64; -- gst/base/gstbytereader.h:221 pragma Import (C, gst_byte_reader_get_int64_be_unchecked, ""gst_byte_reader_get_int64_be_unchecked""); function gst_byte_reader_peek_int64_be_unchecked (reader : access constant GstByteReader) return GLIB.gint64; -- gst/base/gstbytereader.h:221 pragma Import (C, gst_byte_reader_peek_int64_be_unchecked, ""gst_byte_reader_peek_int64_be_unchecked""); -- function gst_byte_reader_get_float32_le_unchecked (reader : access GstByteReader) return GLIB.gfloat; -- gst/base/gstbytereader.h:223 pragma Import (C, gst_byte_reader_get_float32_le_unchecked, ""gst_byte_reader_get_float32_le_unchecked""); function gst_byte_reader_peek_float32_le_unchecked (reader : access constant GstByteReader) return GLIB.gfloat; -- gst/base/gstbytereader.h:223 pragma Import (C, gst_byte_reader_peek_float32_le_unchecked, ""gst_byte_reader_peek_float32_le_unchecked""); -- function gst_byte_reader_get_float32_be_unchecked (reader : access GstByteReader) return GLIB.gfloat; -- gst/base/gstbytereader.h:224 pragma Import (C, gst_byte_reader_get_float32_be_unchecked, ""gst_byte_reader_get_float32_be_unchecked""); function gst_byte_reader_peek_float32_be_unchecked (reader : access constant GstByteReader) return GLIB.gfloat; -- gst/base/gstbytereader.h:224 pragma Import (C, gst_byte_reader_peek_float32_be_unchecked, ""gst_byte_reader_peek_float32_be_unchecked""); -- function gst_byte_reader_get_float64_le_unchecked (reader : access GstByteReader) return GLIB.gdouble; -- gst/base/gstbytereader.h:225 pragma Import (C, gst_byte_reader_get_float64_le_unchecked, ""gst_byte_reader_get_float64_le_unchecked""); function gst_byte_reader_peek_float64_le_unchecked (reader : access constant GstByteReader) return GLIB.gdouble; -- gst/base/gstbytereader.h:225 pragma Import (C, gst_byte_reader_peek_float64_le_unchecked, ""gst_byte_reader_peek_float64_le_unchecked""); -- function gst_byte_reader_get_float64_be_unchecked (reader : access GstByteReader) return GLIB.gdouble; -- gst/base/gstbytereader.h:226 pragma Import (C, gst_byte_reader_get_float64_be_unchecked, ""gst_byte_reader_get_float64_be_unchecked""); function gst_byte_reader_peek_float64_be_unchecked (reader : access constant GstByteReader) return GLIB.gdouble; -- gst/base/gstbytereader.h:226 pragma Import (C, gst_byte_reader_peek_float64_be_unchecked, ""gst_byte_reader_peek_float64_be_unchecked""); function gst_byte_reader_peek_data_unchecked (reader : access constant GstByteReader) return access GLIB.guint8; -- gst/base/gstbytereader.h:231 pragma Import (C, gst_byte_reader_peek_data_unchecked, ""gst_byte_reader_peek_data_unchecked""); function gst_byte_reader_get_data_unchecked (reader : access GstByteReader; size : GLIB.guint) return access GLIB.guint8; -- gst/base/gstbytereader.h:237 pragma Import (C, gst_byte_reader_get_data_unchecked, ""gst_byte_reader_get_data_unchecked""); function gst_byte_reader_dup_data_unchecked (reader : access GstByteReader; size : GLIB.guint) return access GLIB.guint8; -- gst/base/gstbytereader.h:247 pragma Import (C, gst_byte_reader_dup_data_unchecked, ""gst_byte_reader_dup_data_unchecked""); -- Unchecked variants that should not be used -- skipped func _gst_byte_reader_get_pos_unchecked -- skipped func _gst_byte_reader_get_remaining_unchecked -- skipped func _gst_byte_reader_get_size_unchecked -- inlined variants (do not use directly) -- skipped func _gst_byte_reader_get_remaining_inline -- skipped func _gst_byte_reader_get_size_inline -- skipped func _gst_byte_reader_get_uint8_inline -- skipped func _gst_byte_reader_peek_uint8_inline -- skipped func _gst_byte_reader_get_int8_inline -- skipped func _gst_byte_reader_peek_int8_inline -- skipped func _gst_byte_reader_get_uint16_le_inline -- skipped func _gst_byte_reader_peek_uint16_le_inline -- skipped func _gst_byte_reader_get_uint16_be_inline -- skipped func _gst_byte_reader_peek_uint16_be_inline -- skipped func _gst_byte_reader_get_int16_le_inline -- skipped func _gst_byte_reader_peek_int16_le_inline -- skipped func _gst_byte_reader_get_int16_be_inline -- skipped func _gst_byte_reader_peek_int16_be_inline -- skipped func _gst_byte_reader_get_uint32_le_inline -- skipped func _gst_byte_reader_peek_uint32_le_inline -- skipped func _gst_byte_reader_get_uint32_be_inline -- skipped func _gst_byte_reader_peek_uint32_be_inline -- skipped func _gst_byte_reader_get_int32_le_inline -- skipped func _gst_byte_reader_peek_int32_le_inline -- skipped func _gst_byte_reader_get_int32_be_inline -- skipped func _gst_byte_reader_peek_int32_be_inline -- skipped func _gst_byte_reader_get_uint24_le_inline -- skipped func _gst_byte_reader_peek_uint24_le_inline -- skipped func _gst_byte_reader_get_uint24_be_inline -- skipped func _gst_byte_reader_peek_uint24_be_inline -- skipped func _gst_byte_reader_get_int24_le_inline -- skipped func _gst_byte_reader_peek_int24_le_inline -- skipped func _gst_byte_reader_get_int24_be_inline -- skipped func _gst_byte_reader_peek_int24_be_inline -- skipped func _gst_byte_reader_get_uint64_le_inline -- skipped func _gst_byte_reader_peek_uint64_le_inline -- skipped func _gst_byte_reader_get_uint64_be_inline -- skipped func _gst_byte_reader_peek_uint64_be_inline -- skipped func _gst_byte_reader_get_int64_le_inline -- skipped func _gst_byte_reader_peek_int64_le_inline -- skipped func _gst_byte_reader_get_int64_be_inline -- skipped func _gst_byte_reader_peek_int64_be_inline -- skipped func _gst_byte_reader_get_float32_le_inline -- skipped func _gst_byte_reader_peek_float32_le_inline -- skipped func _gst_byte_reader_get_float32_be_inline -- skipped func _gst_byte_reader_peek_float32_be_inline -- skipped func _gst_byte_reader_get_float64_le_inline -- skipped func _gst_byte_reader_peek_float64_le_inline -- skipped func _gst_byte_reader_get_float64_be_inline -- skipped func _gst_byte_reader_peek_float64_be_inline -- we use defines here so we can add the G_LIKELY() -- skipped func _gst_byte_reader_dup_data_inline -- skipped func _gst_byte_reader_get_data_inline -- skipped func _gst_byte_reader_peek_data_inline -- skipped func _gst_byte_reader_get_pos_inline -- skipped func _gst_byte_reader_skip_inline end GStreamer.GST_Low_Level.gstreamer_0_10_gst_base_gstbytereader_h; ",12320,True,3142.347552217713,median "[[plannerConfiguration]] = Planner Configuration :doctype: book :sectnums: :toc: left :icons: font :experimental: :sourcedir: . [[plannerConfigurationOverview]] == Overview Solving a planning problem with Planner consists of the following steps: . *Model your planning problem* as a class that implements the interface ``Solution``, for example the class ``NQueens``. . **Configure a ``**Solver**``**, for example a First Fit and Tabu Search solver for any `NQueens` instance. . *Load a problem data set* from your data layer, for example a 4 Queens instance. That is the planning problem. . *Solve it* with `Solver.solve(planningProblem)` which returns the best solution found. image::Chapter-Planner_configuration/inputOutputOverview.png[align=""center""] [[solverConfiguration]] == Solver Configuration [[solverConfigurationByXML]] === Solver Configuration by XML Build a `Solver` instance with the ``SolverFactory``. Configure the `SolverFactory` with a solver configuration XML file, provided as a classpath resource (as definied by ``ClassLoader.getResource()``): [source,java,options=""nowrap""] ---- SolverFactory solverFactory = SolverFactory.createFromXmlResource( ""org/optaplanner/examples/nqueens/solver/nqueensSolverConfig.xml""); Solver solver = solverFactory.buildSolver(); ---- In a typical project (following the Maven directory structure), that solverConfig XML file would be located at ``$PROJECT_DIR/src/main/resources/org/optaplanner/examples/nqueens/solver/nqueensSolverConfig.xml``. Alternatively, a `SolverFactory` can be created from a ``File``, an `InputStream` or a `Reader` with methods such as ``SolverFactory.createFromXmlFile()``. However, for portability reasons, a classpath resource is recommended. [NOTE] ==== On some environments (<>, <>, ...), classpath resources (such as the solver config, score DRL's and domain classes) in your jars might not be available to the default `ClassLoader` of the `optaplanner-core` jar. In those cases, provide the `ClassLoader` of your classes as a parameter: [source,java,options=""nowrap""] ---- SolverFactory solverFactory = SolverFactory.createFromXmlResource( "".../nqueensSolverConfig.xml"", getClass().getClassLoader()); ---- ==== [NOTE] ==== When using Workbench or Execution Server or to take advantage of Drools's `KieContainer` features, provide the `KieContainer` as a parameter: [source,java,options=""nowrap""] ---- KieServices kieServices = KieServices.Factory.get(); KieContainer kieContainer = kieServices.newKieContainer( kieServices.newReleaseId(""org.nqueens"", ""nqueens"", ""1.0.0"")); SolverFactory solverFactory = SolverFactory.createFromKieContainerXmlResource( kieContainer, "".../nqueensSolverConfig.xml""); ---- Also use <>. ==== Both a `Solver` and a `SolverFactory` have a generic type called ``Solution_``, which is the class representing a <>. A solver configuration XML file looks like this: [source,xml,options=""nowrap""] ---- org.optaplanner.examples.nqueens.domain.NQueens org.optaplanner.examples.nqueens.domain.Queen org/optaplanner/examples/nqueens/solver/nQueensScoreRules.drl ... ... ... ---- Notice the three parts in it: * Define the model. * Define the score function. * Optionally configure the optimization algorithm(s). These various parts of a configuration are explained further in this manual. *Planner makes it relatively easy to switch optimization algorithm(s) just by changing the configuration.* There is even a <> which allows you to play out different configurations against each other and report the most appropriate configuration for your use case. [[solverConfigurationByJavaAPI]] === Solver Configuration by Java API A solver configuration can also be configured with the `SolverConfig` API. This is especially useful to change some values dynamically at runtime. For example, to change the running time based on user input, before building the ``Solver``: [source,java,options=""nowrap""] ---- SolverFactory solverFactory = SolverFactory.createFromXmlResource( ""org/optaplanner/examples/nqueens/solver/nqueensSolverConfig.xml""); TerminationConfig terminationConfig = new TerminationConfig(); terminationConfig.setMinutesSpentLimit(userInput); solverFactory.getSolverConfig().setTerminationConfig(terminationConfig); Solver solver = solverFactory.buildSolver(); ---- Every element in the solver configuration XML is available as a `$$*$$Config` class or a property on a `$$*$$Config` class in the package namespace ``org.optaplanner.core.config``. These `$$*$$Config` classes are the Java representation of the XML format. They build the runtime components (of the package namespace ``org.optaplanner.core.impl``) and assemble them into an efficient ``Solver``. [IMPORTANT] ==== The `SolverFactory` is only multi-thread safe after its configured. So the `getSolverConfig()` method is not thread-safe. To configure a `SolverFactory` dynamically for each user request, build a `SolverFactory` as base during initialization and clone it with the `cloneSolverFactory()` method for a user request: [source,java,options=""nowrap""] ---- private SolverFactory base; public void init() { base = SolverFactory.createFromXmlResource( ""org/optaplanner/examples/nqueens/solver/nqueensSolverConfig.xml""); base.getSolverConfig().setTerminationConfig(new TerminationConfig()); } // Called concurrently from different threads public void userRequest(..., long userInput) SolverFactory solverFactory = base.cloneSolverFactory(); solverFactory.getSolverConfig().getTerminationConfig().setMinutesSpentLimit(userInput); Solver solver = solverFactory.buildSolver(); ... } ---- ==== [[annotationsConfiguration]] === Annotations Configuration [[automaticScanningForAnnotations]] ==== Automatic Scanning for Annotations Instead of the declaring the classes that have a `@PlanningSolution` or `@PlanningEntity` manually: [source,xml,options=""nowrap""] ---- org.optaplanner.examples.nqueens.domain.NQueens org.optaplanner.examples.nqueens.domain.Queen ... ---- Planner can find scan the classpath and find them automatically: [source,xml,options=""nowrap""] ---- ... ---- This comes at a bootstrap performance cost. If there are multiple models in your classpath or to speed up scanning, specify the packages to scan: [source,xml,options=""nowrap""] ---- org.optaplanner.examples.cloudbalancing ... ---- This finds all solution and entity classes in that package or its subpackages. [NOTE] ==== If `scanAnnotatedClasses` is not specified, the `org.reflections` transitive maven dependency can be excluded. ==== [[annotationAlternatives]] ==== Annotation Alternatives Planner needs to be told which classes in your domain model are planning entities, which properties are planning variables, etc. There are several ways to deliver this information: * Add class annotations and JavaBean property annotations on the domain model (recommended). The property annotations must be on the getter method, not on the setter method. Such a getter does not need to be public. * Add class annotations and field annotations on the domain model. Such a field does not need to be public. * No annotations: externalize the domain configuration in an XML file. This is https://issues.jboss.org/browse/PLANNER-151[not yet supported]. This manual focuses on the first manner, but every features supports all 3 manners, even if it's not explicitly mentioned. [[modelAPlanningProblem]] == Model a Planning Problem [[isThisClassAProblemFactOrPlanningEntity]] === Is This Class a Problem Fact or Planning Entity? Look at a dataset of your planning problem. You will recognize domain classes in there, each of which can be categorized as one of the following: * A unrelated class: not used by any of the score constraints. From a planning standpoint, this data is obsolete. * A *problem fact* class: used by the score constraints, but does NOT change during planning (as long as the problem stays the same). For example: ``Bed``, ``Room``, ``Shift``, ``Employee``, ``Topic``, ``Period``, ... All the properties of a problem fact class are problem properties. * A *planning entity* class: used by the score constraints and changes during planning. For example: ``BedDesignation``, ``ShiftAssignment``, ``Exam``, ... The properties that change during planning are planning variables. The other properties are problem properties. Ask yourself: _What class changes during planning?___Which class has variables that I want the ``__Solver__`` to change for me?__ That class is a planning entity. Most use cases have only one planning entity class. Most use cases also have only one planning variable per planning entity class. [NOTE] ==== In <>, even though the problem itself changes, problem facts do not really change during planning, instead they change between planning (because the Solver temporarily stops to apply the problem fact changes). ==== To create a good domain model, read the <>. *In Planner, all problems facts and planning entities are plain old JavaBeans (POJOs).* Load them from a database, an XML file, a data repository, a REST service, a noSQL cloud, ... (see <>): it doesn't matter. [[problemFact]] === Problem Fact A problem fact is any JavaBean (POJO) with getters that does not change during planning. Implementing the interface `Serializable` is recommended (but not required). For example in n queens, the columns and rows are problem facts: [source,java,options=""nowrap""] ---- public class Column implements Serializable { private int index; // ... getters } ---- [source,java,options=""nowrap""] ---- public class Row implements Serializable { private int index; // ... getters } ---- A problem fact can reference other problem facts of course: [source,java,options=""nowrap""] ---- public class Course implements Serializable { private String code; private Teacher teacher; // Other problem fact private int lectureSize; private int minWorkingDaySize; private List curriculumList; // Other problem facts private int studentSize; // ... getters } ---- A problem fact class does _not_ require any Planner specific code. For example, you can reuse your domain classes, which might have JPA annotations. [NOTE] ==== Generally, better designed domain classes lead to simpler and more efficient score constraints. Therefore, when dealing with a messy (denormalized) legacy system, it can sometimes be worthwhile to convert the messy domain model into a Planner specific model first. For example: if your domain model has two `Teacher` instances for the same teacher that teaches at two different departments, it is harder to write a correct score constraint that constrains a teacher's spare time on the original model than on an adjusted model. Alternatively, you can sometimes also introduce <> to enrich the domain model for planning only. ==== [[planningEntity]] === Planning Entity [[planningEntityAnnotation]] ==== Planning Entity Annotation A planning entity is a JavaBean (POJO) that changes during solving, for example a `Queen` that changes to another row. A planning problem has multiple planning entities, for example for a single n queens problem, each `Queen` is a planning entity. But there is usually only one planning entity class, for example the `Queen` class. A planning entity class needs to be annotated with the `@PlanningEntity` annotation. Each planning entity class has one or more _planning variables_ (which can be <> or <>). It should also have one or more _defining_ properties. For example in n queens, a `Queen` is defined by its `Column` and has a planning variable ``Row``. This means that a Queen's column never changes during solving, while its row does change. [source,java,options=""nowrap""] ---- @PlanningEntity public class Queen { private Column column; // Planning variables: changes during planning, between score calculations. private Row row; // ... getters and setters } ---- A planning entity class can have multiple planning variables. For example, a `Lecture` is defined by its `Course` and its index in that course (because one course has multiple lectures). Each `Lecture` needs to be scheduled into a `Period` and a `Room` so it has two planning variables (period and room). For example: the course Mathematics has eight lectures per week, of which the first lecture is Monday morning at 08:00 in room 212. [source,java,options=""nowrap""] ---- @PlanningEntity public class Lecture { private Course course; private int lectureIndexInCourse; // Planning variables: changes during planning, between score calculations. private Period period; private Room room; // ... } ---- Without <>, the solver configuration also needs to declare each planning entity class: [source,java,options=""nowrap""] ---- ... org.optaplanner.examples.nqueens.domain.Queen ... ---- Some uses cases have multiple planning entity classes. For example: route freight and trains into railway network arcs, where each freight can use multiple trains over its journey and each train can carry multiple freights per arc. Having multiple planning entity classes directly raises the implementation complexity of your use case. [NOTE] ==== _Do not create unnecessary planning entity classes._ This leads to difficult `Move` implementations and slower score calculation. For example, do not create a planning entity class to hold the total free time of a teacher, which needs to be kept up to date as the `Lecture` planning entities change. Instead, calculate the free time in the score constraints (or as a <>) and put the result per teacher into a logically inserted score object. If historic data needs to be considered too, then create problem fact to hold the total of the historic assignments up to, but __not including__, the planning window (so that it does not change when a planning entity changes) and let the score constraints take it into account. ==== [[planningEntityDifficulty]] ==== Planning Entity Difficulty Some optimization algorithms work more efficiently if they have an estimation of which planning entities are more difficult to plan. For example: in bin packing bigger items are harder to fit, in course scheduling lectures with more students are more difficult to schedule, and in n queens the middle queens are more difficult to fit on the board. [NOTE] ==== *Do not try to use planning entity difficulty to implement a business constraint.* It will not affect the score function: if we have infinite solving time, the returned solution will be the same. To attain a schedule in which certain entities are scheduled earlier in the schedule, <> to change the score function so it prefers such solutions. Only consider adding planning entity difficulty too if it can make the solver more efficient. ==== To allow the heuristics to take advantage of that domain specific information, set a `difficultyComparatorClass` to the `@PlanningEntity` annotation: [source,java,options=""nowrap""] ---- @PlanningEntity(difficultyComparatorClass = CloudProcessDifficultyComparator.class) public class CloudProcess { // ... } ---- [source,java,options=""nowrap""] ---- public class CloudProcessDifficultyComparator implements Comparator { public int compare(CloudProcess a, CloudProcess b) { return new CompareToBuilder() .append(a.getRequiredMultiplicand(), b.getRequiredMultiplicand()) .append(a.getId(), b.getId()) .toComparison(); } } ---- Alternatively, you can also set a `difficultyWeightFactoryClass` to the `@PlanningEntity` annotation, so that you have access to the rest of the problem facts from the `Solution` too: [source,java,options=""nowrap""] ---- @PlanningEntity(difficultyWeightFactoryClass = QueenDifficultyWeightFactory.class) public class Queen { // ... } ---- See <> for more information. [IMPORTANT] ==== Difficulty should be implemented ascending: easy entities are lower, difficult entities are higher. For example, in bin packing: small item < medium item < big item. Although most algorithms start with the more difficult entities first, they just reverse the ordering. ==== _None of the current planning variable states should be used to compare planning entity difficulty._ During Construction Heuristics, those variables are likely to be `null` anyway. For example, a ``Queen``'s `row` variable should not be used. [[planningVariable]] === Planning Variable (genuine) [[planningVariableAnnotation]] ==== Planning Variable Annotation A planning variable is a JavaBean property (so a getter and setter) on a planning entity. It points to a planning value, which changes during planning. For example, a ``Queen``'s `row` property is a genuine planning variable. Note that even though a ``Queen``'s `row` property changes to another `Row` during planning, no `Row` instance itself is changed. Normally planning variables are genuine, but advanced cases can also have <>. A genuine planning variable getter needs to be annotated with the `@PlanningVariable` annotation, which needs a non-empty `valueRangeProviderRefs` property. [source,java,options=""nowrap""] ---- @PlanningEntity public class Queen { ... private Row row; @PlanningVariable(valueRangeProviderRefs = {""rowRange""}) public Row getRow() { return row; } public void setRow(Row row) { this.row = row; } } ---- The `valueRangeProviderRefs` property defines what are the possible planning values for this planning variable. It references one or more ``@ValueRangeProvider`` ``id``'s. [NOTE] ==== A @PlanningVariable annotation needs to be on a member in a class with a @PlanningEntity annotation. It is ignored on parent classes or subclasses without that annotation. ==== <> instead of the property works too: [source,java,options=""nowrap""] ---- @PlanningEntity public class Queen { ... @PlanningVariable(valueRangeProviderRefs = {""rowRange""}) private Row row; } ---- [[nullablePlanningVariable]] ==== Nullable Planning Variable By default, an initialized planning variable cannot be ``null``, so an initialized solution will never use `null` for any of its planning variables. In an over-constrained use case, this can be counterproductive. For example: in task assignment with too many tasks for the workforce, we would rather leave low priority tasks unassigned instead of assigning them to an overloaded worker. To allow an initialized planning variable to be ``null``, set `nullable` to ``true``: [source,java,options=""nowrap""] ---- @PlanningVariable(..., nullable = true) public Worker getWorker() { return worker; } ---- [IMPORTANT] ==== Planner will automatically add the value `null` to the value range. There is no need to add `null` in a collection used by a ``ValueRangeProvider``. ==== [NOTE] ==== Using a nullable planning variable implies that your score calculation is responsible for punishing (or even rewarding) variables with a null value. ==== <> (especially <>) does not mix well with a nullable planning variable. Every time the Solver starts or a problem fact change is made, the <> will try to initialize all the `null` variables again, which can be a huge waste of time. One way to deal with this, is to change when a planning entity should be reinitialized with an ``reinitializeVariableEntityFilter``: [source,java,options=""nowrap""] ---- @PlanningVariable(..., nullable = true, reinitializeVariableEntityFilter = ReinitializeTaskFilter.class) public Worker getWorker() { return worker; } ---- [[whenIsAPlanningVariableInitialized]] ==== When is a Planning Variable Considered Initialized? A planning variable is considered initialized if its value is not `null` or if the variable is ``nullable``. So a nullable variable is always considered initialized, even when a custom `reinitializeVariableEntityFilter` triggers a reinitialization during construction heuristics. A planning entity is initialized if all of its planning variables are initialized. A `Solution` is initialized if all of its planning entities are initialized. [[planningValueAndPlanningValueRange]] === Planning Value and Planning Value Range [[planningValue]] ==== Planning Value A planning value is a possible value for a genuine planning variable. Usually, a planning value is a problem fact, but it can also be any object, for example a ``double``. It can even be another planning entity or even a interface implemented by both a planning entity and a problem fact. A planning value range is the set of possible planning values for a planning variable. This set can be a countable (for example row ``1``, ``2``, `3` or ``4``) or uncountable (for example any `double` between `0.0` and ``1.0``). [[planningValueRangeProvider]] ==== Planning Value Range Provider [[planningValueRangeProviderOverview]] ===== Overview The value range of a planning variable is defined with the `@ValueRangeProvider` annotation. A `@ValueRangeProvider` annotation always has a property ``id``, which is referenced by the ``@PlanningVariable``'s property ``valueRangeProviderRefs``. This annotation can be located on 2 types of methods: * On the Solution: All planning entities share the same value range. * On the planning entity: The value range differs per planning entity. This is less common. [NOTE] ==== A @ValueRangeProvider annotation needs to be on a member in a class with a @PlanningSolution or a @PlanningEntity annotation. It is ignored on parent classes or subclasses without those annotations. ==== The return type of that method can be 2 types: * ``Collection``: The value range is defined by a `Collection` (usually a ``List``) of its possible values. * ``ValueRange``: The value range is defined by its bounds. This is less common. [[valueRangeProviderOnSolution]] ===== `ValueRangeProvider` on the `Solution` All instances of the same planning entity class share the same set of possible planning values for that planning variable. This is the most common way to configure a value range. The `Solution` implementation has method that returns a `Collection` (or a ``ValueRange``). Any value from that `Collection` is a possible planning value for this planning variable. [source,java,options=""nowrap""] ---- @PlanningVariable(valueRangeProviderRefs = {""rowRange""}) public Row getRow() { return row; } ---- [source,java,options=""nowrap""] ---- @PlanningSolution public class NQueens { ... @ValueRangeProvider(id = ""rowRange"") public List getRowList() { return rowList; } } ---- [IMPORTANT] ==== That `Collection` (or ``ValueRange``) must not contain the value ``null``, not even for a <>. ==== <> instead of the property works too: [source,java,options=""nowrap""] ---- @PlanningSolution public class NQueens { ... @ValueRangeProvider(id = ""rowRange"") private List rowList; } ---- [[valueRangeProviderOnPlanningEntity]] ===== `ValueRangeProvider` on the Planning Entity Each planning entity has its own value range (a set of possible planning values) for the planning variable. For example, if a teacher can *never* teach in a room that does not belong to his department, lectures of that teacher can limit their room value range to the rooms of his department. [source,java,options=""nowrap""] ---- @PlanningVariable(valueRangeProviderRefs = {""departmentRoomRange""}) public Room getRoom() { return room; } @ValueRangeProvider(id = ""departmentRoomRange"") public List getPossibleRoomList() { return getCourse().getTeacher().getDepartment().getRoomList(); } ---- Never use this to enforce a soft constraint (or even a hard constraint when the problem might not have a feasible solution). For example: __Unless there is no other way__, a teacher can not teach in a room that does not belong to his department. In this case, the teacher should _not_ be limited in his room value range (because sometimes there is no other way). [NOTE] ==== By limiting the value range specifically of one planning entity, you are effectively creating a __built-in hard constraint__. This can have the benefit of severely lowering the number of possible solutions; however, it can also away the freedom of the optimization algorithms to temporarily break that constraint in order to escape from a local optimum. ==== A planning entity should _not_ use other planning entities to determinate its value range. That would only try to make the planning entity solve the planning problem itself and interfere with the optimization algorithms. Every entity has its own `List` instance, unless multiple entities have the same value range. For example, if teacher A and B belong to the same department, they use the same `List` instance. Furthermore, each `List` contains a subset of the same set of planning value instances. For example, if department A and B can both use room X, then their `List` instances contain the same `Room` instance. [NOTE] ==== A `ValueRangeProvider` on the planning entity consumes more memory than `ValueRangeProvider` on the Solution and disables certain automatic performance optimizations. ==== [WARNING] ==== A `ValueRangeProvider` on the planning entity is not currently compatible with a <> variable. ==== [[valueRangeFactory]] ===== `ValueRangeFactory` Instead of a ``Collection``, you can also return a `ValueRange` or ``CountableValueRange``, build by the ``ValueRangeFactory``: [source,java,options=""nowrap""] ---- @ValueRangeProvider(id = ""delayRange"") public CountableValueRange getDelayRange() { return ValueRangeFactory.createIntValueRange(0, 5000); } ---- A `ValueRange` uses far less memory, because it only holds the bounds. In the example above, a `Collection` would need to hold all `5000` ints, instead of just the two bounds. Furthermore, an `incrementUnit` can be specified, for example if you have to buy stocks in units of 200 pieces: [source,java,options=""nowrap""] ---- @ValueRangeProvider(id = ""stockAmountRange"") public CountableValueRange getStockAmountRange() { // Range: 0, 200, 400, 600, ..., 9999600, 9999800, 10000000 return ValueRangeFactory.createIntValueRange(0, 10000000, 200); } ---- [NOTE] ==== Return `CountableValueRange` instead of `ValueRange` whenever possible (so Planner knows that it's countable). ==== The `ValueRangeFactory` has creation methods for several value class types: * ``boolean``: A boolean range. * ``int``: A 32bit integer range. * ``long``: A 64bit integer range. * ``double``: A 64bit floating point range which only supports random selection (because it does not implement ``CountableValueRange``). * ``BigInteger``: An arbitrary-precision integer range. * ``BigDecimal``: A decimal point range. By default, the increment unit is the lowest non-zero value in the scale of the bounds. * `Temporal` (such as ``LocalDate``, ``LocalDateTime``, ...): A time range. [[combineValueRangeProviders]] ===== Combine ValueRangeProviders Value range providers can be combined, for example: [source,java,options=""nowrap""] ---- @PlanningVariable(valueRangeProviderRefs = {""companyCarRange"", ""personalCarRange""}) public Car getCar() { return car; } ---- [source,java,options=""nowrap""] ---- @ValueRangeProvider(id = ""companyCarRange"") public List getCompanyCarList() { return companyCarList; } @ValueRangeProvider(id = ""personalCarRange"") public List getPersonalCarList() { return personalCarList; } ---- [[planningValueStrength]] ==== Planning Value Strength Some optimization algorithms work a bit more efficiently if they have an estimation of which planning values are stronger, which means they are more likely to satisfy a planning entity. For example: in bin packing bigger containers are more likely to fit an item and in course scheduling bigger rooms are less likely to break the student capacity constraint. Usually, the efficiency gain of planning value strength is far less than that of <>. [NOTE] ==== *Do not try to use planning value strength to implement a business constraint.* It will not affect the score function: if we have infinite solving time, the returned solution will be the same. To affect the score function, <>. Only consider adding planning value strength too if it can make the solver more efficient. ==== To allow the heuristics to take advantage of that domain specific information, set a `strengthComparatorClass` to the `@PlanningVariable` annotation: [source,java,options=""nowrap""] ---- @PlanningVariable(..., strengthComparatorClass = CloudComputerStrengthComparator.class) public CloudComputer getComputer() { return computer; } ---- [source,java,options=""nowrap""] ---- public class CloudComputerStrengthComparator implements Comparator { public int compare(CloudComputer a, CloudComputer b) { return new CompareToBuilder() .append(a.getMultiplicand(), b.getMultiplicand()) .append(b.getCost(), a.getCost()) // Descending (but this is debatable) .append(a.getId(), b.getId()) .toComparison(); } } ---- [NOTE] ==== If you have multiple planning value classes in the _same_ value range, the `strengthComparatorClass` needs to implement a `Comparator` of a common superclass (for example ``Comparator``) and be able to handle comparing instances of those different classes. ==== Alternatively, you can also set a `strengthWeightFactoryClass` to the `@PlanningVariable` annotation, so you have access to the rest of the problem facts from the solution too: [source,java,options=""nowrap""] ---- @PlanningVariable(..., strengthWeightFactoryClass = RowStrengthWeightFactory.class) public Row getRow() { return row; } ---- See <> for more information. [IMPORTANT] ==== Strength should be implemented ascending: weaker values are lower, stronger values are higher. For example in bin packing: small container < medium container < big container. ==== _None of the current planning variable state in any of the planning entities should be used to compare planning values._ During construction heuristics, those variables are likely to be ``null``. For example, none of the `row` variables of any `Queen` may be used to determine the strength of a ``Row``. [[chainedPlanningVariable]] ==== Chained Planning Variable (TSP, VRP, ...) Some use cases, such as TSP and Vehicle Routing, require __chaining__. This means the planning entities point to each other and form a chain. By modeling the problem as a set of chains (instead of a set of trees/loops), the search space is heavily reduced. A planning variable that is chained either: * Directly points to a problem fact (or planning entity), which is called an __anchor__. * Points to another planning entity with the same planning variable, which recursively points to an anchor. Here are some example of valid and invalid chains: image::Chapter-Planner_configuration/chainPrinciples.png[align=""center""] *Every initialized planning entity is part of an open-ended chain that begins from an anchor.* A valid model means that: * A chain is never a loop. The tail is always open. * Every chain always has exactly one anchor. The anchor is a problem fact, never a planning entity. * A chain is never a tree, it is always a line. Every anchor or planning entity has at most one trailing planning entity. * Every initialized planning entity is part of a chain. * An anchor with no planning entities pointing to it, is also considered a chain. [WARNING] ==== A planning problem instance given to the `Solver` must be valid. ==== [NOTE] ==== If your constraints dictate a closed chain, model it as an open-ended chain (which is easier to persist in a database) and implement a score constraint for the last entity back to the anchor. ==== The optimization algorithms and built-in ``Move``s do chain correction to guarantee that the model stays valid: image::Chapter-Planner_configuration/chainCorrection.png[align=""center""] [WARNING] ==== A custom `Move` implementation must leave the model in a valid state. ==== For example, in TSP the anchor is a `Domicile` (in vehicle routing it is ``Vehicle``): [source,java,options=""nowrap""] ---- public class Domicile ... implements Standstill { ... public City getCity() {...} } ---- The anchor (which is a problem fact) and the planning entity implement a common interface, for example TSP's ``Standstill``: [source,java,options=""nowrap""] ---- public interface Standstill { City getCity(); } ---- That interface is the return type of the planning variable. Furthermore, the planning variable is chained. For example TSP's `Visit` (in vehicle routing it is ``Customer``): [source,java,options=""nowrap""] ---- @PlanningEntity public class Visit ... implements Standstill { ... public City getCity() {...} @PlanningVariable(graphType = PlanningVariableGraphType.CHAINED, valueRangeProviderRefs = {""domicileRange"", ""visitRange""}) public Standstill getPreviousStandstill() { return previousStandstill; } public void setPreviousStandstill(Standstill previousStandstill) { this.previousStandstill = previousStandstill; } } ---- Notice how two value range providers are usually combined: * The value range provider that holds the anchors, for example ``domicileList``. * The value range provider that holds the initialized planning entities, for example ``visitList``. [[shadowVariable]] === Shadow Variable [[shadowVariableIntroduction]] ==== Introduction A shadow variable is a planning variable whose correct value can be deduced from the state of the genuine planning variables. Even though such a variable violates the principle of normalization by definition, in some use cases it can be very practical to use a shadow variable, especially to express the constraints more naturally. For example in vehicle routing with time windows: the arrival time at a customer for a vehicle can be calculated based on the previously visited customers of that vehicle (and the known travel times between two locations). image::Chapter-Planner_configuration/planningVariableListener.png[align=""center""] When the customers for a vehicle change, the arrival time for each customer is automatically adjusted. For more information, see the <>. From a score calculation perspective, a shadow variable is like any other planning variable. From an optimization perspective, Planner effectively only optimizes the genuine variables (and mostly ignores the shadow variables): it just assures that when a genuine variable changes, any dependent shadow variables are changed accordingly. [IMPORTANT] ==== **Any class that has at least one shadow variable, is a planning entity class**, even if it has no genuine planning variables. That entity class needs to be defined in the solver configuration (unless classes are <>) and be annotated accordingly. An genuine planning entity class has at least one genuine planning variable, but can have shadow variables too. A shadow planning entity class has no genuine planning variables and at least one shadow planning variable. ==== There are several built-in shadow variables: [[bidirectionalVariable]] ==== Bi-directional Variable (Inverse Relation Shadow Variable) Two variables are bi-directional if their instances always point to each other (unless one side points to `null` and the other side does not exist). So if A references B, then B references A. image::Chapter-Planner_configuration/bidirectionalVariable.png[align=""center""] For a non-chained planning variable, the bi-directional relationship must be a many to one relationship. To map a bi-directional relationship between two planning variables, annotate the master side (which is the genuine side) as a normal planning variable: [source,java,options=""nowrap""] ---- @PlanningEntity public class CloudProcess { @PlanningVariable(...) public CloudComputer getComputer() { return computer; } public void setComputer(CloudComputer computer) {...} } ---- And then annotate the other side (which is the shadow side) with a `@InverseRelationShadowVariable` annotation on a `Collection` (usually a `Set` or ``List``) property: [source,java,options=""nowrap""] ---- @PlanningEntity public class CloudComputer { @InverseRelationShadowVariable(sourceVariableName = ""computer"") public List getProcessList() { return processList; } } ---- The `sourceVariableName` property is the name of the genuine planning variable on the return type of the getter (so the name of the genuine planning variable on the _other_ side). [NOTE] ==== The shadow property, which is a ``Collection``, can never be ``null``. If no genuine variable is referencing that shadow entity, then it is an empty ``Collection``. Furthermore it must be a mutable `Collection` because once the Solver starts initializing or changing genuine planning variables, it will add and remove to the ``Collection``s of those shadow variables accordingly. ==== For a chained planning variable, the bi-directional relationship must be a one to one relationship. In that case, the genuine side looks like this: [source,java,options=""nowrap""] ---- @PlanningEntity public class Customer ... { @PlanningVariable(graphType = PlanningVariableGraphType.CHAINED, ...) public Standstill getPreviousStandstill() { return previousStandstill; } public void setPreviousStandstill(Standstill previousStandstill) {...} } ---- And the shadow side looks like this: [source,java,options=""nowrap""] ---- @PlanningEntity public class Standstill { @InverseRelationShadowVariable(sourceVariableName = ""previousStandstill"") public Customer getNextCustomer() { return nextCustomer; } public void setNextCustomer(Customer nextCustomer) {...} } ---- [WARNING] ==== The input planning problem of a `Solver` must not violate bi-directional relationships. If A points to B, then B must point to A. Planner will not violate that principle during planning, but the input must not violate it. ==== [[anchorShadowVariable]] ==== Anchor Shadow Variable An anchor shadow variable is the anchor of <>. Annotate the anchor property as a `@AnchorShadowVariable` annotation: [source,java,options=""nowrap""] ---- @PlanningEntity public class Customer { @AnchorShadowVariable(sourceVariableName = ""previousStandstill"") public Vehicle getVehicle() {...} public void setVehicle(Vehicle vehicle) {...} } ---- The `sourceVariableName` property is the name of the chained variable on the same entity class. [[customVariableListener]] ==== Custom `VariableListener` To update a shadow variable, Planner uses a ``VariableListener``. To define a custom shadow variable, write a custom ``VariableListener``: implement the interface and annotate it on the shadow variable that needs to change. [source,java,options=""nowrap""] ---- @PlanningVariable(...) public Standstill getPreviousStandstill() { return previousStandstill; } @CustomShadowVariable(variableListenerClass = VehicleUpdatingVariableListener.class, sources = {@PlanningVariableReference(variableName = ""previousStandstill"")}) public Vehicle getVehicle() { return vehicle; } ---- The `variableName` is the variable that triggers changes in the shadow variable(s). [NOTE] ==== If the class of the trigger variable is different than the shadow variable, also specify the `entityClass` on ``@PlanningVariableReference``. In that case, make sure that that `entityClass` is also properly configured as a planning entity class in the solver config, or the `VariableListener` will simply never trigger. ==== For example, the `VehicleUpdatingVariableListener` assures that every `Customer` in a chain has the same ``Vehicle``, namely the chain's anchor. [source,java,options=""nowrap""] ---- public class VehicleUpdatingVariableListener implements VariableListener { public void afterEntityAdded(ScoreDirector scoreDirector, Customer customer) { updateVehicle(scoreDirector, customer); } public void afterVariableChanged(ScoreDirector scoreDirector, Customer customer) { updateVehicle(scoreDirector, customer); } ... protected void updateVehicle(ScoreDirector scoreDirector, Customer sourceCustomer) { Standstill previousStandstill = sourceCustomer.getPreviousStandstill(); Vehicle vehicle = previousStandstill == null ? null : previousStandstill.getVehicle(); Customer shadowCustomer = sourceCustomer; while (shadowCustomer != null && shadowCustomer.getVehicle() != vehicle) { scoreDirector.beforeVariableChanged(shadowCustomer, ""vehicle""); shadowCustomer.setVehicle(vehicle); scoreDirector.afterVariableChanged(shadowCustomer, ""vehicle""); shadowCustomer = shadowCustomer.getNextCustomer(); } } } ---- [WARNING] ==== A `VariableListener` can only change shadow variables. It must never change a genuine planning variable or a problem fact. ==== [WARNING] ==== Any change of a shadow variable must be told to the ``ScoreDirector``. ==== If one `VariableListener` changes two shadow variables (because having two separate ``VariableListener``s would be inefficient), then annotate only the first shadow variable with the `variableListenerClass` and let the other shadow variable(s) reference the first shadow variable: [source,java,options=""nowrap""] ---- @PlanningVariable(...) public Standstill getPreviousStandstill() { return previousStandstill; } @CustomShadowVariable(variableListenerClass = TransportTimeAndCapacityUpdatingVariableListener.class, sources = {@PlanningVariableReference(variableName = ""previousStandstill"")}) public Integer getTransportTime() { return transportTime; } @CustomShadowVariable(variableListenerRef = @PlanningVariableReference(variableName = ""transportTime"")) public Integer getCapacity() { return capacity; } ---- [[variableListenerTriggeringOrder]] ==== VariableListener triggering order All shadow variables are triggered by a ``VariableListener``, regardless if it's a built-in or a custom shadow variable. The genuine and shadow variables form a graph, that determines the order in which the ``afterEntityAdded()``, `afterVariableChanged()` and `afterEntityRemoved()` methods are called: image::Chapter-Planner_configuration/shadowVariableOrder.png[align=""center""] [NOTE] ==== In the example above, D could have also been ordered after E (or F) because there is no direct or indirect dependency between D and E (or F). ==== Planner guarantees that: * The first ``VariableListener``'s `after*()` methods trigger _after_ the last genuine variable has changed. Therefore the genuine variables (A and B in the example above) are guaranteed to be in a consistent state across all its instances (with values A1, A2 and B1 in the example above) because the entire `Move` has been applied. * The second ``VariableListener``'s `after*()` methods trigger _after_ the last first shadow variable has changed. Therefore the first shadow variable (C in the example above) are guaranteed to be in consistent state across all its instances (with values C1 and C2 in the example above). And of course the genuine variables too. * And so forth. Planner does not guarantee the order in which the `after*()` methods are called for the _same_``VariableListener`` with different parameters (such as A1 and A2 in the example above), although they are likely to be in the order in which they were affected. By default, Planner does not guarantee that the events are unique. For example, if a shadow variable on an entity is changed twice in the same move (for example by 2 different genuine variables), then that will cause the same event twice on the ``VariableListener``s that are listening to that original shadow variable. To avoid dealing with that complexity, overwrite the method `requiresUniqueEntityEvents()` to receive unique events at the cost of a small performance penalty: [source,java,options=""nowrap""] ---- public class StartTimeUpdatingVariableListener implements VariableListener { @Override public boolean requiresUniqueEntityEvents() { return true; } ... } ---- [[planningProblemAndPlanningSolution]] === Planning Problem and Planning Solution [[planningProblemInstance]] ==== Planning Problem Instance A dataset for a planning problem needs to be wrapped in a class for the `Solver` to solve. That solution class represents both the planning problem and (if solved) a solution. It is annotated with a `@PlanningSolution` annotation. For example in n queens, the solution class is the `NQueens` class, which contains a `Column` list, a `Row` list, and a `Queen` list. A planning problem is actually an unsolved planning solution or - stated differently - an uninitialized solution. For example in n queens, that `NQueens` class has the `@PlanningSolution` annotation, yet every `Queen` in an unsolved `NQueens` class is not yet assigned to a `Row` (their `row` property is ``null``). That's not a feasible solution. It's not even a possible solution. It's an uninitialized solution. [[solutionClass]] ==== Solution Class A solution class holds all problem facts, planning entities and a score. It is annotated with a`` @PlanningSolution`` annotation. For example, an `NQueens` instance holds a list of all columns, all rows and all `Queen` instances: [source,java,options=""nowrap""] ---- @PlanningSolution public class NQueens { // Problem facts private int n; private List columnList; private List rowList; // Planning entities private List queenList; private SimpleScore score; ... } ---- Without <>, the solver configuration also needs to declare the planning solution class: [source,java,options=""nowrap""] ---- ... org.optaplanner.examples.nqueens.domain.NQueens ... ---- [[planningEntitiesOfASolution]] ==== Planning Entities of a Solution (@PlanningEntityCollectionProperty) Planner needs to extract the entity instances from the solution instance. It gets those collection(s) by calling every getter (or field) that is annotated with ``@PlanningEntityCollectionProperty``: [source,java,options=""nowrap""] ---- @PlanningSolution public class NQueens { ... private List queenList; @PlanningEntityCollectionProperty public List getQueenList() { return queenList; } } ---- There can be multiple `@PlanningEntityCollectionProperty` annotated members. Those can even return a `Collection` with the same entity class type. [NOTE] ==== A @PlanningEntityCollectionProperty annotation needs to be on a member in a class with a @PlanningSolution annotation. It is ignored on parent classes or subclasses without that annotation. ==== In rare cases, a planning entity might be a singleton: use `@PlanningEntityProperty` on its getter (or field) instead. [[scoreOfASolution]] ==== `Score` of a Solution (``@PlanningScore``) A `Solution` requires a score property, which is annotated with a `@PlanningScore` annotation. The score property is `null` if the the score hasn't been calculated yet. The `score` property is typed to the specific `Score` implementation of your use case. For example, `NQueens` uses a <>: [source,java,options=""nowrap""] ---- @PlanningSolution public class NQueens { ... private SimpleScore score; @PlanningScore public SimpleScore getScore() { return score; } public void setScore(SimpleScore score) { this.score = score; } } ---- Most use cases use a <> instead: [source,java,options=""nowrap""] ---- @PlanningSolution public class CloudBalance { ... private HardSoftScore score; @PlanningScore public HardSoftScore getScore() { return score; } public void setScore(HardSoftScore score) { this.score = score; } } ---- Some use cases use <>. [[getProblemFacts]] ==== Problem Facts of a Solution (``@ProblemFactCollectionProperty``) For <>, Planner needs to extract the problem fact instances from the solution instance. It gets those collection(s) by calling every method (or field) that is annotated with ``@ProblemFactCollectionProperty``. All objects returned by those methods will be inserted into the Drools session, so the score rules can access them. For example in `NQueens` all `Column` and `Row` instances are problem facts. [source,java,options=""nowrap""] ---- @PlanningSolution public class NQueens { ... private List columnList; private List rowList; @ProblemFactCollectionProperty public List getColumnList() { return columnList; } @ProblemFactCollectionProperty public List getRowList() { return rowList; } } ---- All planning entities are automatically inserted into the Drools working memory. Do note add an annotation on their properties. [NOTE] ==== The problem facts methods are not called often: at most only once per solver phase per solver thread. ==== There can be multiple `@ProblemFactCollectionProperty` annotated members. Those can even return a `Collection` with the same class type, but they shouldn't return the same instance twice. [NOTE] ==== A @ProblemFactCollectionProperty annotation needs to be on a member in a class with a @PlanningSolution annotation. It is ignored on parent classes or subclasses without that annotation. ==== In rare cases, a problem fact might be a singleton: use `@ProblemFactProperty` on its method (or field) instead. [[cachedProblemFact]] ===== Cached Problem Fact A cached problem fact is a problem fact that does not exist in the real domain model, but is calculated before the `Solver` really starts solving. The problem facts methods have the opportunity to enrich the domain model with such cached problem facts, which can lead to simpler and faster score constraints. For example in examination, a cached problem fact `TopicConflict` is created for every two ``Topic``s which share at least one ``Student``. [source,java,options=""nowrap""] ---- @ProblemFactCollectionProperty private List calculateTopicConflictList() { List topicConflictList = new ArrayList(); for (Topic leftTopic : topicList) { for (Topic rightTopic : topicList) { if (leftTopic.getId() < rightTopic.getId()) { int studentSize = 0; for (Student student : leftTopic.getStudentList()) { if (rightTopic.getStudentList().contains(student)) { studentSize++; } } if (studentSize > 0) { topicConflictList.add(new TopicConflict(leftTopic, rightTopic, studentSize)); } } } } return topicConflictList; } ---- Where a score constraint needs to check that no two exams with a topic that shares a student are scheduled close together (depending on the constraint: at the same time, in a row, or in the same day), the `TopicConflict` instance can be used as a problem fact, rather than having to combine every two `Student` instances. [[cloningASolution]] ==== Cloning a Solution Most (if not all) optimization algorithms clone the solution each time they encounter a new best solution (so they can recall it later) or to work with multiple solutions in parallel. [NOTE] ==== There are many ways to clone, such as a shallow clone, deep clone, ... This context focuses on __a planning clone__. ==== A planning clone of a solution must fulfill these requirements: * The clone must represent the same planning problem. Usually it reuses the same instances of the problem facts and problem fact collections as the original. * The clone must use different, cloned instances of the entities and entity collections. Changes to an original `Solution` entity's variables must not affect its clone. image::Chapter-Planner_configuration/solutionCloning.png[align=""center""] *Implementing a planning clone method is hard, therefore you do not need to implement it.* [[fieldAccessingSolutionCloner]] ===== `FieldAccessingSolutionCloner` This `SolutionCloner` is used by default. It works well for most use cases. [WARNING] ==== When the `FieldAccessingSolutionCloner` clones one of your collections or maps, it may not recognize the implementation and replace it with `ArrayList`, `LinkedHashSet`, `TreeSet`, `LinkedHashMap` or `TreeMap` (whichever is more applicable) . It recognizes most of the common JDK collection and map implementations. ==== The `FieldAccessingSolutionCloner` does not clone problem facts by default. If any of your problem facts needs to be deep cloned for a planning clone, for example if the problem fact references a planning entity or the planning solution, mark it with a `@DeepPlanningClone` annotation: [source,java,options=""nowrap""] ---- @DeepPlanningClone public class SeatDesignationDependency { private SeatDesignation leftSeatDesignation; // planning entity private SeatDesignation rightSeatDesignation; // planning entity ... } ---- In the example above, because `SeatDesignation` is a planning entity (which is deep planning cloned automatically), `SeatDesignationDependency` must also be deep planning cloned. Alternatively, the `@DeepPlanningClone` annotation can also be used on a getter method. [[customCloning]] ===== Custom Cloning with a SolutionCloner To use a customer cloner, configure it on the planning solution: [source,java,options=""nowrap""] ---- @PlanningSolution(solutionCloner = NQueensSolutionCloner.class) public class NQueens { ... } ---- For example, a `NQueens` planning clone only deep clones all `Queen` instances. So when the original solution changes (later on during planning) and one or more ``Queen`` instances change, the planning clone isn't affected. [source,java,options=""nowrap""] ---- public class NQueensSolutionCloner implements SolutionCloner { @Override public NQueens cloneSolution(CloneLedger ledger, NQueens original) { NQueens clone = new NQueens(); ledger.registerClone(original, clone); clone.setId(original.getId()); clone.setN(original.getN()); clone.setColumnList(original.getColumnList()); clone.setRowList(original.getRowList()); List queenList = original.getQueenList(); List clonedQueenList = new ArrayList(queenList.size()); for (Queen originalQueen : queenList) { Queen cloneQueen = new Queen(); ledger.registerClone(originalQueen, cloneQueen); cloneQueen.setId(originalQueen.getId()); cloneQueen.setColumn(originalQueen.getColumn()); cloneQueen.setRow(originalQueen.getRow()); clonedQueenList.add(cloneQueen); } clone.setQueenList(clonedQueenList); clone.setScore(original.getScore()); return clone; } } ---- _The `cloneSolution()` method should only deep clone the planning entities._ Notice that the problem facts, such as `Column` and `Row` are normally _not_ cloned: even their `List` instances are _not_ cloned. If the problem facts were cloned too, then you would have to make sure that the new planning entity clones also refer to the new problem facts clones used by the cloned solution. For example, if you were to clone all `Row` instances, then each `Queen` clone and the `NQueens` clone itself should refer to those new `Row` clones. [WARNING] ==== Cloning an entity with a <> variable is devious: a variable of an entity A might point to another entity B. If A is cloned, then its variable must point to the clone of B, not the original B. ==== [[createAnUninitializedSolution]] ==== Create an Uninitialized Solution Create a `Solution` instance to represent your planning problem's dataset, so it can be set on the `Solver` as the planning problem to solve. For example in n queens, an `NQueens` instance is created with the required `Column` and `Row` instances and every `Queen` set to a different `column` and every `row` set to ``null``. [source,java,options=""nowrap""] ---- private NQueens createNQueens(int n) { NQueens nQueens = new NQueens(); nQueens.setId(0L); nQueens.setN(n); nQueens.setColumnList(createColumnList(nQueens)); nQueens.setRowList(createRowList(nQueens)); nQueens.setQueenList(createQueenList(nQueens)); return nQueens; } private List createQueenList(NQueens nQueens) { int n = nQueens.getN(); List queenList = new ArrayList(n); long id = 0L; for (Column column : nQueens.getColumnList()) { Queen queen = new Queen(); queen.setId(id); id++; queen.setColumn(column); // Notice that we leave the PlanningVariable properties on null queenList.add(queen); } return queenList; } ---- .Uninitialized Solution for the 4 Queens Puzzle image::Chapter-Planner_configuration/uninitializedNQueens04.png[align=""left""] Usually, most of this data comes from your data layer, and your `Solution` implementation just aggregates that data and creates the uninitialized planning entity instances to plan: [source,java,options=""nowrap""] ---- private void createLectureList(CourseSchedule schedule) { List courseList = schedule.getCourseList(); List lectureList = new ArrayList(courseList.size()); long id = 0L; for (Course course : courseList) { for (int i = 0; i < course.getLectureSize(); i++) { Lecture lecture = new Lecture(); lecture.setId(id); id++; lecture.setCourse(course); lecture.setLectureIndexInCourse(i); // Notice that we leave the PlanningVariable properties (period and room) on null lectureList.add(lecture); } } schedule.setLectureList(lectureList); } ---- [[useTheSolver]] == Use the `Solver` [[theSolverInterface]] === The `Solver` Interface A `Solver` implementation will solve your planning problem. [source,java,options=""nowrap""] ---- public interface Solver { Solution_ solve(Solution_ planningProblem); ... } ---- A `Solver` can only solve one planning problem instance at a time. A `Solver` should only be accessed from a single thread, except for the methods that are specifically javadocced as being thread-safe. It is built with a ``SolverFactory``, there is no need to implement it yourself. [[solvingAProblem]] === Solving a Problem Solving a problem is quite easy once you have: * A `Solver` built from a solver configuration * A `Solution` that represents the planning problem instance Just provide the planning problem as argument to the `solve()` method and it will return the best solution found: [source,java,options=""nowrap""] ---- NQueens bestSolution = solver.solve(planningProblem); ---- For example in n queens, the `solve()` method will return an `NQueens` instance with every `Queen` assigned to a ``Row``. .Best Solution for the 4 Queens Puzzle in 8ms (Also an Optimal Solution) image::Chapter-Planner_configuration/solvedNQueens04.png[align=""left""] The `solve(Solution)` method can take a long time (depending on the problem size and the solver configuration). The `Solver` intelligently wades through <> of possible solutions and remembers the best solution it encounters during solving. Depending on a number factors (including problem size, how much time the `Solver` has, the solver configuration, ...), <>. [NOTE] ==== The `Solution` instance given to the method `solve(Solution)` is changed by the ``Solver``, but do not mistake it for the best solution. The `Solution` instance returned by the methods `solve(Solution)` or `getBestSolution()` is most likely <> of the instance given to the method ``solve(Solution)``, which implies it is a different instance. ==== [NOTE] ==== The `Solution` instance given to the `solve(Solution)` method does not need to be uninitialized. It can be partially or fully initialized, which is often the case in <>. ==== [[environmentMode]] === Environment Mode: Are There Bugs in my Code? The environment mode allows you to detect common bugs in your implementation. It does not affect the <>. You can set the environment mode in the solver configuration XML file: [source,xml,options=""nowrap""] ---- FAST_ASSERT ... ---- A solver has a single `Random` instance. Some solver configurations use the `Random` instance a lot more than others. For example, Simulated Annealing depends highly on random numbers, while Tabu Search only depends on it to deal with score ties. The environment mode influences the seed of that `Random` instance. These are the environment modes: [[environmentModeFullAssert]] ==== FULL_ASSERT The FULL_ASSERT mode turns on all assertions (such as assert that the incremental score calculation is uncorrupted for each move) to fail-fast on a bug in a Move implementation, a score rule, the rule engine itself, ... This mode is reproducible (see the reproducible mode). It is also intrusive because it calls the method `calculateScore()` more frequently than a non-assert mode. The FULL_ASSERT mode is horribly slow (because it does not rely on incremental score calculation). [[environmentModeNonIntrusiveFullAssert]] ==== NON_INTRUSIVE_FULL_ASSERT The NON_INTRUSIVE_FULL_ASSERT turns on several assertions to fail-fast on a bug in a Move implementation, a score rule, the rule engine itself, ... This mode is reproducible (see the reproducible mode). It is non-intrusive because it does not call the method `calculateScore()` more frequently than a non assert mode. The NON_INTRUSIVE_FULL_ASSERT mode is horribly slow (because it does not rely on incremental score calculation). [[environmentModeFastAssert]] ==== FAST_ASSERT The FAST_ASSERT mode turns on most assertions (such as assert that an undoMove's score is the same as before the Move) to fail-fast on a bug in a Move implementation, a score rule, the rule engine itself, ... This mode is reproducible (see the reproducible mode). It is also intrusive because it calls the method `calculateScore()` more frequently than a non assert mode. The FAST_ASSERT mode is slow. It is recommended to write a test case that does a short run of your planning problem with the FAST_ASSERT mode on. [[environmentModeReproducible]] ==== REPRODUCIBLE (default) The reproducible mode is the default mode because it is recommended during development. In this mode, two runs in the same Planner version will execute the same code in the same order. **Those two runs will have the same result at every step**, except if the note below applies. This enables you to reproduce bugs consistently. It also allows you to benchmark certain refactorings (such as a score constraint performance optimization) fairly across runs. [NOTE] ==== Despite the reproducible mode, your application might still not be fully reproducible because of: * Use of `HashSet` (or another `Collection` which has an inconsistent order between JVM runs) for collections of planning entities or planning values (but not normal problem facts), especially in the `Solution` implementation. Replace it with ``LinkedHashSet``. * Combining a time gradient dependent algorithms (most notably Simulated Annealing) together with time spent termination. A sufficiently large difference in allocated CPU time will influence the time gradient values. Replace Simulated Annealing with Late Acceptance. Or instead, replace time spent termination with step count termination. ==== The reproducible mode can be slightly slower than the non-reproducible mode. If your production environment can benefit from reproducibility, use this mode in production. In practice, this mode uses the default, fixed <> if no seed is specified, and it also disables certain concurrency optimizations (such as work stealing). [[environmentModeProduction]] ==== NON_REPRODUCIBLE The non-reproducible mode can be slightly faster than the reproducible mode. Avoid using it during development as it makes debugging and bug fixing painful. If your production environment doesn't care about reproducibility, use this mode in production. In practice, this mode uses no fixed <> if no seed is specified. [[logging]] === Logging Level: What is the `Solver` Doing? The best way to illuminate the black box that is a ``Solver``, is to play with the logging level: * **error**: Log errors, except those that are thrown to the calling code as a ``RuntimeException``. + [NOTE] ==== **If an error happens, Planner normally fails fast**: it throws a subclass of `RuntimeException` with a detailed message to the calling code. It does not log it as an error itself to avoid duplicate log messages. Except if the calling code explicitly catches and eats that ``RuntimeException``, a ``Thread``'s default `ExceptionHandler` will log it as an error anyway. Meanwhile, the code is disrupted from doing further harm or obfuscating the error. ==== * **warn**: Log suspicious circumstances. * **info**: Log every phase and the solver itself. See <>. * **debug**: Log every step of every phase. See <>. * **trace**: Log every move of every step of every phase. See <>. [NOTE] ==== Turning on `trace` logging, will slow down performance considerably: it is often four times slower. However, it is invaluable during development to discover a bottleneck. Even `debug` logging can slow down performance considerably for fast stepping algorithms (such as Late Acceptance and Simulated Annealing), but not for slow stepping algorithms (such as Tabu Search). Both cause congestion in <> with most appenders, see below. In Eclipse, `debug` logging to the console tends to cause congestion with a score calculation speeds above 10 000 per second. Nor IntelliJ, nor the Maven command line suffer from this problem. ==== For example, set it to `debug` logging, to see when the phases end and how fast steps are taken: [source,options=""nowrap""] ---- INFO Solving started: time spent (3), best score (-4init/0), random (JDK with seed 0). DEBUG CH step (0), time spent (5), score (-3init/0), selected move count (1), picked move (Queen-2 {null -> Row-0}). DEBUG CH step (1), time spent (7), score (-2init/0), selected move count (3), picked move (Queen-1 {null -> Row-2}). DEBUG CH step (2), time spent (10), score (-1init/0), selected move count (4), picked move (Queen-3 {null -> Row-3}). DEBUG CH step (3), time spent (12), score (-1), selected move count (4), picked move (Queen-0 {null -> Row-1}). INFO Construction Heuristic phase (0) ended: time spent (12), best score (-1), score calculation speed (9000/sec), step total (4). DEBUG LS step (0), time spent (19), score (-1), best score (-1), accepted/selected move count (12/12), picked move (Queen-1 {Row-2 -> Row-3}). DEBUG LS step (1), time spent (24), score (0), new best score (0), accepted/selected move count (9/12), picked move (Queen-3 {Row-3 -> Row-2}). INFO Local Search phase (1) ended: time spent (24), best score (0), score calculation speed (4000/sec), step total (2). INFO Solving ended: time spent (24), best score (0), score calculation speed (7000/sec), phase total (2), environment mode (REPRODUCIBLE). ---- All time spent values are in milliseconds. Everything is logged to http://www.slf4j.org/[SLF4J], which is a simple logging facade which delegates every log message to Logback, Apache Commons Logging, Log4j or java.util.logging. Add a dependency to the logging adaptor for your logging framework of choice. If you are not using any logging framework yet, use Logback by adding this Maven dependency (there is no need to add an extra bridge dependency): [source,xml,options=""nowrap""] ---- ch.qos.logback logback-classic 1.x ---- Configure the logging level on the `org.optaplanner` package in your `logback.xml` file: [source,xml,options=""nowrap""] ---- ... ---- If it isn't picked up, temporarily add the system property `-Dlogback.debug=true` to figure out why. [NOTE] ==== When running multiple solvers or one <>, most appenders (including the console) cause congestion with `debug` and `trace` logging. Switch to an async appender to avoid this problem or turn off `debug` logging. ==== If instead, you are still using Log4J 1.x (and you do not want to switch to its faster successor, Logback), add the bridge dependency: [source,xml,options=""nowrap""] ---- org.slf4j slf4j-log4j12 1.x ---- And configure the logging level on the package `org.optaplanner` in your `log4j.xml` file: [source,xml,options=""nowrap""] ---- ... ---- [NOTE] ==== In a multitenant application, multiple `Solver` instances might be running at the same time. To separate their logging into distinct files, surround the `solve()` call with an http://logback.qos.ch/manual/mdc.html[MDC]: [source,java,options=""nowrap""] ---- MDC.put(""tenant.name"",tenantName); MySolution bestSolution = solver.solve(planningProblem); MDC.remove(""tenant.name""); ---- Then configure your logger to use different files for each ``${tenant.name}``. For example in Logback, use a `SiftingAppender` in ``logback.xml``: [source,xml,options=""nowrap""] ---- tenant.name unknown local/log/optaplanner-${tenant.name}.log ... ---- ==== [[randomNumberGenerator]] === Random Number Generator Many heuristics and metaheuristics depend on a pseudorandom number generator for move selection, to resolve score ties, probability based move acceptance, ... During solving, the same `Random` instance is reused to improve reproducibility, performance and uniform distribution of random values. To change the random seed of that `Random` instance, specify a ``randomSeed``: [source,xml,options=""nowrap""] ---- 0 ... ---- To change the pseudorandom number generator implementation, specify a ``randomType``: [source,xml,options=""nowrap""] ---- MERSENNE_TWISTER ... ---- The following types are supported: * `JDK` (default): Standard implementation (``java.util.Random``). * ``MERSENNE_TWISTER``: Implementation by http://commons.apache.org/proper/commons-math/userguide/random.html[Commons Math]. * ``WELL512A``, ``WELL1024A``, ``WELL19937A``, ``WELL19937C``, `WELL44497A` and ``WELL44497B``: Implementation by http://commons.apache.org/proper/commons-math/userguide/random.html[Commons Math]. For most use cases, the randomType has no significant impact on the average quality of the best solution on multiple datasets. If you want to confirm this on your use case, use the <>. ",16238,True,2783.748394154499,median " -1 dilate_0_0_2160_3840_0_3_3_1_1_12 0 4 0 1 1 imgHelper2_4102 0 0 0 FIFO_SRL 3583567312 8 0 3 0 0 0 1 2 imgHelper3_4103 0 0 0 FIFO_SRL 3583731872 8 1 3 0 0 0 1 3 p_src_rows 0 0 0 FIFO_SRL 3582933056 32 0 3 0 0 0 1 4 p_src_cols 0 0 0 FIFO_SRL 3580163504 32 0 3 0 0 0 6 0 0 11 p_src_rows_read /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp .. 340 dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; dilate_0_0_2160_3840_0_3_3_1_1_s 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; 340 auto fifo srl FIFO_SRL 81 32 2 0 19 20 read 0 0 0 0 3.32 1 -1 0 12 p_src_cols_read /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp .. 341 dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; dilate_0_0_2160_3840_0_3_3_1_1_s 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; 341 auto fifo srl FIFO_SRL 81 32 2 0 21 22 read 0 0 0 0 3.32 2 -1 0 13 trunc_ln340 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp .. 340 dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; dilate_0_0_2160_3840_0_3_3_1_1_s 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; 340 trunc_ln340_fu_52_p1 3580164736 16 1 0 23 trunc 0 0 0 0 0.00 3 -1 0 14 trunc_ln341 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp .. 341 dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; dilate_0_0_2160_3840_0_3_3_1_1_s 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; 341 trunc_ln341_fu_57_p1 113 16 1 0 24 trunc 0 0 0 0 0.00 4 -1 0 15 _ln376 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp .. 376 dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; dilate_0_0_2160_3840_0_3_3_1_1_s 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; 376 grp_xfdilate_2160_3840_1_0_1_0_3841_3_3_s_fu_42 113 0 5 0 26 27 28 29 30 call 0 0 0 0 0.00 5 -1 0 16 _ln0 0 0 0 113 0 0 0 ret 0 0 0 0 0.00 6 -1 1 0 2 25 xfdilate_2160_3840_1_0_1_0_3841_3_3_s 0 0 0 3583186448 0 6 <constant:xfdilate<2160, 3840, 1, 0, 1, 0, 3841, 3, 3>> 1 0 3 17 dilate<0, 0, 2160, 3840, 0, 3, 3, 1, 1>12 0 0 0 1768189039 6 0 11 12 13 14 15 16 9 0 20 1 3 11 0 22 1 4 12 0 23 1 11 13 0 24 1 12 14 0 26 1 25 15 0 27 1 1 15 0 28 1 2 15 0 29 1 13 15 0 30 1 14 15 0 1 0 1 dilate<0, 0, 2160, 3840, 0, 3, 3, 1, 1>12 dilate_0_0_2160_3840_0_3_3_1_1_12 0 0 0 1 0 17 -1 -1 -1 -1 13 8319373 0 2 0 1 5 0 11 1 1 12 1 1 13 1 1 14 1 1 15 2 2 2 8 0 5 1 1 6 1 1 7 1 1 8 1 1 9 1 1 10 1 1 15 1 2 16 1 1 1 0 1 2 -1 1 0 0 0 1 0 grp_xfdilate_2160_3840_1_0_1_0_3841_3_3_s_fu_42 (xfdilate_2160_3840_1_0_1_0_3841_3_3_s) 3 0 BRAM 6 FF 611 LUT 819 1 0 ap_block_state1 ( or ) 4 0 (0P0) 1 (1P1) 1 FF 0 LUT 1 0 0 0 0 6 0 ap_NS_fsm 4 0 (0Size) 3 (1Bits) 1 (2Count) 3 LUT 13 ap_done 4 0 (0Size) 2 (1Bits) 1 (2Count) 2 LUT 9 imgHelper2_4102_read 4 0 (0Size) 2 (1Bits) 1 (2Count) 2 LUT 9 imgHelper3_4103_write 4 0 (0Size) 2 (1Bits) 1 (2Count) 2 LUT 9 p_src_cols_blk_n 4 0 (0Size) 2 (1Bits) 1 (2Count) 2 LUT 9 p_src_rows_blk_n 4 0 (0Size) 2 (1Bits) 1 (2Count) 2 LUT 9 5 0 ap_CS_fsm 3 0 (Bits) 2 (Consts) 0 FF 2 ap_done_reg 3 0 (Bits) 1 (Consts) 0 FF 1 grp_xfdilate_2160_3840_1_0_1_0_3841_3_3_s_fu_42_ap_start_reg 3 0 (Bits) 1 (Consts) 0 FF 1 trunc_ln340_reg_62 3 0 (Bits) 16 (Consts) 0 FF 16 trunc_ln341_reg_67 3 0 (Bits) 16 (Consts) 0 FF 16 1 0 grp_xfdilate_2160_3840_1_0_1_0_3841_3_3_s_fu_42 0 0 1 0 grp_xfdilate_2160_3840_1_0_1_0_3841_3_3_s_fu_42 (xfdilate_2160_3840_1_0_1_0_3841_3_3_s) 1 0 15 0 0 0 0 0 0 6 0 11 0 0 12 0 0 13 0 0 14 0 0 15 0 1 16 1 0 1 0 17 0 1 0 0 5 0 30 1 0 11 36 1 0 12 42 2 0 15 15 52 1 0 13 57 1 0 14 2 0 trunc_ln340_fu_52 1 0 13 trunc_ln341_fu_57 1 0 14 1 0 grp_xfdilate_2160_3840_1_0_1_0_3841_3_3_s_fu_42 2 0 15 15 2 0 p_src_cols_read_read_fu_36 1 0 12 p_src_rows_read_read_fu_30 1 0 11 0 0 0 0 2 0 62 1 0 13 67 1 0 14 2 0 trunc_ln340_reg_62 1 0 13 trunc_ln341_reg_67 1 0 14 0 0 0 0 4 0 imgHelper2_4102 1 0 call 1 0 15 imgHelper3_4103 1 0 call 1 0 15 p_src_cols 1 0 read 1 0 12 p_src_rows 1 0 read 1 0 11 4 0 1 1150 10 2 1151 10 3 1150 10 4 1150 10 3 0 11 1150 10 12 1150 10 15 -1 -1 ",12544,False,2212.8464538505877,median "// Module included in the following assemblies: // // * installing/installing_aws/installing-aws-china.adoc // * installing/installing_aws/installing-aws-customizations.adoc // * installing/installing_aws/installing-aws-government-region.adoc // * installing/installing_aws/installing-aws-network-customizations.adoc // * installing/installing_aws/installing-aws-private.adoc // * installing/installing_aws/installing-aws-secret-region.adoc // * installing/installing_aws/installing-aws-vpc.adoc // * installing/installing_aws/installing-restricted-networks-aws-installer-provisioned.adoc // * installing/installing_azure/installing-azure-customizations.adoc // * installing/installing_azure/installing-azure-government-region.adoc // * installing/installing_azure/installing-azure-network-customizations.adoc // * installing/installing_azure/installing-azure-private.adoc // * installing/installing_azure/installing-azure-vnet.adoc // * installing/installing_bare_metal/installing-bare-metal-network-customizations.adoc // * installing/installing_bare_metal/installing-bare-metal.adoc // * installing/installing_bare_metal/installing-restricted-networks-bare-metal.adoc // * installing/installing_gcp/installing-gcp-customizations.adoc // * installing/installing_gcp/installing-gcp-network-customizations.adoc // * installing/installing_gcp/installing-gcp-private.adoc // * installing/installing_gcp/installing-gcp-vpc.adoc // * installing/installing_gcp/installing-restricted-networks-gcp-installer-provisioned.adoc // * installing/installing_ibm_cloud_public/installing-ibm-cloud-customizations.adoc // * installing/installing_ibm_cloud_public/installing-ibm-cloud-network-customizations.adoc // * installing/installing_ibm_power/installing-ibm-power.adoc // * installing/installing_ibm_power/installing-restricted-networks-ibm-power.adoc // * installing/installing_ibm_z/installing-ibm-z-kvm.adoc // * installing/installing_ibm_z/installing-ibm-z.adoc // * installing/installing_ibm_z/installing-restricted-networks-ibm-z-kvm.adoc // * installing/installing_ibm_z/installing-restricted-networks-ibm-z.adoc // * installing/installing_openstack/installing-openstack-installer-custom.adoc // * installing/installing_openstack/installing-openstack-installer-kuryr.adoc // * installing/installing_openstack/installing-openstack-installer-restricted.adoc // * installing/installing_openstack/installing-openstack-installer-sr-iov.adoc // * installing/installing_openstack/installing-openstack-user-kuryr.adoc // * installing/installing_openstack/installing-openstack-user-sr-iov-kuryr.adoc // * installing/installing_openstack/installing-openstack-user-sr-iov.adoc // * installing/installing_openstack/installing-openstack-user.adoc // * installing/installing_rhv/installing-rhv-customizations.adoc // * installing/installing_vmc/installing-restricted-networks-vmc.adoc // * installing/installing_vmc/installing-vmc-customizations.adoc // * installing/installing_vmc/installing-vmc-network-customizations.adoc // * installing/installing_vsphere/installing-restricted-networks-installer-provisioned-vsphere.adoc // * installing/installing_vsphere/installing-vsphere-installer-provisioned-customizations.adoc // * installing/installing_vsphere/installing-vsphere-installer-provisioned-network-customizations.adoc // * installing/installing_azure_stack_hub/installing-azure-stack-hub-default.adoc ifeval::[""{context}"" == ""installing-aws-customizations""] :aws: endif::[] ifeval::[""{context}"" == ""installing-aws-government-region""] :aws: endif::[] ifeval::[""{context}"" == ""installing-aws-secret-region""] :aws: endif::[] ifeval::[""{context}"" == ""installing-aws-network-customizations""] :aws: endif::[] ifeval::[""{context}"" == ""installing-aws-private""] :aws: endif::[] ifeval::[""{context}"" == ""installing-aws-vpc""] :aws: endif::[] ifeval::[""{context}"" == ""installing-restricted-networks-aws-installer-provisioned""] :aws: endif::[] ifeval::[""{context}"" == ""installing-azure-customizations""] :azure: endif::[] ifeval::[""{context}"" == ""installing-azure-government-region""] :azure: endif::[] ifeval::[""{context}"" == ""installing-azure-network-customizations""] :azure: endif::[] ifeval::[""{context}"" == ""installing-azure-private""] :azure: endif::[] ifeval::[""{context}"" == ""installing-azure-vnet""] :azure: endif::[] ifeval::[""{context}"" == ""installing-gcp-customizations""] :gcp: endif::[] // OSDOCS-1640 - IPv4/IPv6 dual-stack bare metal only // But only for installer-provisioned // https://bugzilla.redhat.com/show_bug.cgi?id=2020416 //ifeval::[""{context}"" == ""installing-bare-metal""] //:bare: //endif::[] // OSDOCS-1640 - IPv4/IPv6 dual-stack bare metal only // But only for installer-provisioned // https://bugzilla.redhat.com/show_bug.cgi?id=2020416 //ifeval::[""{context}"" == ""installing-bare-metal-network-customizations""] //:bare: //endif::[] // OSDOCS-1640 - IPv4/IPv6 dual-stack bare metal only // But only for installer-provisioned // https://bugzilla.redhat.com/show_bug.cgi?id=2020416 //ifeval::[""{context}"" == ""installing-restricted-networks-bare-metal""] //:bare: //endif::[] ifeval::[""{context}"" == ""installing-gcp-private""] :gcp: endif::[] ifeval::[""{context}"" == ""installing-gcp-network-customizations""] :gcp: endif::[] ifeval::[""{context}"" == ""installing-gcp-vpc""] :gcp: endif::[] ifeval::[""{context}"" == ""installing-restricted-networks-gcp-installer-provisioned""] :gcp: endif::[] ifeval::[""{context}"" == ""installing-aws-customizations""] :aws: endif::[] ifeval::[""{context}"" == ""installing-ibm-cloud-customizations""] :ibm-cloud: endif::[] ifeval::[""{context}"" == ""installing-ibm-cloud-network-customizations""] :ibm-cloud: endif::[] ifeval::[""{context}"" == ""installing-openstack-installer-custom""] :osp: :osp-custom: endif::[] ifeval::[""{context}"" == ""installing-openstack-installer-kuryr""] :osp: :osp-kuryr: endif::[] ifeval::[""{context}"" == ""installing-openstack-user""] :osp: :osp-custom: endif::[] ifeval::[""{context}"" == ""installing-openstack-user-kuryr""] :osp: :osp-kuryr: endif::[] ifeval::[""{context}"" == ""installing-openstack-user-sr-iov""] :osp: :osp-custom: endif::[] ifeval::[""{context}"" == ""installing-openstack-user-sr-iov-kuryr""] :osp: :osp-kuryr: endif::[] ifeval::[""{context}"" == ""installing-rhv-customizations""] :rhv: endif::[] ifeval::[""{context}"" == ""installing-vsphere-installer-provisioned-customizations""] :vsphere: endif::[] ifeval::[""{context}"" == ""installing-vsphere-installer-provisioned-network-customizations""] :vsphere: endif::[] ifeval::[""{context}"" == ""installing-vmc-customizations""] :vmc: endif::[] ifeval::[""{context}"" == ""installing-vmc-network-customizations""] :vmc: endif::[] ifeval::[""{context}"" == ""installing-restricted-networks-vmc""] :vmc: endif::[] ifeval::[""{context}"" == ""installing-openstack-installer-restricted""] :osp: :osp-custom: endif::[] ifeval::[""{context}"" == ""installing-restricted-networks-installer-provisioned-vsphere""] :vsphere: endif::[] ifeval::[""{context}"" == ""installing-ibm-z""] :ibm-z: endif::[] ifeval::[""{context}"" == ""installing-ibm-z-kvm""] :ibm-z: endif::[] ifeval::[""{context}"" == ""installing-restricted-networks-ibm-z""] :ibm-z: endif::[] ifeval::[""{context}"" == ""installing-restricted-networks-ibm-z-kvm""] :ibm-z: endif::[] ifeval::[""{context}"" == ""installing-ibm-power""] :ibm-power: endif::[] ifeval::[""{context}"" == ""installing-restricted-networks-ibm-power""] :ibm-power: endif::[] ifeval::[""{context}"" == ""installing-azure-stack-hub-default""] :ash-default: endif::[] :_content-type: CONCEPT [id=""installation-configuration-parameters_{context}""] = Installation configuration parameters // If install-config.yaml is generated by openshift-install ifndef::bare,ibm-power,ibm-z,ash-default[] Before you deploy an {product-title} cluster, you provide parameter values to describe your account on the cloud platform that hosts your cluster and optionally customize your cluster's platform. When you create the `install-config.yaml` installation configuration file, you provide values for the required parameters through the command line. If you customize your cluster, you can modify the `install-config.yaml` file to provide more details about the platform. endif::bare,ibm-power,ibm-z,ash-default[] // If the user manually creates install-config.yaml ifdef::bare,ibm-power,ibm-z,ash-default[] Before you deploy an {product-title} cluster, you provide a customized `install-config.yaml` installation configuration file that describes the details for your environment. endif::bare,ibm-power,ibm-z,ash-default[] [NOTE] ==== After installation, you cannot modify these parameters in the `install-config.yaml` file. ==== [id=""installation-configuration-parameters-required_{context}""] == Required configuration parameters Required installation configuration parameters are described in the following table: .Required parameters [cols="".^2,.^3,.^5a"",options=""header""] |==== |Parameter|Description|Values |`apiVersion` |The API version for the `install-config.yaml` content. The current version is `v1`. The installer may also support older API versions. |String |`baseDomain` |The base domain of your cloud provider. The base domain is used to create routes to your {product-title} cluster components. The full DNS name for your cluster is a combination of the `baseDomain` and `metadata.name` parameter values that uses the `.` format. |A fully-qualified domain or subdomain name, such as `example.com`. |`metadata` |Kubernetes resource `ObjectMeta`, from which only the `name` parameter is consumed. |Object |`metadata.name` |The name of the cluster. DNS records for the cluster are all subdomains of `{{.metadata.name}}.{{.baseDomain}}`. |String of lowercase letters, hyphens (`-`), and periods (`.`), such as `dev`. ifdef::osp[] The string must be 14 characters or fewer long. endif::osp[] |`platform` |The configuration for the specific platform upon which to perform the installation: `aws`, `baremetal`, `azure`, `ibmcloud`, `openstack`, `ovirt`, `vsphere`, or `{}`. For additional information about `platform.` parameters, consult the table for your specific platform that follows. |Object ifndef::openshift-origin[] |`pullSecret` |Get a pull secret from link:https://console.redhat.com/openshift/install/pull-secret[] to authenticate downloading container images for {product-title} components from services such as Quay.io. | [source,json] ---- { ""auths"":{ ""cloud.openshift.com"":{ ""auth"":""b3Blb="", ""email"":""you@example.com"" }, ""quay.io"":{ ""auth"":""b3Blb="", ""email"":""you@example.com"" } } } ---- endif::[] |==== [id=""installation-configuration-parameters-network_{context}""] == Network configuration parameters You can customize your installation configuration based on the requirements of your existing network infrastructure. For example, you can expand the IP address block for the cluster network or provide different IP address blocks than the defaults. ifndef::bare[] Only IPv4 addresses are supported. endif::bare[] ifdef::bare[] If you use the OVN-Kubernetes cluster network provider, both IPv4 and IPv6 address families are supported. If you use the OpenShift SDN cluster network provider, only the IPv4 address family is supported. If you configure your cluster to use both IP address families, review the following requirements: * Both IP families must use the same network interface for the default gateway. * You must specify IPv4 and IPv6 addresses in the same order for all network configuration parameters. For example, in the following configuration IPv4 addresses are listed before IPv6 addresses. + [source,yaml] ---- networking: clusterNetwork: - cidr: 10.128.0.0/14 hostPrefix: 23 - cidr: fd00:10:128::/56 hostPrefix: 64 serviceNetwork: - 172.30.0.0/16 - fd00:172:16::/112 ---- endif::bare[] .Network parameters [cols="".^2,.^3a,.^3a"",options=""header""] |==== |Parameter|Description|Values |`networking` |The configuration for the cluster network. |Object [NOTE] ==== You cannot modify parameters specified by the `networking` object after installation. ==== |`networking.networkType` |The cluster network provider Container Network Interface (CNI) plug-in to install. | ifdef::openshift-origin[] Either `OpenShiftSDN` or `OVNKubernetes`. The default value is `OVNKubernetes`. endif::openshift-origin[] ifndef::openshift-origin[] Either `OpenShiftSDN` or `OVNKubernetes`. The default value is `OpenShiftSDN`. endif::openshift-origin[] |`networking.clusterNetwork` | The IP address blocks for pods. The default value is `10.128.0.0/14` with a host prefix of `/23`. If you specify multiple IP address blocks, the blocks must not overlap. |An array of objects. For example: [source,yaml] ---- ifndef::bare[] networking: clusterNetwork: - cidr: 10.128.0.0/14 hostPrefix: 23 endif::bare[] ifdef::bare[] networking: clusterNetwork: - cidr: 10.128.0.0/14 hostPrefix: 23 - cidr: fd01::/48 hostPrefix: 64 endif::bare[] ---- |`networking.clusterNetwork.cidr` | Required if you use `networking.clusterNetwork`. An IP address block. ifndef::bare[] An IPv4 network. endif::bare[] ifdef::bare[] If you use the OpenShift SDN network provider, specify an IPv4 network. If you use the OVN-Kubernetes network provider, you can specify IPv4 and IPv6 networks. endif::bare[] | An IP address block in Classless Inter-Domain Routing (CIDR) notation. The prefix length for an IPv4 block is between `0` and `32`. ifdef::bare[] The prefix length for an IPv6 block is between `0` and `128`. For example, `10.128.0.0/14` or `fd01::/48`. endif::bare[] |`networking.clusterNetwork.hostPrefix` |The subnet prefix length to assign to each individual node. For example, if `hostPrefix` is set to `23` then each node is assigned a `/23` subnet out of the given `cidr`. A `hostPrefix` value of `23` provides 510 (2^(32 - 23) - 2) pod IP addresses. | A subnet prefix. ifndef::bare[] The default value is `23`. endif::bare[] ifdef::bare[] For an IPv4 network the default value is `23`. For an IPv6 network the default value is `64`. The default value is also the minimum value for IPv6. endif::bare[] |`networking.serviceNetwork` | The IP address block for services. The default value is `172.30.0.0/16`. The OpenShift SDN and OVN-Kubernetes network providers support only a single IP address block for the service network. ifdef::bare[] If you use the OVN-Kubernetes network provider, you can specify an IP address block for both of the IPv4 and IPv6 address families. endif::bare[] | An array with an IP address block in CIDR format. For example: [source,yaml] ---- ifndef::bare[] networking: serviceNetwork: - 172.30.0.0/16 endif::bare[] ifdef::bare[] networking: serviceNetwork: - 172.30.0.0/16 - fd02::/112 endif::bare[] ---- |`networking.machineNetwork` | The IP address blocks for machines. If you specify multiple IP address blocks, the blocks must not overlap. ifdef::ibm-z,ibm-power[] If you specify multiple IP kernel arguments, the `machineNetwork.cidr` value must be the CIDR of the primary network. endif::ibm-z,ibm-power[] |An array of objects. For example: [source,yaml] ---- networking: machineNetwork: - cidr: 10.0.0.0/16 ---- |`networking.machineNetwork.cidr` | Required if you use `networking.machineNetwork`. An IP address block. The default value is `10.0.0.0/16` for all platforms other than libvirt. For libvirt, the default value is `192.168.126.0/24`. | An IP network block in CIDR notation. ifndef::bare[] For example, `10.0.0.0/16`. endif::bare[] ifdef::bare[] For example, `10.0.0.0/16` or `fd00::/48`. endif::bare[] [NOTE] ==== Set the `networking.machineNetwork` to match the CIDR that the preferred NIC resides in. ==== |==== [id=""installation-configuration-parameters-optional_{context}""] == Optional configuration parameters Optional installation configuration parameters are described in the following table: .Optional parameters [cols="".^2,.^3a,.^3a"",options=""header""] |==== |Parameter|Description|Values |`additionalTrustBundle` |A PEM-encoded X.509 certificate bundle that is added to the nodes' trusted certificate store. This trust bundle may also be used when a proxy has been configured. |String |`cgroupsV2` |Enables link:https://www.kernel.org/doc/html/latest/admin-guide/cgroup-v2.html[Linux control groups version 2] (cgroups v2) on specific nodes in your cluster. The {product-title} process for enabling cgroups v2 disables all cgroup version 1 controllers and hierarchies. The {product-title} cgroups version 2 feature is in Developer Preview and is not supported by Red Hat at this time. |`true` |`compute` |The configuration for the machines that comprise the compute nodes. |Array of `MachinePool` objects. ifdef::rhv[] For details, see the ""Additional RHV parameters for machine pools"" table. endif::rhv[] ifndef::ibm-z,ibm-power[] |`compute.architecture` |Determines the instruction set architecture of the machines in the pool. Currently, clusters with varied architectures are not supported. All pools must specify the same architecture. Valid values are `amd64` and `arm64`. See _Supported installation methods for different platforms_ in _Installing_ documentation for information about instance availability. |String endif::ibm-z,ibm-power[] ifdef::ibm-z[] |`compute.architecture` |Determines the instruction set architecture of the machines in the pool. Currently, heteregeneous clusters are not supported, so all pools must specify the same architecture. Valid values are `s390x` (the default). |String endif::ibm-z[] ifdef::ibm-power[] |`compute.architecture` |Determines the instruction set architecture of the machines in the pool. Currently, heteregeneous clusters are not supported, so all pools must specify the same architecture. Valid values are `ppc64le` (the default). |String endif::ibm-power[] |`compute.hyperthreading` |Whether to enable or disable simultaneous multithreading, or `hyperthreading`, on compute machines. By default, simultaneous multithreading is enabled to increase the performance of your machines' cores. [IMPORTANT] ==== If you disable simultaneous multithreading, ensure that your capacity planning accounts for the dramatically decreased machine performance. ==== |`Enabled` or `Disabled` |`compute.name` |Required if you use `compute`. The name of the machine pool. |`worker` |`compute.platform` |Required if you use `compute`. Use this parameter to specify the cloud provider to host the worker machines. This parameter value must match the `controlPlane.platform` parameter value. |`aws`, `azure`, `gcp`, `ibmcloud`, `openstack`, `ovirt`, `vsphere`, or `{}` |`compute.replicas` |The number of compute machines, which are also known as worker machines, to provision. |A positive integer greater than or equal to `2`. The default value is `3`. |`controlPlane` |The configuration for the machines that comprise the control plane. |Array of `MachinePool` objects. ifdef::rhv[] For details, see the ""Additional RHV parameters for machine pools"" table. endif::rhv[] ifndef::ibm-z,ibm-power[] |`controlPlane.architecture` |Determines the instruction set architecture of the machines in the pool. Currently, clusters with varied architectures are not supported. All pools must specify the same architecture. Valid values are `amd64` and `arm64`. See _Supported installation methods for different platforms_ in _Installing_ documentation for information about instance availability. |String endif::ibm-z,ibm-power[] ifdef::ibm-z[] |`controlPlane.architecture` |Determines the instruction set architecture of the machines in the pool. Currently, heterogeneous clusters are not supported, so all pools must specify the same architecture. Valid values are `s390x` (the default). |String endif::ibm-z[] ifdef::ibm-power[] |`controlPlane.architecture` |Determines the instruction set architecture of the machines in the pool. Currently, heterogeneous clusters are not supported, so all pools must specify the same architecture. Valid values are `ppc64le` (the default). |String endif::ibm-power[] |`controlPlane.hyperthreading` |Whether to enable or disable simultaneous multithreading, or `hyperthreading`, on control plane machines. By default, simultaneous multithreading is enabled to increase the performance of your machines' cores. [IMPORTANT] ==== If you disable simultaneous multithreading, ensure that your capacity planning accounts for the dramatically decreased machine performance. ==== |`Enabled` or `Disabled` |`controlPlane.name` |Required if you use `controlPlane`. The name of the machine pool. |`master` |`controlPlane.platform` |Required if you use `controlPlane`. Use this parameter to specify the cloud provider that hosts the control plane machines. This parameter value must match the `compute.platform` parameter value. |`aws`, `azure`, `gcp`, `ibmcloud`, `openstack`, `ovirt`, `vsphere`, or `{}` |`controlPlane.replicas` |The number of control plane machines to provision. |The only supported value is `3`, which is the default value. |`credentialsMode` |The Cloud Credential Operator (CCO) mode. If no mode is specified, the CCO dynamically tries to determine the capabilities of the provided credentials, with a preference for mint mode on the platforms where multiple modes are supported. [NOTE] ==== Not all CCO modes are supported for all cloud providers. For more information on CCO modes, see the _Cloud Credential Operator_ entry in the _Platform Operators reference_ content. ==== |`Mint`, `Passthrough`, `Manual`, or an empty string (`""""`). ifndef::openshift-origin[] |`fips` |Enable or disable FIPS mode. The default is `false` (disabled). If FIPS mode is enabled, the {op-system-first} machines that {product-title} runs on bypass the default Kubernetes cryptography suite and use the cryptography modules that are provided with {op-system} instead. [IMPORTANT] ==== The use of FIPS Validated / Modules in Process cryptographic libraries is only supported on {product-title} deployments on the `x86_64` architecture. ==== [NOTE] ==== If you are using Azure File storage, you cannot enable FIPS mode. ==== |`false` or `true` endif::openshift-origin[] |`imageContentSources` |Sources and repositories for the release-image content. |Array of objects. Includes a `source` and, optionally, `mirrors`, as described in the following rows of this table. |`imageContentSources.source` |Required if you use `imageContentSources`. Specify the repository that users refer to, for example, in image pull specifications. |String |`imageContentSources.mirrors` |Specify one or more repositories that may also contain the same images. |Array of strings |`publish` |How to publish or expose the user-facing endpoints of your cluster, such as the Kubernetes API, OpenShift routes. | ifdef::aws,azure,gcp[] `Internal` or `External`. To deploy a private cluster, which cannot be accessed from the internet, set `publish` to `Internal`. The default value is `External`. endif::[] ifndef::aws,azure,gcp[] `Internal` or `External`. The default value is `External`. Setting this field to `Internal` is not supported on non-cloud platforms and IBM Cloud. ifeval::[{product-version} <= 4.7] [IMPORTANT] ==== If the value of the field is set to `Internal`, the cluster will become non-functional. For more information, refer to link:https://bugzilla.redhat.com/show_bug.cgi?id=1953035[BZ#1953035]. ==== endif::[] endif::[] |`sshKey` | The SSH key to authenticate access to your cluster machines. [NOTE] ==== For production {product-title} clusters on which you want to perform installation debugging or disaster recovery, specify an SSH key that your `ssh-agent` process uses. ==== a|For example, `sshKey: ssh-ed25519 AAAA..`. |==== ifdef::aws[] [id=""installation-configuration-parameters-optional-aws_{context}""] == Optional AWS configuration parameters Optional AWS configuration parameters are described in the following table: .Optional AWS parameters [cols="".^2,.^3,.^5a"",options=""header""] |==== |Parameter|Description|Values |`compute.platform.aws.amiID` |The AWS AMI used to boot compute machines for the cluster. This is required for regions that require a custom {op-system} AMI. |Any published or custom {op-system} AMI that belongs to the set AWS region. See _{op-system} AMIs for AWS infrastructure_ for available AMI IDs. |`compute.platform.aws.iamRole` |A pre-existing AWS IAM role applied to the compute machine pool instance profiles. You can use these fields to match naming schemes and include predefined permissions boundaries for your IAM roles. If undefined, the installation program creates a new IAM role. |The name of a valid AWS IAM role. |`compute.platform.aws.rootVolume.iops` |The Input/Output Operations Per Second (IOPS) that is reserved for the root volume. |Integer, for example `4000`. |`compute.platform.aws.rootVolume.size` |The size in GiB of the root volume. |Integer, for example `500`. |`compute.platform.aws.rootVolume.type` |The type of the root volume. |Valid link:https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html[AWS EBS volume type], such as `io1`. |`compute.platform.aws.type` |The EC2 instance type for the compute machines. |Valid AWS instance type, such as `m4.2xlarge`. See the *Supported AWS machine types* table that follows. //add an xref when possible. |`compute.platform.aws.zones` |The availability zones where the installation program creates machines for the compute machine pool. If you provide your own VPC, you must provide a subnet in that availability zone. |A list of valid AWS availability zones, such as `us-east-1c`, in a link:https://yaml.org/spec/1.2/spec.html#sequence//[YAML sequence]. |`compute.aws.region` |The AWS region that the installation program creates compute resources in. |Any valid link:https://docs.aws.amazon.com/general/latest/gr/rande.html[AWS region], such as `us-east-1`. [IMPORTANT] ==== When running on ARM based AWS A1 instances, ensure that you enter a region where AWS Graviton processors are available. See link:https://aws.amazon.com/ec2/graviton/#Global_availability[Global availability] map in the AWS documentation. ==== |`controlPlane.platform.aws.amiID` |The AWS AMI used to boot control plane machines for the cluster. This is required for regions that require a custom {op-system} AMI. |Any published or custom {op-system} AMI that belongs to the set AWS region. See _{op-system} AMIs for AWS infrastructure_ for available AMI IDs. |`controlPlane.platform.aws.iamRole` |A pre-existing AWS IAM role applied to the control plane machine pool instance profiles. You can use these fields to match naming schemes and include predefined permissions boundaries for your IAM roles. If undefined, the installation program creates a new IAM role. |The name of a valid AWS IAM role. |`controlPlane.platform.aws.type` |The EC2 instance type for the control plane machines. |Valid AWS instance type, such as `m5.xlarge`. See the *Supported AWS machine types* table that follows. //add an xref when possible |`controlPlane.platform.aws.zones` |The availability zones where the installation program creates machines for the control plane machine pool. |A list of valid AWS availability zones, such as `us-east-1c`, in a link:https://yaml.org/spec/1.2/spec.html#sequence//[YAML sequence]. |`controlPlane.aws.region` |The AWS region that the installation program creates control plane resources in. |Valid link:https://docs.aws.amazon.com/general/latest/gr/rande.html[AWS region], such as `us-east-1`. |`platform.aws.amiID` |The AWS AMI used to boot all machines for the cluster. If set, the AMI must belong to the same region as the cluster. This is required for regions that require a custom {op-system} AMI. |Any published or custom {op-system} AMI that belongs to the set AWS region. See _{op-system} AMIs for AWS infrastructure_ for available AMI IDs. |`platform.aws.hostedZone` |An existing Route 53 private hosted zone for the cluster. You can only use a pre-existing hosted zone when also supplying your own VPC. The hosted zone must already be associated with the user-provided VPC before installation. Also, the domain of the hosted zone must be the cluster domain or a parent of the cluster domain. If undefined, the installation program creates a new hosted zone. |String, for example `Z3URY6TWQ91KVV`. |`platform.aws.serviceEndpoints.name` |The AWS service endpoint name. Custom endpoints are only required for cases where alternative AWS endpoints, like FIPS, must be used. Custom API endpoints can be specified for EC2, S3, IAM, Elastic Load Balancing, Tagging, Route 53, and STS AWS services. |Valid link:https://docs.aws.amazon.com/general/latest/gr/rande.html[AWS service endpoint] name. |`platform.aws.serviceEndpoints.url` |The AWS service endpoint URL. The URL must use the `https` protocol and the host must trust the certificate. |Valid link:https://docs.aws.amazon.com/general/latest/gr/rande.html[AWS service endpoint] URL. |`platform.aws.userTags` |A map of keys and values that the installation program adds as tags to all resources that it creates. |Any valid YAML map, such as key value pairs in the `: ` format. For more information about AWS tags, see link:https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html[Tagging Your Amazon EC2 Resources] in the AWS documentation. |`platform.aws.subnets` |If you provide the VPC instead of allowing the installation program to create the VPC for you, specify the subnet for the cluster to use. The subnet must be part of the same `machineNetwork[].cidr` ranges that you specify. For a standard cluster, specify a public and a private subnet for each availability zone. For a private cluster, specify a private subnet for each availability zone. |Valid subnet IDs. |==== endif::aws[] ifdef::osp[] [id=""installation-configuration-parameters-additional-osp_{context}""] == Additional {rh-openstack-first} configuration parameters Additional {rh-openstack} configuration parameters are described in the following table: .Additional {rh-openstack} parameters [cols="".^2m,.^3a,^5a"",options=""header""] |==== |Parameter|Description|Values |`compute.platform.openstack.rootVolume.size` |For compute machines, the size in gigabytes of the root volume. If you do not set this value, machines use ephemeral storage. |Integer, for example `30`. |`compute.platform.openstack.rootVolume.type` |For compute machines, the root volume's type. |String, for example `performance`. |`controlPlane.platform.openstack.rootVolume.size` |For control plane machines, the size in gigabytes of the root volume. If you do not set this value, machines use ephemeral storage. |Integer, for example `30`. |`controlPlane.platform.openstack.rootVolume.type` |For control plane machines, the root volume's type. |String, for example `performance`. |`platform.openstack.cloud` |The name of the {rh-openstack} cloud to use from the list of clouds in the `clouds.yaml` file. |String, for example `MyCloud`. |`platform.openstack.externalNetwork` |The {rh-openstack} external network name to be used for installation. |String, for example `external`. |`platform.openstack.computeFlavor` |The {rh-openstack} flavor to use for control plane and compute machines. This property is deprecated. To use a flavor as the default for all machine pools, add it as the value of the `type` key in the `platform.openstack.defaultMachinePlatform` property. You can also set a flavor value for each machine pool individually. |String, for example `m1.xlarge`. |==== [id=""installation-configuration-parameters-optional-osp_{context}""] == Optional {rh-openstack} configuration parameters Optional {rh-openstack} configuration parameters are described in the following table: .Optional {rh-openstack} parameters [%header, cols="".^2,.^3,.^5a""] |==== |Parameter|Description|Values |`compute.platform.openstack.additionalNetworkIDs` |Additional networks that are associated with compute machines. Allowed address pairs are not created for additional networks. |A list of one or more UUIDs as strings. For example, `fa806b2f-ac49-4bce-b9db-124bc64209bf`. |`compute.platform.openstack.additionalSecurityGroupIDs` |Additional security groups that are associated with compute machines. |A list of one or more UUIDs as strings. For example, `7ee219f3-d2e9-48a1-96c2-e7429f1b0da7`. |`compute.platform.openstack.zones` |{rh-openstack} Compute (Nova) availability zones (AZs) to install machines on. If this parameter is not set, the installer relies on the default settings for Nova that the {rh-openstack} administrator configured. On clusters that use Kuryr, {rh-openstack} Octavia does not support availability zones. Load balancers and, if you are using the Amphora provider driver, {product-title} services that rely on Amphora VMs, are not created according to the value of this property. |A list of strings. For example, `[""zone-1"", ""zone-2""]`. |`compute.platform.openstack.rootVolume.zones` |For compute machines, the availability zone to install root volumes on. If you do not set a value for this parameter, the installer selects the default availability zone. |A list of strings, for example `[""zone-1"", ""zone-2""]`. |`controlPlane.platform.openstack.additionalNetworkIDs` |Additional networks that are associated with control plane machines. Allowed address pairs are not created for additional networks. |A list of one or more UUIDs as strings. For example, `fa806b2f-ac49-4bce-b9db-124bc64209bf`. |`controlPlane.platform.openstack.additionalSecurityGroupIDs` |Additional security groups that are associated with control plane machines. |A list of one or more UUIDs as strings. For example, `7ee219f3-d2e9-48a1-96c2-e7429f1b0da7`. |`controlPlane.platform.openstack.zones` |{rh-openstack} Compute (Nova) availability zones (AZs) to install machines on. If this parameter is not set, the installer relies on the default settings for Nova that the {rh-openstack} administrator configured. On clusters that use Kuryr, {rh-openstack} Octavia does not support availability zones. Load balancers and, if you are using the Amphora provider driver, {product-title} services that rely on Amphora VMs, are not created according to the value of this property. |A list of strings. For example, `[""zone-1"", ""zone-2""]`. |`controlPlane.platform.openstack.rootVolume.zones` |For control plane machines, the availability zone to install root volumes on. If you do not set this value, the installer selects the default availability zone. |A list of strings, for example `[""zone-1"", ""zone-2""]`. |`platform.openstack.clusterOSImage` |The location from which the installer downloads the {op-system} image. You must set this parameter to perform an installation in a restricted network. |An HTTP or HTTPS URL, optionally with an SHA-256 checksum. For example, `\\http://mirror.example.com/images/rhcos-43.81.201912131630.0-openstack.x86_64.qcow2.gz?sha256=ffebbd68e8a1f2a245ca19522c16c86f67f9ac8e4e0c1f0a812b068b16f7265d`. The value can also be the name of an existing Glance image, for example `my-rhcos`. |`platform.openstack.clusterOSImageProperties` |Properties to add to the installer-uploaded ClusterOSImage in Glance. This property is ignored if `platform.openstack.clusterOSImage` is set to an existing Glance image. You can use this property to exceed the default persistent volume (PV) limit for {rh-openstack} of 26 PVs per node. To exceed the limit, set the `hw_scsi_model` property value to `virtio-scsi` and the `hw_disk_bus` value to `scsi`. You can also use this property to enable the QEMU guest agent by including the `hw_qemu_guest_agent` property with a value of `yes`. |A list of key-value string pairs. For example, `[""hw_scsi_model"": ""virtio-scsi"", ""hw_disk_bus"": ""scsi""]`. |`platform.openstack.defaultMachinePlatform` |The default machine pool platform configuration. | [source,json] ---- { ""type"": ""ml.large"", ""rootVolume"": { ""size"": 30, ""type"": ""performance"" } } ---- |`platform.openstack.ingressFloatingIP` |An existing floating IP address to associate with the Ingress port. To use this property, you must also define the `platform.openstack.externalNetwork` property. |An IP address, for example `128.0.0.1`. |`platform.openstack.apiFloatingIP` |An existing floating IP address to associate with the API load balancer. To use this property, you must also define the `platform.openstack.externalNetwork` property. |An IP address, for example `128.0.0.1`. |`platform.openstack.externalDNS` |IP addresses for external DNS servers that cluster instances use for DNS resolution. |A list of IP addresses as strings. For example, `[""8.8.8.8"", ""192.168.1.12""]`. |`platform.openstack.machinesSubnet` |The UUID of a {rh-openstack} subnet that the cluster's nodes use. Nodes and virtual IP (VIP) ports are created on this subnet. The first item in `networking.machineNetwork` must match the value of `machinesSubnet`. If you deploy to a custom subnet, you cannot specify an external DNS server to the {product-title} installer. Instead, link:https://access.redhat.com/documentation/en-us/red_hat_openstack_platform/16.0/html/command_line_interface_reference/subnet[add DNS to the subnet in {rh-openstack}]. |A UUID as a string. For example, `fa806b2f-ac49-4bce-b9db-124bc64209bf`. |==== endif::osp[] ifdef::azure[] [id=""installation-configuration-parameters-additional-azure_{context}""] == Additional Azure configuration parameters Additional Azure configuration parameters are described in the following table: .Additional Azure parameters [cols="".^2,.^3a,.^3a"",options=""header""] |==== |Parameter|Description|Values |`controlPlane.platform.azure.osDisk.diskSizeGB` |The Azure disk size for the VM. |Integer that represents the size of the disk in GB. The minimum supported disk size is `1024`. |`platform.azure.baseDomainResourceGroupName` |The name of the resource group that contains the DNS zone for your base domain. |String, for example `production_cluster`. |`platform.azure.resourceGroupName` | The name of an already existing resource group to install your cluster to. This resource group must be empty and only used for this specific cluster; the cluster components assume ownership of all resources in the resource group. If you limit the service principal scope of the installation program to this resource group, you must ensure all other resources used by the installation program in your environment have the necessary permissions, such as the public DNS zone and virtual network. Destroying the cluster using the installation program deletes this resource group. |String, for example `existing_resource_group`. |`platform.azure.outboundType` |The outbound routing strategy used to connect your cluster to the internet. If you are using user-defined routing, you must have pre-existing networking available where the outbound routing has already been configured prior to installing a cluster. The installation program is not responsible for configuring user-defined routing. |`LoadBalancer` or `UserDefinedRouting`. The default is `LoadBalancer`. |`platform.azure.region` |The name of the Azure region that hosts your cluster. |Any valid region name, such as `centralus`. |`platform.azure.zone` |List of availability zones to place machines in. For high availability, specify at least two zones. |List of zones, for example `[""1"", ""2"", ""3""]`. |`platform.azure.networkResourceGroupName` |The name of the resource group that contains the existing VNet that you want to deploy your cluster to. This name cannot be the same as the `platform.azure.baseDomainResourceGroupName`. |String. |`platform.azure.virtualNetwork` |The name of the existing VNet that you want to deploy your cluster to. |String. |`platform.azure.controlPlaneSubnet` |The name of the existing subnet in your VNet that you want to deploy your control plane machines to. |Valid CIDR, for example `10.0.0.0/16`. |`platform.azure.computeSubnet` |The name of the existing subnet in your VNet that you want to deploy your compute machines to. |Valid CIDR, for example `10.0.0.0/16`. |`platform.azure.cloudName` |The name of the Azure cloud environment that is used to configure the Azure SDK with the appropriate Azure API endpoints. If empty, the default value `AzurePublicCloud` is used. |Any valid cloud environment, such as `AzurePublicCloud` or `AzureUSGovernmentCloud`. |==== [NOTE] ==== You cannot customize link:https://azure.microsoft.com/en-us/global-infrastructure/availability-zones/[Azure Availability Zones] or link:https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-using-tags[Use tags to organize your Azure resources] with an Azure cluster. ==== endif::azure[] ifdef::gcp[] [id=""installation-configuration-parameters-additional-gcp_{context}""] == Additional Google Cloud Platform (GCP) configuration parameters Additional GCP configuration parameters are described in the following table: .Additional GCP parameters [cols="".^1,.^6a,.^3a"",options=""header""] |==== |Parameter|Description|Values |`platform.gcp.network` |The name of the existing VPC that you want to deploy your cluster to. |String. |`platform.gcp.region` |The name of the GCP region that hosts your cluster. |Any valid region name, such as `us-central1`. |`platform.gcp.type` |The link:https://cloud.google.com/compute/docs/machine-types[GCP machine type]. |The GCP machine type. |`platform.gcp.zones` |The availability zones where the installation program creates machines for the specified MachinePool. |A list of valid link:https://cloud.google.com/compute/docs/regions-zones#available[GCP availability zones], such as `us-central1-a`, in a link:https://yaml.org/spec/1.2/spec.html#sequence//[YAML sequence]. |`platform.gcp.controlPlaneSubnet` |The name of the existing subnet in your VPC that you want to deploy your control plane machines to. |The subnet name. |`platform.gcp.computeSubnet` |The name of the existing subnet in your VPC that you want to deploy your compute machines to. |The subnet name. |`platform.gcp.licenses` |A list of license URLs that must be applied to the compute images. [IMPORTANT] ==== The `licenses` parameter is a deprecated field and nested virtualization is enabled by default. It is not recommended to use this field. ==== |Any license available with the link:https://cloud.google.com/compute/docs/reference/rest/v1/licenses/list[license API], such as the license to enable link:https://cloud.google.com/compute/docs/instances/nested-virtualization/overview[nested virtualization]. You cannot use this parameter with a mechanism that generates pre-built images. Using a license URL forces the installer to copy the source image before use. |`platform.gcp.osDisk.diskSizeGB` |The size of the disk in gigabytes (GB). |Any size between 16 GB and 65536 GB. |`platform.gcp.osDisk.diskType` |The type of disk. |Either the default `pd-ssd` or the `pd-standard` disk type. The control plane nodes must be the `pd-ssd` disk type. The worker nodes can be either type. |`controlPlane.platform.gcp.osDisk.encryptionKey.kmsKey.name` |The name of the customer managed encryption key to be used for control plane machine disk encryption. |The encryption key name. |`controlPlane.platform.gcp.osDisk.encryptionKey.kmsKey.keyRing` |For control plane machines, the name of the KMS key ring to which the KMS key belongs. |The KMS key ring name. |`controlPlane.platform.gcp.osDisk.encryptionKey.kmsKey.location` |For control plane machines, the GCP location in which the key ring exists. For more information on KMS locations, see Google's documentation on link:https://cloud.google.com/kms/docs/locations[Cloud KMS locations]. |The GCP location for the key ring. |`controlPlane.platform.gcp.osDisk.encryptionKey.kmsKey.projectID` |For control plane machines, the ID of the project in which the KMS key ring exists. This value defaults to the VM project ID if not set. |The GCP project ID. //// `controlPlane.platform.gcp.osDisk.encryptionKey.kmsKeyServiceAccount` The GCP Compute Engine System service account used for the encryption request for the given KMS key. The Compute Engine default service account is always used for control plane machines during installation, which follows this pattern: `service-@compute-system.iam.gserviceaccount.com`. The default service account must have access to the KMS key specified for the control plane machines. The custom service account defined is available for use during post-installation operations. For more information on GCP service accounts, see Google's documentation on link:https://cloud.google.com/iam/docs/service-accounts#types[Types of service accounts]. The GCP Compute Engine System service account email, like `@.iam.gserviceaccount.com`. //// // kmsKeyServiceAccount not yet fully supported in 4.7. Re-add when more stable. |`compute.platform.gcp.osDisk.encryptionKey.kmsKey.name` |The name of the customer managed encryption key to be used for compute machine disk encryption. |The encryption key name. |`compute.platform.gcp.osDisk.encryptionKey.kmsKey.keyRing` |For compute machines, the name of the KMS key ring to which the KMS key belongs. |The KMS key ring name. |`compute.platform.gcp.osDisk.encryptionKey.kmsKey.location` |For compute machines, the GCP location in which the key ring exists. For more information on KMS locations, see Google's documentation on link:https://cloud.google.com/kms/docs/locations[Cloud KMS locations]. |The GCP location for the key ring. |`compute.platform.gcp.osDisk.encryptionKey.kmsKey.projectID` |For compute machines, the ID of the project in which the KMS key ring exists. This value defaults to the VM project ID if not set. |The GCP project ID. //// `compute.platform.gcp.osDisk.encryptionKey.kmsKeyServiceAccount` For compute machines, the GCP Compute Engine System service account used for the encryption request for the given KMS key. If left undefined, the Compute Engine default service account is used, which follows this pattern: `service-@compute-system.iam.gserviceaccount.com`. For more information on GCP service accounts, see Google's documentation on link:https://cloud.google.com/iam/docs/service-accounts#types[Types of service accounts]. The GCP Compute Engine System service account email, like `@.iam.gserviceaccount.com`. //// // kmsKeyServiceAccount not yet fully supported in 4.7. Re-add when more stable. |==== endif::gcp[] ifdef::ibm-cloud[] [id=""installation-configuration-parameters-additional-ibm-cloud_{context}""] == Additional IBM Cloud configuration parameters Additional IBM Cloud configuration parameters are described in the following table: .Additional IBM Cloud parameters [cols="".^1,.^6a,.^3a"",options=""header""] |==== |Parameter|Description|Values |`platform.ibmcloud.resourceGroupName` |The name of an existing resource group to install your cluster to. This resource group must only be used for this specific cluster because the cluster components assume ownership of all of the resources in the resource group. If undefined, a new resource group is created for the cluster. [^1^] |String, for example `existing_resource_group`. |`platform.ibmcloud.dedicatedHosts.profile` |The new dedicated host to create. If you specify a value for `platform.ibmcloud.dedicatedHosts.name`, this parameter is not required. |Valid IBM Cloud dedicated host profile, such as `cx2-host-152x304`. [^2^] |`platform.ibmcloud.dedicatedHosts.name` |An existing dedicated host. If you specify a value for `platform.ibmcloud.dedicatedHosts.profile`, this parameter is not required. |String, for example `my-dedicated-host-name`. |`platform.ibmcloud.type` |The instance type for all IBM Cloud machines. |Valid IBM Cloud instance type, such as `bx2-8x32`. [^2^] |==== [.small] -- 1. Whether you define an existing resource group, or if the installer creates one, determines how the resource group is treated when the cluster is uninstalled. If you define a resource group, the installer removes all of the installer-provisioned resources, but leaves the resource group alone; if a resource group is created as part of the installation, the installer removes all of the installer provisioned resources and the resource group. 2. To determine which profile best meets your needs, see https://cloud.ibm.com/docs/vpc?topic=vpc-profiles&interface=ui[Instance Profiles] in the IBM documentation. -- endif::ibm-cloud[] ifdef::rhv[] [id=""installation-configuration-parameters-additional-rhv_{context}""] == Additional {rh-virtualization-first} configuration parameters Additional {rh-virtualization} configuration parameters are described in the following table: [id=""additional-virt-parameters-for-clusters_{context}""] .Additional {rh-virtualization-first} parameters for clusters [cols="".^2,.^3a,.^3a"",options=""header""] |==== |Parameter|Description|Values |`platform.ovirt.ovirt_cluster_id` |Required. The Cluster where the VMs will be created. |String. For example: `68833f9f-e89c-4891-b768-e2ba0815b76b` |`platform.ovirt.ovirt_storage_domain_id` |Required. The Storage Domain ID where the VM disks will be created. |String. For example: `ed7b0f4e-0e96-492a-8fff-279213ee1468` |`platform.ovirt.ovirt_network_name` |Required. The network name where the VM nics will be created. |String. For example: `ocpcluster` |`platform.ovirt.vnicProfileID` |Required. The vNIC profile ID of the VM network interfaces. This can be inferred if the cluster network has a single profile. |String. For example: `3fa86930-0be5-4052-b667-b79f0a729692` |`platform.ovirt.api_vip` |Required. An IP address on the machine network that will be assigned to the API virtual IP (VIP). You can access the OpenShift API at this endpoint. |String. Example: `10.46.8.230` |`platform.ovirt.ingress_vip` |Required. An IP address on the machine network that will be assigned to the Ingress virtual IP (VIP). |String. Example: `10.46.8.232` |`platform.ovirt.affinityGroups` |Optional. A list of affinity groups to create during the installation process. |List of objects. |`platform.ovirt.affinityGroups.description` |Required if you include `platform.ovirt.affinityGroups`. A description of the affinity group. |String. Example: `AffinityGroup for spreading each compute machine to a different host` |`platform.ovirt.affinityGroups.enforcing` |Required if you include `platform.ovirt.affinityGroups`. When set to `true`, {rh-virtualization} does not provision any machines if not enough hardware nodes are available. When set to `false`, {rh-virtualization} does provision machines even if not enough hardware nodes are available, resulting in multiple virtual machines being hosted on the same physical machine. |String. Example: `true` |`platform.ovirt.affinityGroups.name` |Required if you include `platform.ovirt.affinityGroups`. The name of the affinity group. |String. Example: `compute` |`platform.ovirt.affinityGroups.priority` |Required if you include `platform.ovirt.affinityGroups`. The priority given to an affinity group when `platform.ovirt.affinityGroups.enforcing = false`. {rh-virtualization} applies affinity groups in the order of priority, where a greater number takes precedence over a lesser one. If multiple affinity groups have the same priority, the order in which they are applied is not guaranteed. |Integer. Example: `3` |==== [id=""installation-configuration-parameters-additional-machine_{context}""] == Additional {rh-virtualization} parameters for machine pools Additional {rh-virtualization} configuration parameters for machine pools are described in the following table: .Additional {rh-virtualization} parameters for machine pools [cols="".^2,.^3a,.^3a"",options=""header""] |==== |Parameter|Description|Values |`.platform.ovirt.cpu` |Optional. Defines the CPU of the VM. |Object |`.platform.ovirt.cpu.cores` |Required if you use `.platform.ovirt.cpu`. The number of cores. Total virtual CPUs (vCPUs) is cores * sockets. |Integer |`.platform.ovirt.cpu.sockets` |Required if you use `.platform.ovirt.cpu`. The number of sockets per core. Total virtual CPUs (vCPUs) is cores * sockets. |Integer |`.platform.ovirt.memoryMB` |Optional. Memory of the VM in MiB. |Integer |`.platform.ovirt.instanceTypeID` |Optional. An instance type UUID, such as `00000009-0009-0009-0009-0000000000f1`, which you can get from the `https:///ovirt-engine/api/instancetypes` endpoint. [WARNING] ==== The `instance_type_id` field is deprecated and will be removed in a future release. ==== |String of UUID |`.platform.ovirt.osDisk` |Optional. Defines the first and bootable disk of the VM. |String |`.platform.ovirt.osDisk.sizeGB` |Required if you use `.platform.ovirt.osDisk`. Size of the disk in GiB. |Number |`.platform.ovirt.vmType` |Optional. The VM workload type, such as `high-performance`, `server`, or `desktop`. By default, master nodes use `high-performance`, and worker nodes use `server`. For details, see link:https://access.redhat.com/documentation/en-us/red_hat_virtualization/4.4/html-single/virtual_machine_management_guide/index#Virtual_Machine_General_settings_explained[Explanation of Settings in the New Virtual Machine and Edit Virtual Machine Windows] and link:https://access.redhat.com/documentation/en-us/red_hat_virtualization/4.4/html-single/virtual_machine_management_guide/index#Configuring_High_Performance_Virtual_Machines_Templates_and_Pools[Configuring High Performance Virtual Machines, Templates, and Pools] in the _Virtual Machine Management Guide_. [NOTE] ==== `high_performance` improves performance on the VM, but there are limitations. For example, you cannot access the VM with a graphical console. For more information, see link:https://access.redhat.com/documentation/en-us/red_hat_virtualization/4.4/html-single/virtual_machine_management_guide/index#Configuring_High_Performance_Virtual_Machines_Templates_and_Pools[Configuring High Performance Virtual Machines, Templates, and Pools] in the _Virtual Machine Management Guide_. ==== |String |`.platform.ovirt.affinityGroupsNames` |Optional. A list of affinity group names that should be applied to the virtual machines. The affinity groups must exist in {rh-virtualization}, or be created during installation as described in _Additional {rh-virtualization} parameters for clusters_ in this topic. This entry can be empty. // xref:../../installing/installing_rhv/installing-rhv-customizations.adoc#additional-virt-parameters-for-clusters[Additional {rh-virtualization} parameters for clusters]. This entry can be empty. //xref:../../additional-virt-parameters-for-clusters[Additional {rh-virtualization} parameters for clusters]. This entry can be empty. .Example with two affinity groups This example defines two affinity groups, named `compute` and `clusterWideNonEnforcing`: [source,yaml] ---- : platform: ovirt: affinityGroupNames: - compute - clusterWideNonEnforcing ---- This example defines no affinity groups: [source,yaml] ---- : platform: ovirt: affinityGroupNames: [] ---- |String |`.platform.ovirt.AutoPinningPolicy` | Optional. AutoPinningPolicy defines the policy to automatically set the CPU and NUMA settings, including pinning to the host for the instance. When the field is omitted, the default is `none`. Supported values: `none`, `resize_and_pin`. For more information, see link:https://access.redhat.com/documentation/en-us/red_hat_virtualization/4.4/html-single/virtual_machine_management_guide/index#Setting_NUMA_Nodes[Setting NUMA Nodes] in the _Virtual Machine Management Guide_. |String |`.platform.ovirt.hugepages` |Optional. Hugepages is the size in KiB for defining hugepages in a VM. Supported values: `2048` or `1048576`. For more information, see link:https://access.redhat.com/documentation/en-us/red_hat_virtualization/4.4/html-single/virtual_machine_management_guide/index#Configuring_Huge_Pages[Configuring Huge Pages] in the _Virtual Machine Management Guide_. |Integer |==== [NOTE] ==== You can replace `` with `controlPlane` or `compute`. ==== endif::rhv[] ifdef::vsphere,vmc[] [id=""installation-configuration-parameters-additional-vsphere_{context}""] == Additional VMware vSphere configuration parameters Additional VMware vSphere configuration parameters are described in the following table: .Additional VMware vSphere cluster parameters [cols="".^2,.^3a,.^3a"",options=""header""] |==== |Parameter|Description|Values |`platform.vsphere.vCenter` |The fully-qualified hostname or IP address of the vCenter server. |String |`platform.vsphere.username` |The user name to use to connect to the vCenter instance with. This user must have at least the roles and privileges that are required for link:https://vmware.github.io/vsphere-storage-for-kubernetes/documentation/vcp-roles.html[static or dynamic persistent volume provisioning] in vSphere. |String |`platform.vsphere.password` |The password for the vCenter user name. |String |`platform.vsphere.datacenter` |The name of the datacenter to use in the vCenter instance. |String |`platform.vsphere.defaultDatastore` |The name of the default datastore to use for provisioning volumes. |String |`platform.vsphere.folder` |_Optional_. The absolute path of an existing folder where the installation program creates the virtual machines. If you do not provide this value, the installation program creates a folder that is named with the infrastructure ID in the datacenter virtual machine folder. |String, for example, `//vm//`. |`platform.vsphere.network` |The network in the vCenter instance that contains the virtual IP addresses and DNS records that you configured. |String |`platform.vsphere.cluster` |The vCenter cluster to install the {product-title} cluster in. |String |`platform.vsphere.apiVIP` |The virtual IP (VIP) address that you configured for control plane API access. |An IP address, for example `128.0.0.1`. |`platform.vsphere.ingressVIP` |The virtual IP (VIP) address that you configured for cluster ingress. |An IP address, for example `128.0.0.1`. |==== [id=""installation-configuration-parameters-optional-vsphere_{context}""] == Optional VMware vSphere machine pool configuration parameters Optional VMware vSphere machine pool configuration parameters are described in the following table: .Optional VMware vSphere machine pool parameters [cols="".^2,.^3a,.^3a"",options=""header""] |==== |Parameter|Description|Values |`platform.vsphere.clusterOSImage` |The location from which the installer downloads the {op-system} image. You must set this parameter to perform an installation in a restricted network. |An HTTP or HTTPS URL, optionally with a SHA-256 checksum. For example, `\\https://mirror.openshift.com/images/rhcos--vmware..ova`. |`platform.vsphere.osDisk.diskSizeGB` |The size of the disk in gigabytes. |Integer |`platform.vsphere.cpus` |The total number of virtual processor cores to assign a virtual machine. |Integer |`platform.vsphere.coresPerSocket` |The number of cores per socket in a virtual machine. The number of virtual sockets on the virtual machine is `platform.vsphere.cpus`/`platform.vsphere.coresPerSocket`. The default value is `1` |Integer |`platform.vsphere.memoryMB` |The size of a virtual machine's memory in megabytes. |Integer |`platform.vsphere.diskType` |The disk provisioning method. This value defaults to the vSphere default storage policy if not set. |Valid values are `thin`, `thick`, or `eagerZeroedThick`. |==== endif::vsphere,vmc[] ifdef::ash-default[] [id=""installation-configuration-parameters-additional-azure-stack-hub_{context}""] == Additional Azure Stack Hub configuration parameters Additional Azure configuration parameters are described in the following table: .Additional Azure Stack Hub parameters [cols="".^2,.^3a,.^3a"",options=""header""] |==== |Parameter|Description|Values |`platform.azure.armEndpoint` |The URL of the Azure Resource Manager endpoint that your Azure Stack Hub operator provides. |String |`platform.azure.baseDomainResourceGroupName` |The name of the resource group that contains the DNS zone for your base domain. |String, for example `production_cluster`. |`platform.azure.region` |The name of your Azure Stack Hub local region. |String |`platform.azure.resourceGroupName` | The name of an already existing resource group to install your cluster to. If undefined, a new resource group is created for the cluster. |String, for example `existing_resource_group`. |`platform.azure.outboundType` |The outbound routing strategy used to connect your cluster to the internet. If you are using user-defined routing, you must have pre-existing networking available where the outbound routing has already been configured prior to installing a cluster. The installation program is not responsible for configuring user-defined routing. |`LoadBalancer` or `UserDefinedRouting`. The default is `LoadBalancer`. |`platform.azure.cloudName` |The name of the Azure cloud environment that is used to configure the Azure SDK with the appropriate Azure API endpoints. |`AzureStackCloud` |`clusterOSImage` |The URL of a storage blob in the Azure Stack environment that contains an {op-system} VHD. |String, for example, \\https://vhdsa.blob.example.example.com/vhd/rhcos-410.84.202112040202-0-azurestack.x86_64.vhd |==== endif::ash-default[] ifdef::bare[] :!bare: endif::bare[] ifeval::[""{context}"" == ""installing-aws-customizations""] :!aws: endif::[] ifeval::[""{context}"" == ""installing-aws-government-region""] :!aws: endif::[] ifeval::[""{context}"" == ""installing-aws-secret-region""] :!aws: endif::[] ifeval::[""{context}"" == ""installing-aws-network-customizations""] :!aws: endif::[] ifeval::[""{context}"" == ""installing-aws-private""] :!aws: endif::[] ifeval::[""{context}"" == ""installing-aws-vpc""] :!aws: endif::[] ifeval::[""{context}"" == ""installing-restricted-networks-aws-installer-provisioned""] :!aws: endif::[] ifeval::[""{context}"" == ""installing-azure-customizations""] :!azure: endif::[] ifeval::[""{context}"" == ""installing-azure-government-region""] :!azure: endif::[] ifeval::[""{context}"" == ""installing-azure-network-customizations""] :!azure: endif::[] ifeval::[""{context}"" == ""installing-azure-private""] :!azure: endif::[] ifeval::[""{context}"" == ""installing-azure-vnet""] :!azure: endif::[] ifeval::[""{context}"" == ""installing-gcp-customizations""] :!gcp: endif::[] ifeval::[""{context}"" == ""installing-gcp-private""] :!gcp: endif::[] ifeval::[""{context}"" == ""installing-gcp-network-customizations""] :!gcp: endif::[] ifeval::[""{context}"" == ""installing-gcp-vpc""] :!gcp: endif::[] ifeval::[""{context}"" == ""installing-restricted-networks-gcp-installer-provisioned""] :!gcp: endif::[] ifeval::[""{context}"" == ""installing-aws-customizations""] :!aws: endif::[] ifeval::[""{context}"" == ""installing-ibm-cloud-customizations""] :!ibm-cloud: endif::[] ifeval::[""{context}"" == ""installing-ibm-cloud-network-customizations""] :!ibm-cloud: endif::[] ifeval::[""{context}"" == ""installing-openstack-installer-custom""] :!osp: :!osp-custom: endif::[] ifeval::[""{context}"" == ""installing-openstack-installer-kuryr""] :!osp: :!osp-kuryr: endif::[] ifeval::[""{context}"" == ""installing-openstack-user""] :!osp: :!osp-custom: endif::[] ifeval::[""{context}"" == ""installing-openstack-user-kuryr""] :!osp: :!osp-kuryr: endif::[] ifeval::[""{context}"" == ""installing-openstack-user-sr-iov""] :!osp: :!osp-custom: endif::[] ifeval::[""{context}"" == ""installing-openstack-user-sr-iov-kuryr""] :!osp: :!osp-kuryr: endif::[] ifeval::[""{context}"" == ""installing-rhv-customizations""] :!rhv: endif::[] ifeval::[""{context}"" == ""installing-vsphere-installer-provisioned-customizations""] :!vsphere: endif::[] ifeval::[""{context}"" == ""installing-vsphere-installer-provisioned-network-customizations""] :!vsphere: endif::[] ifeval::[""{context}"" == ""installing-vmc-customizations""] :!vmc: endif::[] ifeval::[""{context}"" == ""installing-vmc-network-customizations""] :!vmc: endif::[] ifeval::[""{context}"" == ""installing-restricted-networks-vmc""] :!vmc: endif::[] ifeval::[""{context}"" == ""installing-openstack-installer-restricted""] :!osp: :!osp-custom: endif::[] ifeval::[""{context}"" == ""installing-restricted-networks-installer-provisioned-vsphere""] :!vsphere: endif::[] ifeval::[""{context}"" == ""installing-ibm-z""] :!ibm-z: endif::[] ifeval::[""{context}"" == ""installing-ibm-z-kvm""] :!ibm-z: endif::[] ifeval::[""{context}"" == ""installing-restricted-networks-ibm-z""] :!ibm-z: endif::[] ifeval::[""{context}"" == ""installing-restricted-networks-ibm-z-kvm""] :!ibm-z: endif::[] ifeval::[""{context}"" == ""installing-ibm-power""] :!ibm-power: endif::[] ifeval::[""{context}"" == ""installing-restricted-networks-ibm-power""] :!ibm-power: endif::[] ifeval::[""{context}"" == ""installing-azure-stack-hub-default""] :!ash-default: endif::[] ",16381,True,2946.7025599981016,median "------------------------------------------------------------------------------ -- -- -- GNU ADA RUN-TIME LIBRARY (GNARL) COMPONENTS -- -- -- -- S Y S T E M . I N T E R R U P T S -- -- -- -- B o d y -- -- -- -- $Revision$ -- -- -- Copyright (C) 1991-2001 Free Software Foundation, Inc. -- -- -- -- GNARL is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNARL is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNARL; see file COPYING. If not, write -- -- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, -- -- MA 02111-1307, USA. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- -- -- -- GNARL was developed by the GNARL team at Florida State University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- Invariants: -- All user-handleable signals are masked at all times in all -- tasks/threads except possibly for the Interrupt_Manager task. -- When a user task wants to have the effect of masking/unmasking an -- signal, it must call Block_Interrupt/Unblock_Interrupt, which -- will have the effect of unmasking/masking the signal in the -- Interrupt_Manager task. These comments do not apply to vectored -- hardware interrupts, which may be masked or unmasked using routined -- interfaced to the relevant VxWorks system calls. -- Note : Direct calls to sigaction, sigprocmask, pthread_sigsetmask or any -- other low-level interface that changes the signal action or -- signal mask needs careful consideration. -- One may achieve the effect of system calls first masking RTS blocked -- (by calling Block_Interrupt) for the signal under consideration. -- This will make all the tasks in RTS blocked for the signal. -- Once we associate a Signal_Server_Task with an signal, the task never -- goes away, and we never remove the association. On the other hand, it -- is more convenient to terminate an associated Interrupt_Server_Task -- for a vectored hardware interrupt (since we use a binary semaphore -- for synchronization with the umbrella handler). -- There is no more than one signal per Signal_Server_Task and no more than -- one Signal_Server_Task per signal. The same relation holds for hardware -- interrupts and Interrupt_Server_Task's at any given time. That is, -- only one non-terminated Interrupt_Server_Task exists for a give -- interrupt at any time. -- Within this package, the lock L is used to protect the various status -- tables. If there is a Server_Task associated with a signal or interrupt, -- we use the per-task lock of the Server_Task instead so that we protect the -- status between Interrupt_Manager and Server_Task. Protection among -- service requests are ensured via user calls to the Interrupt_Manager -- entries. -- This is the VxWorks version of this package, supporting both signals -- and vectored hardware interrupts. with Unchecked_Conversion; with System.OS_Interface; use System.OS_Interface; with System.VxWorks; with Interfaces.VxWorks; with Ada.Task_Identification; -- used for Task_ID type with Ada.Exceptions; -- used for Raise_Exception with System.Task_Primitives; -- used for RTS_Lock -- Self with System.Interrupt_Management; -- used for Reserve -- Interrupt_ID -- Interrupt_Mask -- Abort_Task_Interrupt with System.Interrupt_Management.Operations; -- used for Thread_Block_Interrupt -- Thread_Unblock_Interrupt -- Install_Default_Action -- Install_Ignore_Action -- Copy_Interrupt_Mask -- Set_Interrupt_Mask -- Empty_Interrupt_Mask -- Fill_Interrupt_Mask -- Add_To_Interrupt_Mask -- Delete_From_Interrupt_Mask -- Interrupt_Wait -- Interrupt_Self_Process -- Get_Interrupt_Mask -- Set_Interrupt_Mask -- IS_Member -- Environment_Mask -- All_Tasks_Mask pragma Elaborate_All (System.Interrupt_Management.Operations); with System.Error_Reporting; -- used for Shutdown with System.Task_Primitives.Operations; -- used for Write_Lock -- Unlock -- Abort -- Wakeup_Task -- Sleep -- Initialize_Lock with System.Task_Primitives.Interrupt_Operations; -- used for Set_Interrupt_ID with System.Storage_Elements; -- used for To_Address -- To_Integer -- Integer_Address with System.Tasking; -- used for Task_ID -- Task_Entry_Index -- Null_Task -- Self -- Interrupt_Manager_ID with System.Tasking.Utilities; -- used for Make_Independent with System.Tasking.Rendezvous; -- used for Call_Simple pragma Elaborate_All (System.Tasking.Rendezvous); with System.Tasking.Initialization; -- used for Defer_Abort -- Undefer_Abort package body System.Interrupts is use Tasking; use System.Error_Reporting; use Ada.Exceptions; package PRI renames System.Task_Primitives; package POP renames System.Task_Primitives.Operations; package PIO renames System.Task_Primitives.Interrupt_Operations; package IMNG renames System.Interrupt_Management; package IMOP renames System.Interrupt_Management.Operations; function To_Ada is new Unchecked_Conversion (System.Tasking.Task_ID, Ada.Task_Identification.Task_Id); function To_System is new Unchecked_Conversion (Ada.Task_Identification.Task_Id, Task_ID); ----------------- -- Local Tasks -- ----------------- -- WARNING: System.Tasking.Utilities performs calls to this task -- with low-level constructs. Do not change this spec without synchro- -- nizing it. task Interrupt_Manager is entry Initialize (Mask : IMNG.Interrupt_Mask); entry Attach_Handler (New_Handler : Parameterless_Handler; Interrupt : Interrupt_ID; Static : Boolean; Restoration : Boolean := False); entry Exchange_Handler (Old_Handler : out Parameterless_Handler; New_Handler : Parameterless_Handler; Interrupt : Interrupt_ID; Static : Boolean); entry Detach_Handler (Interrupt : Interrupt_ID; Static : Boolean); entry Bind_Interrupt_To_Entry (T : Task_ID; E : Task_Entry_Index; Interrupt : Interrupt_ID); entry Detach_Interrupt_Entries (T : Task_ID); pragma Interrupt_Priority (System.Interrupt_Priority'First); end Interrupt_Manager; task type Signal_Server_Task (Interrupt : Interrupt_ID) is pragma Interrupt_Priority (System.Interrupt_Priority'First + 1); end Signal_Server_Task; -- Server task for signal handling type Signal_Task_Access is access Signal_Server_Task; task type Interrupt_Server_Task (Interrupt : Interrupt_ID; Int_Sema : SEM_ID) is -- Server task for vectored hardware interrupt handling pragma Interrupt_Priority (System.Interrupt_Priority'First + 2); end Interrupt_Server_Task; type Interrupt_Task_Access is access Interrupt_Server_Task; ------------------------------- -- Local Types and Variables -- ------------------------------- type Entry_Assoc is record T : Task_ID; E : Task_Entry_Index; end record; type Handler_Assoc is record H : Parameterless_Handler; Static : Boolean; -- Indicates static binding; end record; User_Handler : array (Interrupt_ID) of Handler_Assoc := (others => (null, Static => False)); pragma Volatile_Components (User_Handler); -- Holds the protected procedure handler (if any) and its Static -- information for each interrupt or signal. A handler is static -- iff it is specified through the pragma Attach_Handler. User_Entry : array (Interrupt_ID) of Entry_Assoc := (others => (T => Null_Task, E => Null_Task_Entry)); pragma Volatile_Components (User_Entry); -- Holds the task and entry index (if any) for each interrupt / signal -- Type and Head, Tail of the list containing Registered Interrupt -- Handlers. These definitions are used to register the handlers -- specified by the pragma Interrupt_Handler. type Registered_Handler; type R_Link is access all Registered_Handler; type Registered_Handler is record H : System.Address := System.Null_Address; Next : R_Link := null; end record; Registered_Handler_Head : R_Link := null; Registered_Handler_Tail : R_Link := null; Server_ID : array (Interrupt_ID) of System.Tasking.Task_ID := (others => System.Tasking.Null_Task); pragma Atomic_Components (Server_ID); -- Holds the Task_ID of the Server_Task for each interrupt / signal. -- Task_ID is needed to accomplish locking per interrupt base. Also -- is needed to determine whether to create a new Server_Task. Semaphore_ID_Map : array (Interrupt_ID range 0 .. System.VxWorks.Num_HW_Interrupts) of SEM_ID := (others => 0); -- Array of binary semaphores associated with vectored interrupts -- Note that the last bound should be Max_HW_Interrupt, but this will raise -- Storage_Error if Num_HW_Interrupts is null, so use an extra 4 bytes -- instead. Signal_Access_Hold : Signal_Task_Access; -- Variable for allocating a Signal_Server_Task Interrupt_Access_Hold : Interrupt_Task_Access; -- Variable for allocating an Interrupt_Server_Task L : aliased PRI.RTS_Lock; -- L protects the contents of the above tables for interrupts / signals -- for which Server_ID (I) = Null_Task. -- -- If Server_ID (I) /= Null_Task then protection is via the -- per-task (TCB) lock of Server_ID (I). -- -- For deadlock prevention, L should not be locked after -- any other lock is held, hence we use PO_Level which is the highest -- lock level for error checking. Task_Lock : array (Interrupt_ID) of Boolean := (others => False); -- Booleans indicating whether the per task lock is used Default_Handler : array (HW_Interrupt) of Interfaces.VxWorks.VOIDFUNCPTR; -- Vectored interrupt handlers installed prior to program startup. -- These are saved only when the umbrella handler is installed for -- a given interrupt number. ----------------------- -- Local Subprograms -- ----------------------- procedure Check_Reserved_Interrupt (Interrupt : Interrupt_ID); -- Check if Id is a reserved interrupt, and if so raise Program_Error -- with an appropriate message, otherwise return. procedure Finalize_Interrupt_Servers; -- Unbind the handlers for hardware interrupt server tasks at program -- termination. procedure Lock_Interrupt (Self_ID : Task_ID; Interrupt : Interrupt_ID); -- Protect the tables using L or the per-task lock. Set the Boolean -- value Task_Lock if the lock is made using per-task lock. -- This information is needed so that Unlock_Interrupt -- performs unlocking on the same lock. The situation we are preventing -- is, for example, when Attach_Handler is called for the first time -- we lock L and create an Server_Task. For a matching unlocking, if we -- rely on the fact that there is a Server_Task, we will unlock the -- per-task lock. procedure Unlock_Interrupt (Self_ID : Task_ID; Interrupt : Interrupt_ID); -- Unlock interrupt previously locked by Lock_Interrupt function Is_Registered (Handler : Parameterless_Handler) return Boolean; -- Needs comment ??? procedure Notify_Interrupt (Param : System.Address); -- Umbrella handler for vectored interrupts (not signals) procedure Install_Default_Action (Interrupt : HW_Interrupt); -- Restore a handler that was in place prior to program execution procedure Install_Umbrella_Handler (Interrupt : HW_Interrupt; Handler : Interfaces.VxWorks.VOIDFUNCPTR); -- Install the runtime umbrella handler for a vectored hardware -- interrupt function To_Signal (S : Interrupt_ID) return IMNG.Interrupt_ID; -- Convert interrupt ID to signal number. procedure Unimplemented (Feature : String); pragma No_Return (Unimplemented); -- Used to mark a call to an unimplemented function. Raises Program_Error -- with an appropriate message noting that Feature is unimplemented. -------------------- -- Attach_Handler -- -------------------- -- Calling this procedure with New_Handler = null and Static = True -- means we want to detach the current handler regardless of the -- previous handler's binding status (ie. do not care if it is a -- dynamic or static handler). -- This option is needed so that during the finalization of a PO, we -- can detach handlers attached through pragma Attach_Handler. procedure Attach_Handler (New_Handler : Parameterless_Handler; Interrupt : Interrupt_ID; Static : Boolean := False) is begin Check_Reserved_Interrupt (Interrupt); Interrupt_Manager.Attach_Handler (New_Handler, Interrupt, Static); end Attach_Handler; ----------------------------- -- Bind_Interrupt_To_Entry -- ----------------------------- -- This procedure raises a Program_Error if it tries to -- bind an interrupt to which an Entry or a Procedure is -- already bound. procedure Bind_Interrupt_To_Entry (T : Task_ID; E : Task_Entry_Index; Int_Ref : System.Address) is Interrupt : constant Interrupt_ID := Interrupt_ID (Storage_Elements.To_Integer (Int_Ref)); begin Check_Reserved_Interrupt (Interrupt); Interrupt_Manager.Bind_Interrupt_To_Entry (T, E, Interrupt); end Bind_Interrupt_To_Entry; --------------------- -- Block_Interrupt -- --------------------- procedure Block_Interrupt (Interrupt : Interrupt_ID) is begin Unimplemented (""Block_Interrupt""); end Block_Interrupt; ------------------------------ -- Check_Reserved_Interrupt -- ------------------------------ procedure Check_Reserved_Interrupt (Interrupt : Interrupt_ID) is begin if Is_Reserved (Interrupt) then Raise_Exception (Program_Error'Identity, ""Interrupt"" & Interrupt_ID'Image (Interrupt) & "" is reserved""); else return; end if; end Check_Reserved_Interrupt; --------------------- -- Current_Handler -- --------------------- function Current_Handler (Interrupt : Interrupt_ID) return Parameterless_Handler is begin Check_Reserved_Interrupt (Interrupt); -- ??? Since Parameterless_Handler is not Atomic, the -- current implementation is wrong. We need a new service in -- Interrupt_Manager to ensure atomicity. return User_Handler (Interrupt).H; end Current_Handler; -------------------- -- Detach_Handler -- -------------------- -- Calling this procedure with Static = True means we want to Detach the -- current handler regardless of the previous handler's binding status -- (i.e. do not care if it is a dynamic or static handler). -- This option is needed so that during the finalization of a PO, we can -- detach handlers attached through pragma Attach_Handler. procedure Detach_Handler (Interrupt : Interrupt_ID; Static : Boolean := False) is begin Check_Reserved_Interrupt (Interrupt); Interrupt_Manager.Detach_Handler (Interrupt, Static); end Detach_Handler; ------------------------------ -- Detach_Interrupt_Entries -- ------------------------------ procedure Detach_Interrupt_Entries (T : Task_ID) is begin Interrupt_Manager.Detach_Interrupt_Entries (T); end Detach_Interrupt_Entries; ---------------------- -- Exchange_Handler -- ---------------------- -- Calling this procedure with New_Handler = null and Static = True -- means we want to detach the current handler regardless of the -- previous handler's binding status (ie. do not care if it is a -- dynamic or static handler). -- This option is needed so that during the finalization of a PO, we -- can detach handlers attached through pragma Attach_Handler. procedure Exchange_Handler (Old_Handler : out Parameterless_Handler; New_Handler : Parameterless_Handler; Interrupt : Interrupt_ID; Static : Boolean := False) is begin Check_Reserved_Interrupt (Interrupt); Interrupt_Manager.Exchange_Handler (Old_Handler, New_Handler, Interrupt, Static); end Exchange_Handler; -------------- -- Finalize -- -------------- procedure Finalize (Object : in out Static_Interrupt_Protection) is begin -- ??? loop to be executed only when we're not doing library level -- finalization, since in this case all interrupt / signal tasks are -- gone. if not Interrupt_Manager'Terminated then for N in reverse Object.Previous_Handlers'Range loop Interrupt_Manager.Attach_Handler (New_Handler => Object.Previous_Handlers (N).Handler, Interrupt => Object.Previous_Handlers (N).Interrupt, Static => Object.Previous_Handlers (N).Static, Restoration => True); end loop; end if; Tasking.Protected_Objects.Entries.Finalize (Tasking.Protected_Objects.Entries.Protection_Entries (Object)); end Finalize; -------------------------------- -- Finalize_Interrupt_Servers -- -------------------------------- -- Restore default handlers for interrupt servers. Signal servers -- restore the default handlers when they're aborted. This is called -- by the Interrupt_Manager task when it receives the abort signal -- during program finalization. procedure Finalize_Interrupt_Servers is begin if HW_Interrupt'Last >= 0 then for Int in HW_Interrupt loop if Server_ID (Interrupt_ID (Int)) /= null and then not Ada.Task_Identification.Is_Terminated (To_Ada (Server_ID (Interrupt_ID (Int)))) then Interrupt_Manager.Attach_Handler (New_Handler => null, Interrupt => Interrupt_ID (Int), Static => True, Restoration => True); end if; end loop; end if; end Finalize_Interrupt_Servers; ------------------------------------- -- Has_Interrupt_Or_Attach_Handler -- ------------------------------------- function Has_Interrupt_Or_Attach_Handler (Object : access Dynamic_Interrupt_Protection) return Boolean is begin return True; end Has_Interrupt_Or_Attach_Handler; function Has_Interrupt_Or_Attach_Handler (Object : access Static_Interrupt_Protection) return Boolean is begin return True; end Has_Interrupt_Or_Attach_Handler; ---------------------- -- Ignore_Interrupt -- ---------------------- procedure Ignore_Interrupt (Interrupt : Interrupt_ID) is begin Unimplemented (""Ignore_Interrupt""); end Ignore_Interrupt; ---------------------------- -- Install_Default_Action -- ---------------------------- procedure Install_Default_Action (Interrupt : HW_Interrupt) is begin -- Restore original interrupt handler Interfaces.VxWorks.intVecSet (Interfaces.VxWorks.INUM_TO_IVEC (Integer (Interrupt)), Default_Handler (Interrupt)); Default_Handler (Interrupt) := null; end Install_Default_Action; ---------------------- -- Install_Handlers -- ---------------------- procedure Install_Handlers (Object : access Static_Interrupt_Protection; New_Handlers : New_Handler_Array) is begin for N in New_Handlers'Range loop -- We need a lock around this ??? Object.Previous_Handlers (N).Interrupt := New_Handlers (N).Interrupt; Object.Previous_Handlers (N).Static := User_Handler (New_Handlers (N).Interrupt).Static; -- We call Exchange_Handler and not directly Interrupt_Manager. -- Exchange_Handler so we get the Is_Reserved check. Exchange_Handler (Old_Handler => Object.Previous_Handlers (N).Handler, New_Handler => New_Handlers (N).Handler, Interrupt => New_Handlers (N).Interrupt, Static => True); end loop; end Install_Handlers; ------------------------------ -- Install_Umbrella_Handler -- ------------------------------ procedure Install_Umbrella_Handler (Interrupt : HW_Interrupt; Handler : Interfaces.VxWorks.VOIDFUNCPTR) is use Interfaces.VxWorks; Vec : constant Interrupt_Vector := INUM_TO_IVEC (Interfaces.VxWorks.int (Interrupt)); Old_Handler : constant VOIDFUNCPTR := intVecGet (INUM_TO_IVEC (Interfaces.VxWorks.int (Interrupt))); Stat : Interfaces.VxWorks.STATUS; begin -- Only install umbrella handler when no Ada handler has already been -- installed. Note that the interrupt number is passed as a parameter -- when an interrupt occurs, so the umbrella handler has a different -- wrapper generated by intConnect for each interrupt number. if Default_Handler (Interrupt) = null then Stat := intConnect (Vec, VOIDFUNCPTR (Handler), System.Address (Interrupt)); Default_Handler (Interrupt) := Old_Handler; end if; end Install_Umbrella_Handler; ---------------- -- Is_Blocked -- ---------------- function Is_Blocked (Interrupt : Interrupt_ID) return Boolean is begin Unimplemented (""Is_Blocked""); return False; end Is_Blocked; ----------------------- -- Is_Entry_Attached -- ----------------------- function Is_Entry_Attached (Interrupt : Interrupt_ID) return Boolean is begin Check_Reserved_Interrupt (Interrupt); return User_Entry (Interrupt).T /= Null_Task; end Is_Entry_Attached; ------------------------- -- Is_Handler_Attached -- ------------------------- function Is_Handler_Attached (Interrupt : Interrupt_ID) return Boolean is begin Check_Reserved_Interrupt (Interrupt); return User_Handler (Interrupt).H /= null; end Is_Handler_Attached; ---------------- -- Is_Ignored -- ---------------- function Is_Ignored (Interrupt : Interrupt_ID) return Boolean is begin Unimplemented (""Is_Ignored""); return False; end Is_Ignored; ------------------- -- Is_Registered -- ------------------- -- See if Handler has been ""pragma""ed using Interrupt_Handler. -- Always consider a null handler as registered. function Is_Registered (Handler : Parameterless_Handler) return Boolean is type Fat_Ptr is record Object_Addr : System.Address; Handler_Addr : System.Address; end record; function To_Fat_Ptr is new Unchecked_Conversion (Parameterless_Handler, Fat_Ptr); Ptr : R_Link; Fat : Fat_Ptr; begin if Handler = null then return True; end if; Fat := To_Fat_Ptr (Handler); Ptr := Registered_Handler_Head; while (Ptr /= null) loop if Ptr.H = Fat.Handler_Addr then return True; end if; Ptr := Ptr.Next; end loop; return False; end Is_Registered; ----------------- -- Is_Reserved -- ----------------- function Is_Reserved (Interrupt : Interrupt_ID) return Boolean is begin if Interrupt < System.VxWorks.Num_HW_Interrupts then return False; else return IMNG.Reserve (To_Signal (Interrupt)); end if; end Is_Reserved; -------------------- -- Lock_Interrupt -- -------------------- -- ????? -- This package has been modified several times. -- Do we still need this fancy locking scheme, now that more operations -- are entries of the interrupt manager task? -- ????? -- More likely, we will need to convert one or more entry calls to -- protected operations, because presently we are violating locking order -- rules by calling a task entry from within the runtime system. procedure Lock_Interrupt (Self_ID : Task_ID; Interrupt : Interrupt_ID) is begin Initialization.Defer_Abort (Self_ID); POP.Write_Lock (L'Access); if Task_Lock (Interrupt) then pragma Assert (Server_ID (Interrupt) /= null, ""Task_Lock is true for null server task""); pragma Assert (not Ada.Task_Identification.Is_Terminated (To_Ada (Server_ID (Interrupt))), ""Attempt to lock per task lock of terminated server: "" & ""Task_Lock => True""); POP.Unlock (L'Access); POP.Write_Lock (Server_ID (Interrupt)); elsif Server_ID (Interrupt) /= Null_Task then pragma Assert (not Ada.Task_Identification.Is_Terminated (To_Ada (Server_ID (Interrupt))), ""Attempt to lock per task lock of terminated server: "" & ""Task_Lock => False""); Task_Lock (Interrupt) := True; POP.Unlock (L'Access); POP.Write_Lock (Server_ID (Interrupt)); end if; end Lock_Interrupt; ------------------------ -- Notify_Interrupt -- ------------------------ -- Umbrella handler for vectored hardware interrupts (as opposed to -- signals and exceptions). As opposed to the signal implementation, -- this handler is only installed in the vector table while there is -- an active association of an Ada handler to the interrupt. -- Otherwise, the handler that existed prior to program startup is -- in the vector table. This ensures that handlers installed by -- the BSP are active unless explicitly replaced in the program text. -- Each Interrupt_Server_Task has an associated binary semaphore -- on which it pends once it's been started. This routine determines -- The appropriate semaphore and and issues a semGive call, waking -- the server task. When a handler is unbound, -- System.Interrupts.Unbind_Handler issues a semFlush, and the -- server task deletes its semaphore and terminates. procedure Notify_Interrupt (Param : System.Address) is Interrupt : Interrupt_ID := Interrupt_ID (Param); Discard_Result : STATUS; begin Discard_Result := semGive (Semaphore_ID_Map (Interrupt)); end Notify_Interrupt; --------------- -- Reference -- --------------- function Reference (Interrupt : Interrupt_ID) return System.Address is begin Check_Reserved_Interrupt (Interrupt); return Storage_Elements.To_Address (Storage_Elements.Integer_Address (Interrupt)); end Reference; -------------------------------- -- Register_Interrupt_Handler -- -------------------------------- procedure Register_Interrupt_Handler (Handler_Addr : System.Address) is New_Node_Ptr : R_Link; begin -- This routine registers a handler as usable for dynamic -- interrupt handler association. Routines attaching and detaching -- handlers dynamically should determine whether the handler is -- registered. Program_Error should be raised if it is not registered. -- Pragma Interrupt_Handler can only appear in a library -- level PO definition and instantiation. Therefore, we do not need -- to implement an unregister operation. Nor do we need to -- protect the queue structure with a lock. pragma Assert (Handler_Addr /= System.Null_Address); New_Node_Ptr := new Registered_Handler; New_Node_Ptr.H := Handler_Addr; if Registered_Handler_Head = null then Registered_Handler_Head := New_Node_Ptr; Registered_Handler_Tail := New_Node_Ptr; else Registered_Handler_Tail.Next := New_Node_Ptr; Registered_Handler_Tail := New_Node_Ptr; end if; end Register_Interrupt_Handler; --------------- -- To_Signal -- --------------- function To_Signal (S : Interrupt_ID) return IMNG.Interrupt_ID is begin return IMNG.Interrupt_ID (S - System.VxWorks.Num_HW_Interrupts); end To_Signal; ----------------------- -- Unblock_Interrupt -- ----------------------- procedure Unblock_Interrupt (Interrupt : Interrupt_ID) is begin Unimplemented (""Unblock_Interrupt""); end Unblock_Interrupt; ------------------ -- Unblocked_By -- ------------------ function Unblocked_By (Interrupt : Interrupt_ID) return System.Tasking.Task_ID is begin Unimplemented (""Unblocked_By""); return Null_Task; end Unblocked_By; ------------------------ -- Unignore_Interrupt -- ------------------------ procedure Unignore_Interrupt (Interrupt : Interrupt_ID) is begin Unimplemented (""Unignore_Interrupt""); end Unignore_Interrupt; ------------------- -- Unimplemented -- ------------------- procedure Unimplemented (Feature : String) is begin Raise_Exception (Program_Error'Identity, Feature & "" not implemented on VxWorks""); end Unimplemented; ---------------------- -- Unlock_Interrupt -- ---------------------- procedure Unlock_Interrupt (Self_ID : Task_ID; Interrupt : Interrupt_ID) is begin if Task_Lock (Interrupt) then pragma Assert (not Ada.Task_Identification.Is_Terminated (To_Ada (Server_ID (Interrupt))), ""Attempt to unlock per task lock of terminated server""); POP.Unlock (Server_ID (Interrupt)); else POP.Unlock (L'Access); end if; Initialization.Undefer_Abort (Self_ID); end Unlock_Interrupt; ----------------------- -- Interrupt_Manager -- ----------------------- task body Interrupt_Manager is --------------------- -- Local Variables -- --------------------- Intwait_Mask : aliased IMNG.Interrupt_Mask; Old_Mask : aliased IMNG.Interrupt_Mask; Self_ID : Task_ID := POP.Self; -------------------- -- Local Routines -- -------------------- procedure Bind_Handler (Interrupt : Interrupt_ID); -- This procedure does not do anything if a signal is blocked. -- Otherwise, we have to interrupt Server_Task for status change through -- a wakeup signal. procedure Unbind_Handler (Interrupt : Interrupt_ID); -- This procedure does not do anything if a signal is blocked. -- Otherwise, we have to interrupt Server_Task for status change -- through an abort signal. -- The following two procedures are labelled Unprotected... in order to -- indicate that Lock/Unlock_Interrupt operations are needed around -- around calls to them. procedure Unprotected_Exchange_Handler (Old_Handler : out Parameterless_Handler; New_Handler : Parameterless_Handler; Interrupt : Interrupt_ID; Static : Boolean; Restoration : Boolean := False); procedure Unprotected_Detach_Handler (Interrupt : Interrupt_ID; Static : Boolean); ------------------ -- Bind_Handler -- ------------------ procedure Bind_Handler (Interrupt : Interrupt_ID) is begin if Interrupt < System.VxWorks.Num_HW_Interrupts then Install_Umbrella_Handler (HW_Interrupt (Interrupt), Notify_Interrupt'Access); else -- Mask this task for the given signal so that all tasks -- are masked for the signal and the actual delivery of the -- signal will be caught using ""sigwait"" by the -- corresponding Server_Task. IMOP.Thread_Block_Interrupt (To_Signal (Interrupt)); -- We have installed a handler or an entry before we called -- this procedure. If the handler task is waiting to be -- awakened, do it here. Otherwise, the signal will be -- discarded. POP.Wakeup (Server_ID (Interrupt), Interrupt_Server_Idle_Sleep); end if; end Bind_Handler; -------------------- -- Unbind_Handler -- -------------------- procedure Unbind_Handler (Interrupt : Interrupt_ID) is S : STATUS; Ret_Interrupt : IMNG.Interrupt_ID; use type IMNG.Interrupt_ID; use type STATUS; begin if Interrupt < System.VxWorks.Num_HW_Interrupts then -- Hardware interrupt Install_Default_Action (HW_Interrupt (Interrupt)); -- Flush server task off semaphore, allowing it to terminate S := semFlush (Semaphore_ID_Map (Interrupt)); pragma Assert (S = 0); else -- Currently, there is a handler or an entry attached and -- the corresponding Server_Task is waiting on ""sigwait."" -- We have to wake up the Server_Task and make it -- wait on a condition variable by sending an -- Abort_Task_Interrupt -- Make sure corresponding Server_Task is out of its own -- sigwait state. POP.Abort_Task (Server_ID (Interrupt)); Ret_Interrupt := IMOP.Interrupt_Wait (Intwait_Mask'Access); pragma Assert (Ret_Interrupt = IMNG.Abort_Task_Interrupt); IMOP.Install_Default_Action (To_Signal (Interrupt)); -- Unmake the Interrupt for this task in order to allow default -- action again. IMOP.Thread_Unblock_Interrupt (To_Signal (Interrupt)); end if; end Unbind_Handler; -------------------------------- -- Unprotected_Detach_Handler -- -------------------------------- procedure Unprotected_Detach_Handler (Interrupt : Interrupt_ID; Static : Boolean) is Old_Handler : Parameterless_Handler; begin if User_Entry (Interrupt).T /= Null_Task then -- If an interrupt entry is installed raise -- Program_Error. (propagate it to the caller). Unlock_Interrupt (Self_ID, Interrupt); Raise_Exception (Program_Error'Identity, ""An interrupt entry is already installed""); end if; -- Note : Static = True will pass the following check. This is the -- case when we want to detach a handler regardless of the static -- status of the Current_Handler. if not Static and then User_Handler (Interrupt).Static then -- Trying to detach a static Interrupt Handler. -- raise Program_Error. Unlock_Interrupt (Self_ID, Interrupt); Raise_Exception (Program_Error'Identity, ""Trying to detach a static Interrupt Handler""); end if; Old_Handler := User_Handler (Interrupt).H; -- The new handler User_Handler (Interrupt).H := null; User_Handler (Interrupt).Static := False; if Old_Handler /= null then Unbind_Handler (Interrupt); end if; end Unprotected_Detach_Handler; ---------------------------------- -- Unprotected_Exchange_Handler -- ---------------------------------- procedure Unprotected_Exchange_Handler (Old_Handler : out Parameterless_Handler; New_Handler : Parameterless_Handler; Interrupt : Interrupt_ID; Static : Boolean; Restoration : Boolean := False) is begin if User_Entry (Interrupt).T /= Null_Task then -- If an interrupt entry is already installed, raise -- Program_Error. (propagate it to the caller). Unlock_Interrupt (Self_ID, Interrupt); Raise_Exception (Program_Error'Identity, ""An interrupt is already installed""); end if; -- Note : A null handler with Static = True will -- pass the following check. This is the case when we want to -- detach a handler regardless of the Static status -- of Current_Handler. -- We don't check anything if Restoration is True, since we -- may be detaching a static handler to restore a dynamic one. if not Restoration and then not Static and then (User_Handler (Interrupt).Static -- Trying to overwrite a static Interrupt Handler with a -- dynamic Handler -- The new handler is not specified as an -- Interrupt Handler by a pragma. or else not Is_Registered (New_Handler)) then Unlock_Interrupt (Self_ID, Interrupt); Raise_Exception (Program_Error'Identity, ""Trying to overwrite a static Interrupt Handler with a "" & ""dynamic Handler""); end if; -- Save the old handler Old_Handler := User_Handler (Interrupt).H; -- The new handler User_Handler (Interrupt).H := New_Handler; if New_Handler = null then -- The null handler means we are detaching the handler. User_Handler (Interrupt).Static := False; else User_Handler (Interrupt).Static := Static; end if; -- Invoke a corresponding Server_Task if not yet created. -- Place Task_ID info in Server_ID array. if New_Handler /= null and then (Server_ID (Interrupt) = Null_Task or else Ada.Task_Identification.Is_Terminated (To_Ada (Server_ID (Interrupt)))) then -- When a new Server_Task is created, it should have its -- signal mask set to the All_Tasks_Mask. IMOP.Set_Interrupt_Mask (IMOP.All_Tasks_Mask'Access, Old_Mask'Access); if Interrupt < System.VxWorks.Num_HW_Interrupts then -- Vectored hardware interrupt Interrupt_Access_Hold := new Interrupt_Server_Task (Interrupt, semBCreate (SEM_Q_FIFO, SEM_EMPTY)); Server_ID (Interrupt) := To_System (Interrupt_Access_Hold.all'Identity); else -- Signal Signal_Access_Hold := new Signal_Server_Task (Interrupt); Server_ID (Interrupt) := To_System (Signal_Access_Hold.all'Identity); end if; IMOP.Set_Interrupt_Mask (Old_Mask'Access); end if; if (New_Handler = null) and then Old_Handler /= null then -- Restore default handler Unbind_Handler (Interrupt); elsif Old_Handler = null then -- Save default handler Bind_Handler (Interrupt); end if; end Unprotected_Exchange_Handler; -- Start of processing for Interrupt_Manager begin -- By making this task independent of any master, when the process -- goes away, the Interrupt_Manager will terminate gracefully. System.Tasking.Utilities.Make_Independent; -- Environment task gets its own interrupt mask, saves it, -- and then masks all signals except the Keep_Unmasked set. -- During rendezvous, the Interrupt_Manager receives the old -- signal mask of the environment task, and sets its own -- signal mask to that value. -- The environment task will call this entry of Interrupt_Manager -- during elaboration of the body of this package. accept Initialize (Mask : IMNG.Interrupt_Mask) do declare The_Mask : aliased IMNG.Interrupt_Mask; begin IMOP.Copy_Interrupt_Mask (The_Mask, Mask); IMOP.Set_Interrupt_Mask (The_Mask'Access); end; end Initialize; -- Note: All tasks in RTS will have all reserved signals -- being masked (except the Interrupt_Manager) and Keep_Unmasked -- signals unmasked when created. -- Abort_Task_Interrupt is one of the signals unmasked -- in all tasks. We mask the signal in this particular task -- so that ""sigwait"" is can catch an explicit -- Abort_Task_Interrupt from a Server_Task. -- This sigwaiting is needed to ensure that a Signal_Server_Task is -- out of its own sigwait state. This extra synchronization is -- necessary to prevent following scenarios: -- 1) Interrupt_Manager sends an Abort_Task_Interrupt to a -- Signal_Server_Task then changes its own signal mask (OS level). -- If a signal (corresponding to the Signal_Server_Task) arrives -- in the meantime, we have the Interrupt_Manager umnasked and -- the Signal_Server_Task waiting on sigwait. -- 2) For unbinding a handler, we install a default action in the -- Interrupt_Manager. POSIX.1c states that the result of using -- ""sigwait"" and ""sigaction"" simultaneously on the same signal -- is undefined. Therefore, we need to be informed from the -- Signal_Server_Task that it is out of its sigwait stage. IMOP.Empty_Interrupt_Mask (Intwait_Mask'Access); IMOP.Add_To_Interrupt_Mask (Intwait_Mask'Access, IMNG.Abort_Task_Interrupt); IMOP.Thread_Block_Interrupt (IMNG.Abort_Task_Interrupt); loop -- A block is needed to absorb Program_Error exception declare Old_Handler : Parameterless_Handler; begin select accept Attach_Handler (New_Handler : Parameterless_Handler; Interrupt : Interrupt_ID; Static : Boolean; Restoration : Boolean := False) do Lock_Interrupt (Self_ID, Interrupt); Unprotected_Exchange_Handler (Old_Handler, New_Handler, Interrupt, Static, Restoration); Unlock_Interrupt (Self_ID, Interrupt); end Attach_Handler; or accept Exchange_Handler (Old_Handler : out Parameterless_Handler; New_Handler : Parameterless_Handler; Interrupt : Interrupt_ID; Static : Boolean) do Lock_Interrupt (Self_ID, Interrupt); Unprotected_Exchange_Handler (Old_Handler, New_Handler, Interrupt, Static); Unlock_Interrupt (Self_ID, Interrupt); end Exchange_Handler; or accept Detach_Handler (Interrupt : Interrupt_ID; Static : Boolean) do Lock_Interrupt (Self_ID, Interrupt); Unprotected_Detach_Handler (Interrupt, Static); Unlock_Interrupt (Self_ID, Interrupt); end Detach_Handler; or accept Bind_Interrupt_To_Entry (T : Task_ID; E : Task_Entry_Index; Interrupt : Interrupt_ID) do Lock_Interrupt (Self_ID, Interrupt); -- If there is a binding already (either a procedure or an -- entry), raise Program_Error (propagate it to the caller). if User_Handler (Interrupt).H /= null or else User_Entry (Interrupt).T /= Null_Task then Unlock_Interrupt (Self_ID, Interrupt); Raise_Exception (Program_Error'Identity, ""A binding for this interrupt is already present""); end if; User_Entry (Interrupt) := Entry_Assoc' (T => T, E => E); -- Indicate the attachment of interrupt entry in the ATCB. -- This is needed so when an interrupt entry task terminates -- the binding can be cleaned. The call to unbinding must be -- make by the task before it terminates. T.Interrupt_Entry := True; -- Invoke a corresponding Server_Task if not yet created. -- Place Task_ID info in Server_ID array. if Server_ID (Interrupt) = Null_Task or else Ada.Task_Identification.Is_Terminated (To_Ada (Server_ID (Interrupt))) then -- When a new Server_Task is created, it should have its -- signal mask set to the All_Tasks_Mask. IMOP.Set_Interrupt_Mask (IMOP.All_Tasks_Mask'Access, Old_Mask'Access); if Interrupt < System.VxWorks.Num_HW_Interrupts then Interrupt_Access_Hold := new Interrupt_Server_Task (Interrupt, semBCreate (SEM_Q_FIFO, SEM_EMPTY)); Server_ID (Interrupt) := To_System (Interrupt_Access_Hold.all'Identity); else Signal_Access_Hold := new Signal_Server_Task (Interrupt); Server_ID (Interrupt) := To_System (Signal_Access_Hold.all'Identity); end if; IMOP.Set_Interrupt_Mask (Old_Mask'Access); end if; Bind_Handler (Interrupt); Unlock_Interrupt (Self_ID, Interrupt); end Bind_Interrupt_To_Entry; or accept Detach_Interrupt_Entries (T : Task_ID) do for Int in Interrupt_ID'Range loop if not Is_Reserved (Int) then Lock_Interrupt (Self_ID, Int); if User_Entry (Int).T = T then User_Entry (Int) := Entry_Assoc' (T => Null_Task, E => Null_Task_Entry); Unbind_Handler (Int); end if; Unlock_Interrupt (Self_ID, Int); end if; end loop; -- Indicate in ATCB that no interrupt entries are attached. T.Interrupt_Entry := False; end Detach_Interrupt_Entries; end select; exception -- If there is a Program_Error we just want to propagate it to -- the caller and do not want to stop this task. when Program_Error => null; when E : others => pragma Assert (Shutdown (""Interrupt_Manager---exception not expected"" & ASCII.LF & Exception_Information (E))); null; end; end loop; pragma Assert (Shutdown (""Interrupt_Manager---should not get here"")); exception when Standard'Abort_Signal => -- Flush interrupt server semaphores, so they can terminate Finalize_Interrupt_Servers; raise; end Interrupt_Manager; ------------------------ -- Signal_Server_Task -- ------------------------ task body Signal_Server_Task is Intwait_Mask : aliased IMNG.Interrupt_Mask; Ret_Interrupt : IMNG.Interrupt_ID; Self_ID : Task_ID := Self; Tmp_Handler : Parameterless_Handler; Tmp_ID : Task_ID; Tmp_Entry_Index : Task_Entry_Index; use type IMNG.Interrupt_ID; begin -- By making this task independent of master, when the process -- goes away, the Server_Task will terminate gracefully. System.Tasking.Utilities.Make_Independent; -- Install default action in system level. IMOP.Install_Default_Action (To_Signal (Interrupt)); -- Note: All tasks in RTS will have all reserved signals -- masked (except the Interrupt_Manager) and Keep_Unmasked -- unmasked when created. -- Abort_Task_Interrupt is one of the signals unmasked -- in all tasks. We mask it in this particular task -- so that ""sigwait"" can catch an explicit -- Abort_Task_Interrupt from the Interrupt_Manager. -- There are two signals that this task catches through -- ""sigwait."" One is the signal it is designated to catch -- in order to execute an user handler or entry. The other is -- Abort_Task_Interrupt. This signal is sent from the -- Interrupt_Manager to inform of status changes (e.g: become Blocked, -- or a handler or entry is to be detached). -- Prepare the mask to be used for sigwait. IMOP.Empty_Interrupt_Mask (Intwait_Mask'Access); IMOP.Add_To_Interrupt_Mask (Intwait_Mask'Access, To_Signal (Interrupt)); IMOP.Add_To_Interrupt_Mask (Intwait_Mask'Access, IMNG.Abort_Task_Interrupt); IMOP.Thread_Block_Interrupt (IMNG.Abort_Task_Interrupt); PIO.Set_Interrupt_ID (To_Signal (Interrupt), Self_ID); loop System.Tasking.Initialization.Defer_Abort (Self_ID); POP.Write_Lock (Self_ID); if User_Handler (Interrupt).H = null and then User_Entry (Interrupt).T = Null_Task then -- No signal binding. If a signal is received, -- Interrupt_Manager will take the default action. Self_ID.Common.State := Interrupt_Server_Blocked_Interrupt_Sleep; POP.Sleep (Self_ID, Interrupt_Server_Idle_Sleep); Self_ID.Common.State := Runnable; else -- A handler or an entry is installed. At this point all tasks -- mask for the signal is masked. Catch it using -- sigwait. -- This task may wake up from sigwait by receiving a signal -- (Abort_Task_Interrupt) from the Interrupt_Manager for unbinding -- a procedure handler or an entry. Or it could be a wake up -- from status change (Unblocked -> Blocked). If that is not -- the case, we should execute the attached procedure or entry. POP.Unlock (Self_ID); Ret_Interrupt := IMOP.Interrupt_Wait (Intwait_Mask'Access); if Ret_Interrupt = IMNG.Abort_Task_Interrupt then -- Inform the Interrupt_Manager of wakeup from above sigwait. POP.Abort_Task (Interrupt_Manager_ID); POP.Write_Lock (Self_ID); else POP.Write_Lock (Self_ID); -- Even though we have received a signal, the status may -- have changed before we got the Self_ID lock above. -- Therefore we make sure a handler or an entry is still -- bound and make appropriate call. -- If there is no call to make we need to regenerate the -- signal in order not to lose it. if User_Handler (Interrupt).H /= null then Tmp_Handler := User_Handler (Interrupt).H; -- RTS calls should not be made with self being locked. POP.Unlock (Self_ID); Tmp_Handler.all; POP.Write_Lock (Self_ID); elsif User_Entry (Interrupt).T /= Null_Task then Tmp_ID := User_Entry (Interrupt).T; Tmp_Entry_Index := User_Entry (Interrupt).E; -- RTS calls should not be made with self being locked. POP.Unlock (Self_ID); System.Tasking.Rendezvous.Call_Simple (Tmp_ID, Tmp_Entry_Index, System.Null_Address); POP.Write_Lock (Self_ID); else -- This is a situation where this task woke up receiving a -- signal and before it got the lock the signal was blocked. -- We do not want to lose the signal so we regenerate it at -- the process level. IMOP.Interrupt_Self_Process (Ret_Interrupt); end if; end if; end if; POP.Unlock (Self_ID); System.Tasking.Initialization.Undefer_Abort (Self_ID); -- Undefer abort here to allow a window for this task -- to be aborted at the time of system shutdown. end loop; end Signal_Server_Task; --------------------------- -- Interrupt_Server_Task -- --------------------------- -- Server task for vectored hardware interrupt handling task body Interrupt_Server_Task is Self_ID : Task_ID := Self; Tmp_Handler : Parameterless_Handler; Tmp_ID : Task_ID; Tmp_Entry_Index : Task_Entry_Index; S : STATUS; use type STATUS; begin System.Tasking.Utilities.Make_Independent; Semaphore_ID_Map (Interrupt) := Int_Sema; loop -- Pend on semaphore that will be triggered by the -- umbrella handler when the associated interrupt comes in S := semTake (Int_Sema, WAIT_FOREVER); pragma Assert (S = 0); if User_Handler (Interrupt).H /= null then -- Protected procedure handler Tmp_Handler := User_Handler (Interrupt).H; Tmp_Handler.all; elsif User_Entry (Interrupt).T /= Null_Task then -- Interrupt entry handler Tmp_ID := User_Entry (Interrupt).T; Tmp_Entry_Index := User_Entry (Interrupt).E; System.Tasking.Rendezvous.Call_Simple (Tmp_ID, Tmp_Entry_Index, System.Null_Address); else -- Semaphore has been flushed by an unbind operation in -- the Interrupt_Manager. Terminate the server task. -- Wait for the Interrupt_Manager to complete its work POP.Write_Lock (Self_ID); -- Delete the associated semaphore S := semDelete (Int_Sema); pragma Assert (S = 0); -- Set status for the Interrupt_Manager Semaphore_ID_Map (Interrupt) := 0; Task_Lock (Interrupt) := False; Server_ID (Interrupt) := Null_Task; POP.Unlock (Self_ID); exit; end if; end loop; end Interrupt_Server_Task; begin -- Elaboration code for package System.Interrupts -- Get Interrupt_Manager's ID so that Abort_Interrupt can be sent. Interrupt_Manager_ID := To_System (Interrupt_Manager'Identity); -- Initialize the lock L. Initialization.Defer_Abort (Self); POP.Initialize_Lock (L'Access, POP.PO_Level); Initialization.Undefer_Abort (Self); -- During the elaboration of this package body we want the RTS to -- inherit its signal mask from the Environment Task. -- The Environment Task should have gotten its mask from -- the enclosing process during the RTS start up. (See -- in s-inmaop.adb). Pass the Interrupt_Mask of the Environment -- task to the Interrupt_Manager. -- Note : At this point we know that all tasks (including -- RTS internal servers) are masked for non-reserved signals -- (see s-taprop.adb). Only the Interrupt_Manager will have -- masks set up differently, inheriting the original Environment -- Task's mask. Interrupt_Manager.Initialize (IMOP.Environment_Mask); end System.Interrupts; ",12214,False,2385.206551925735,median "-- This file was generated by bmp2ada with Giza.Image; with Giza.Image.DMA2D; use Giza.Image.DMA2D; package clock_80x80 is pragma Style_Checks (Off); CLUT : aliased constant L4_CLUT_T := ( (R => 3, G => 6, B => 2), (R => 248, G => 250, B => 246), others => (0, 0, 0)); Data : aliased constant L4_Data_T := ( 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 1, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 16, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 17, 17, 17, 17, 17, 1, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 17, 17, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 17, 17, 17, 17, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 16, 1, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 17, 17, 17, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 16, 1, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 17, 17, 1, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 16, 1, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 17, 17, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 16, 1, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 17, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 16, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 1, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 16, 1, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 16, 1, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 16, 1, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 16, 1, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 16, 17, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 17, 17, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 1, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 16, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17 ); Image : constant Giza.Image.Ref := new Giza.Image.DMA2D.Instance' (Mode => L4, W => 80, H => 80, Length => 3200, L4_CLUT => CLUT'Access, L4_Data => Data'Access); pragma Style_Checks (On); end clock_80x80; ",12424,True,5336.091686157713,median "[[es6-essentials]] == ES6 Essentials The sixth edition of the language comes with a plethora of non-breaking syntax improvements, most of which we'll tackle throughout this chapter. Many of these changes are syntactic sugar; that is, they could be represented in ES5, albeit using more complicated pieces of code. There are also changes that aren't merely (((""syntactic sugar"")))syntactic sugar but a completely different way of declaring variables using `let` and `const`, as we'll see toward the end of the chapter. Object literals get a few syntax changes in ES6, and they're a good place to start. === Object Literals An (((""object literals"", id=""ol2"")))_object literal_ is any object declaration using the `{}` shorthand syntax, such as the following example: [source,javascript] ---- var book = { title: 'Modular ES6', author: 'Nicolas', publisher: 'O´Reilly' } ---- ES6 brings a few improvements to object literal syntax: property value shorthands, computed property names, and method definitions. Let's go through them and describe their use cases as well. ==== Property Value Shorthands Sometimes (((""object literals"", ""property value shorthands"", id=""ol2pvs"")))(((""property value shorthands"", id=""pvs2"")))we declare objects with one or more properties whose values are references to variables by the same name. For example, we might have a `listeners` collection, and in order to assign it to a property called `listeners` of an object literal, we have to repeat its name. The following snippet has a typical example where we have an object literal declaration with a couple of these repetitive properties: [source,javascript] ---- var listeners = [] function listen() {} var events = { listeners: listeners, listen: listen } ---- Whenever you find yourself in this situation, you can omit the property value and the colon by taking advantage of the new property value shorthand syntax in ES6. As shown in the following example, the new ES6 syntax makes the assignment implicit: [source,javascript] ---- var listeners = [] function listen() {} var events = { listeners, listen } ---- As we'll further explore in the second part of the book, property value shorthands help de-duplicate the code we write without diluting its meaning. In the following snippet, I reimplemented part of `localStorage`, a browser API for persistent storage, as an in-memory ponyfill.pass:[Like polyfills, ponyfills are user-land implementations of features that aren't available in every JavaScript runtime. While polyfills try to patch the runtime environment so that it behaves as if the feature was indeed available on the runtime, ponyfills implement the missing functionality as standalone modules that don't pollute the runtime environment. This has the benefit of not breaking expectations third-party libraries (that don't know about your polyfill) may have about the environment.] If it weren't for the shorthand syntax, the `storage` object would be more verbose to type out: [source,javascript] ---- var store = {} var storage = { getItem, setItem, clear } function getItem(key) { return key in store ? store[key] : null } function setItem(key, value) { store[key] = value } function clear() { store = {} } ---- That's the first of many ES6 features that are aimed toward reducing complexity in the code you have to maintain. Once you get used to the syntax, you'll notice that code readability and developer productivity get boosts as (((""object literals"", ""property value shorthands"", startref=""ol2pvs"")))(((""property value shorthands"", startref=""pvs2"")))well. ==== Computed Property Names Sometimes (((""object literals"", ""computed property names"", id=""ol2cpn"")))(((""computed property names"", id=""cpn2"")))you have to declare objects that contain properties with names based on variables or other JavaScript expressions, as shown in the following piece of code written in ES5. For this example, assume that `expertise` is provided to you as a function parameter, and is not a value you know beforehand: [source,javascript] ---- var expertise = 'journalism' var person = { name: 'Sharon', age: 27 } person[expertise] = { years: 5, interests: ['international', 'politics', 'internet'] } ---- Object literals in ES6 aren't constrained to declarations with static names. With computed property names, you can wrap any expression in square brackets, and use that as the property name. When the declaration is reached, your expression is evaluated and used as the property name. The following example shows how the piece of code we just saw could declare the +person+ object in a single step, without having to resort to a second statement adding the person's `expertise`. [source,javascript] ---- var expertise = 'journalism' var person = { name: 'Sharon', age: 27, [expertise]: { years: 5, interests: ['international', 'politics', 'internet'] } } ---- You can't combine the property value shorthands with computed property names. Value shorthands are simple compile-time syntactic sugar that helps avoid repetition, while computed property names are evaluated at runtime. Given that we're trying to mix these two incompatible features, the following example would throw a syntax error. In most cases this combination would lead to code that's hard to interpret for other humans, so it's probably a good thing that you can't combine the two. [source,javascript] ---- var expertise = 'journalism' var journalism = { years: 5, interests: ['international', 'politics', 'internet'] } var person = { name: 'Sharon', age: 27, [expertise] // this is a syntax error! } ---- A common scenario for computed property names is when we want to add an entity to an object map that uses the `entity.id` ((("" entity.id field"")))field as its keys, as shown next. Instead of having to have a third statement where we add the `grocery` to the `groceries` map, we can inline that declaration in the `groceries` object literal itself. [source,javascript] ---- var grocery = { id: 'bananas', name: 'Bananas', units: 6, price: 10, currency: 'USD' } var groceries = { [grocery.id]: grocery } ---- Another case may be whenever a function receives a parameter that it should then use to build out an object. In ES5 code, you'd need to allocate a variable declaring an object literal, then add the dynamic property, and then return the object. The following example shows exactly that, when creating an envelope that could later be used for Ajax messages that follow a convention: they have an `error` property with a description when something goes wrong, and a `success` property (((""error property"")))(((""success property"")))when things turn out okay: [source,javascript] ---- function getEnvelope(type, description) { var envelope = { data: {} } envelope[type] = description return envelope } ---- Computed property names help us write the same function more concisely, using a single statement: [source,javascript] ---- function getEnvelope(type, description) { return { data: {}, [type]: description } } ---- The last enhancement coming to object literals is (((""object literals"", ""computed property names"", startref=""ol2cpn"")))(((""computed property names"", startref=""cpn2"")))about functions. ==== Method Definitions Typically, (((""object literals"", ""method definitions"", id=""ol2md"")))(((""method definitions"", id=""mdef2"")))you can declare methods on an object by adding properties to it. In the next snippet, we're creating a small event emitter that supports multiple kinds of events. It comes with an `emitter#on` method (((""emitter object"", id=""eo2"")))that can be used to register event listeners, and an `emitter#emit` method that can be used to raise events: [source,javascript] ---- var emitter = { events: {}, on: function (type, fn) { if (this.events[type] === undefined) { this.events[type] = [] } this.events[type].push(fn) }, emit: function (type, event) { if (this.events[type] === undefined) { return } this.events[type].forEach(function (fn) { fn(event) }) } } ---- Starting in ES6, you can declare methods on an object literal using the new method definition syntax. In this case, we can omit the colon and the `function` keyword. This is meant as a terse alternative to traditional method declarations where you need to use the pass:[function] (((""function keyword"")))keyword. The following example shows how our `emitter` object looks when using method definitions. [source,javascript] ---- var emitter = { events: {}, on(type, fn) { if (this.events[type] === undefined) { this.events[type] = [] } this.events[type].push(fn) }, emit(type, event) { if (this.events[type] === undefined) { return } this.events[type].forEach(function (fn) { fn(event) }) } } ---- Arrow (((""emitter object"", startref=""eo2"")))(((""arrow functions"", id=""af2"")))functions are another way of declaring functions in ES6, and they come in several flavors. Let's investigate what arrow functions are, how they can be declared, and how they behave (((""object literals"", startref=""ol2"")))(((""object literals"", ""method definitions"", startref=""ol2md"")))(((""method definitions"", startref=""mdef2"")))semantically. [[arrow_functions]] === Arrow Functions In JavaScript you typically declare functions using code like the following, where you have a name, a list of parameters, and a function body. [source,javascript] ---- function name(parameters) { // function body } ---- You could also create (((""arrow functions"", ""anonymous"", id=""af2a"")))(((""anonymous functions"", id=""anonf2"")))anonymous functions, by omitting the name when assigning the function to a variable, a property, or a function call. [source,javascript] ---- var example = function (parameters) { // function body } ---- Starting with ES6, you can use arrow functions as another way of writing anonymous functions. Keep in mind, there are several slightly different ways of writing them. The following piece of code shows an arrow function that's very similar to the anonymous function we just saw. The only difference seems to be the missing `function` keyword and the `=>` arrow to the right of the parameter list. [source,javascript] ---- var example = (parameters) => { // function body } ---- While arrow functions look very similar to your typical anonymous function, they are fundamentally different: arrow functions can't be named explicitly, although modern runtimes can infer a name based on the variable they're assigned to; they can't be used as constructors nor do they have a `prototype` property, meaning you can't use `new` on an arrow function; and they are bound to their lexical scope, which is the reason why they don't alter the meaning of `this`. Let's dig into their semantic differences with traditional functions, the many ways to declare an arrow function, and practical use cases. ==== Lexical Scoping In (((""arrow functions"", ""lexical scoping"", id=""af2ls"")))(((""lexical scoping"", id=""ls2"")))the body of an arrow function, `this`, `arguments`, and `super` point to the containing scope, since arrow functions don't create a new scope. Consider the following example. We have a `timer` object with a `seconds` counter and a `start` method defined using the syntax we learned about earlier. We then start the timer, wait for a few seconds, and log the current amount of elapsed `seconds`: [source,javascript] ---- var timer = { seconds: 0, start() { setInterval(() => { this.seconds++ }, 1000) } } timer.start() setTimeout(function () { console.log(timer.seconds) }, 3500) // <- 3 ---- If we had defined the function passed to `setInterval` as a regular anonymous function instead of using an arrow function, `this` would've been bound to the context of the (((""arrow functions"", ""anonymous"", startref=""af2a"")))(((""anonymous functions"", startref=""anonf2"")))anonymous function, instead of the context of the `start` method. We could have implemented `timer` with a declaration like `var self = this` at the beginning of the `start` method, and then referencing `self` instead of `this`. With arrow functions, the added complexity of keeping context references around fades away and we can focus on the functionality of our code. In a similar fashion, lexical binding in ES6 arrow functions also means that function calls won't be able to change the `this` context when using `.call`, `.apply`, `.bind`, etc. That limitation is usually more useful than not, as it ensures that the context will always be preserved and constant. Let's now shift our attention to the following example. What do you think the `console.log` statement will print? [source,javascript] ---- function puzzle() { return function () { console.log(arguments) } } puzzle('a', 'b', 'c')(1, 2, 3) ---- The answer is that `arguments` refers (((""arguments object"")))to the context of the anonymous function, and thus the arguments passed to that function will be printed. In this case, those arguments are `1, 2, 3`. What about in the following case, where we use an arrow function instead of the anonymous function in the previous example? [source,javascript] ---- function puzzle() { return () => console.log(arguments) } puzzle('a', 'b', 'c')(1, 2, 3) ---- Because arrow functions don't have their own `arguments` keyword (or `this` or `super`), the lookup bubbles up to the outer scope of the `puzzle` function. That means the printed arguments will be `'a', 'b', 'c'`. I've mentioned there are several flavors of arrow functions, but so far we've only looked at their fully fleshed version. What are the other ways to represent an (((""arrow functions"", ""lexical scoping"", startref=""af2ls"")))(((""lexical scoping"", startref=""ls2"")))arrow function? ==== Arrow Function Flavors Let's (((""arrow functions"", ""flavors"", id=""af2f"")))look one more time at the arrow function syntax we've learned so far: [source,javascript] ---- var example = (parameters) => { // function body } ---- An arrow function with exactly one parameter can omit the parentheses. This is optional. It's useful when passing the arrow function to another method, as it reduces the amount of parentheses involved, making it easier for some humans to parse the code: [source,javascript] ---- var double = value => { return value * 2 } ---- Arrow functions are heavily used for simple functions, such as the `double` function (((""double functions"")))(((""arrow functions"", ""double"")))we just saw. The following flavor of arrow functions does away with the function body. Instead, you provide an expression such as `value * 2`. When the function is called, the expression is evaluated and its result is returned. The `return` statement is (((""return statement"")))implicit, and there's no need for curly braces denoting the function body anymore, as you can only use a single expression: [source,javascript] ---- var double = (value) => value * 2 ---- Note that you can combine implicit parentheses and implicit return, making for concise arrow functions: [source,javascript] ---- var double = value => value * 2 ---- .Implicitly Returning Object Literals **** When you need to implicitly return an object literal, you'll need to wrap that object literal expression in parentheses. Otherwise, the compiler would interpret your curly braces as the start and the end of the function block. [source,javascript] ---- var objectFactory = () => ({ modular: 'es6' }) ---- In the following example, JavaScript interprets the curly braces as the body of our arrow function. Furthermore, `number` is interpreted as a labelpass:[Labels are used as a way of identifying instructions. Labels can be used by goto statements, to indicate what instruction we should jump to; break statements, to indicate the sequence we want to break out of; and continue statements, to indicate the sequence we want to advance.] and then figures out we have a `value` expression that doesn't do anything. Since we're in a block and not returning anything, the mapped values will be `undefined`: [source,javascript] ---- [1, 2, 3].map(value => { number: value }) // <- [undefined, undefined, undefined] ---- If our attempt at implicitly returning an object literal had more than a single property, then the compiler wouldn't be able to make sense of the second property, and it'd throw a `SyntaxError`: [source,javascript] ---- [1, 2, 3].map(value => { number: value, verified: true }) // <- SyntaxError ---- Wrapping the expression in parentheses fixes these issues, because the compiler would no longer interpret it as a function block. Instead, the object declaration becomes an expression that evaluates to the object literal we want to return implicitly: [source,javascript] ---- [1, 2, 3].map(value => ({ number: value, verified: true })) /* <- [ { number: 1, verified: true }, { number: 2, verified: true }, { number: 3, verified: true }] */ ---- **** Now that you understand arrow functions, let's ponder about their merits and where they might be a (((""arrow functions"", ""flavors"", startref=""af2f"")))good fit. ==== Merits and Use Cases As (((""arrow functions"", ""merits and use cases"", id=""af2mauc"")))a rule of thumb, you shouldn't blindly adopt ES6 features wherever you can. Instead, it's best to reason about each case individually and see whether adopting the new feature actually improves code readability and maintainability. ES6 features are not strictly better than what we had all along, and it's a bad idea to treat them as such. There are a few situations where arrow functions may not be the best tool. For example, if you have a large function comprised of several lines of code, replacing `function` with `=>` is hardly going to improve your code. Arrow functions are often most effective for short routines, where the `function` keyword and syntax boilerplate make up a significant portion of the function expression. Properly (((""arrow functions"", ""naming"")))naming a function adds context to make it easier for humans to interpret them. Arrow functions can't be explicitly named, but they can be named implicitly by assigning them to a variable. In the following example, we assign an arrow function to the `throwError` variable. When calling this function results in an error, the stack trace properly identifies the arrow function as `throwError`: [source,javascript] ---- var throwError = message => { throw new Error(message) } throwError('this is a warning') <- Uncaught Error: this is a warning at throwError ---- Arrow functions are neat when it comes to defining anonymous functions that should probably be lexically bound anyway, and they can definitely make your code more terse in some situations. They are particularly useful in most functional programming situations, such as when using `.map`, `.filter`, or `.reduce` on collections, as shown in the following example: [source,javascript] ---- [1, 2, 3, 4] .map(value => value * 2) .filter(value => value > 2) .forEach(value => console.log(value)) // <- 4 // <- 6 // <- 8 ---- === Assignment Destructuring This (((""arrow functions"", startref=""af2"")))(((""arrow functions"", ""merits and use cases"", startref=""af2mauc"")))(((""assignment destructuring"", id=""ad2"")))(((""destructuring"", id=""d2"")))is one of the most flexible and expressive features in ES6. It's also one of the simplest. It binds properties to as many variables as you need. It works with objects, arrays, and even in `function` parameter lists. Let's go step by step, starting with objects. ==== Destructuring Objects Imagine (((""assignment destructuring"", ""objects"", id=""ad2o"")))(((""destructuring"", ""objects"", id=""d2o"")))(((""objects"", ""destructuring"", id=""o2d"")))you had a program describing a color palette and you want to refer to properties in the object that describes it. Here's an example object we'll be using for our palette: [source,javascript] ---- var palette = { profile: 'intense-red', name: 'Red', color: { code: `#f00` }, luminosity: 0.8 } ---- If you wanted a `profile` variable referencing `palette.profile`, you could write the following bit of ES5 code. This is commonplace when, for instance, you'll be referencing `profile` in several places in your codebase and you'd prefer to avoid typing out `palette.profile` each time: [source,javascript] ---- var profile = palette.profile ---- With destructuring in assignment, the syntax becomes a bit more clear. As you can see in the next example, you don't have to write `profile` twice, while still clearly conveying intent. The following statement is equivalent to the previous one written in ES5 code: [source,javascript] ---- var { profile } = palette ---- Just like you could declare multiple comma-separated variables with a single `var` statement, you can also declare multiple variables within the curly braces of a destructuring expression: [source,javascript] ---- var { profile, name } = palette ---- In a similar fashion, you could mix and match destructuring with regular variable declarations in the same `var` statement. While this might look a bit confusing at first, it'll be up to any JavaScript coding style guides you follow to determine whether it's appropriate to declare several variables in a single statement. In any case, it goes to show the flexibility offered by destructuring syntax: [source,javascript] ---- var { profile } = palette, two = 2 ---- If you want to extract a property named `profile` but would like to declare it as a variable named `id`, you can use the following destructuring syntax, known as _aliasing_. Note that you can use `id` or any other valid variable name: [source,javascript] ---- var { profile: id } = palette console.log(id) // <- 'intense-red' ---- While aliases don't look any simpler than the ES5 flavor, `id = palette.profile`, (((""aliases"", id=""al2"")))they start making sense when you consider the fact that destructuring supports deep structures, as in the following example: [source,javascript] ---- var { color: { code } } = palette ---- In cases like the previous one, where you have deeply nested properties being destructured, you might be able to convey a property name more clearly if you choose an alias. Consider the next snippet, where a property named `code` wouldn't have been as indicative of its contents as `colorCode` could be: [source,javascript] ---- var { color: { code: colorCode } } = palette ---- The scenario we just saw repeats itself frequently, because properties are often named in the context of their host object. While `palette.color.code` is perfectly descriptive, `code` on its own could mean a wide variety of things, and aliases such as `colorCode` can help you bring context back into the variable name while still using destructuring. Whenever you access a nonexistent property in ES5 notation, you get a value of `undefined`: [source,javascript] ---- console.log(palette.luminosity) // <- undefined console.log(palette['luminosity']) // <- undefined ---- With destructuring, the same behavior prevails. When declaring a destructured variable for a property that's missing, you'll get back `undefined` as well. [source,javascript] ---- var { luminosity } = palette console.log(luminosity) // <- undefined ---- A destructured declaration accessing a nested property of a parent object that's `null` or `undefined` will throw an `Exception`, just like regular attempts to access properties of `null` or `undefined` would, in other cases. [source,javascript] ---- var { stroke: { width } } = palette // <- Exception var { missing } = null // <- Exception ---- When you think of that piece of code as the equivalent ES5 code shown next, it becomes evident why the expression must throw, given that destructuring is mostly syntactic sugar. [source,javascript] ---- var nothing = null var missing = nothing.missing // <- Exception ---- As part of destructuring, you can provide default values for those cases where the value is `undefined`. The default value can be anything you can think of: numbers, strings, functions, objects, a reference to another variable, etc. [source,javascript] ---- var { description = 'This is a color palette' } = palette console.log(description) // <- 'This is a color palette' ---- Default values can also be provided in nested property destructuring. [source,javascript] ---- var { color: { density = 320 } } = palette console.log(density) // <- 320 ---- For use in combination with aliases, you should place the alias first, and then the default value, as shown next. [source,javascript] ---- var { color: paletteColor = { density: 320 } } = palette ---- It's possible to use the (((""computed property names"")))computed property names syntax in destructuring patterns. In this case, however, you're required to provide an alias to be used as the variable name. That's because computed property names allow arbitrary expressions and thus the compiler wouldn't be able to infer a variable name. In the following example we use the `paletteProfile` alias, and a computed property name to extract the `profile` property from the `palette` object. [source,javascript] ---- var { ['pro' + 'file']: paletteProfile } = palette console.log(paletteProfile) // <- true ---- This flavor of destructuring is probably the least useful, as `sourceProperty = source[property]` is usually simpler than `{ [property]: sourceProperty } = source`, as it's a more sequential statement. That being said, the feature is useful when you have properties you want to declare in the object literal, as opposed to using subsequent assignment statements. That's it, as far as objects go, in terms of destructuring. (((""assignment destructuring"", ""objects"", startref=""ad2o"")))(((""destructuring"", ""objects"", startref=""d2o"")))(((""objects"", ""destructuring"", startref=""o2d"")))(((""aliases"", startref=""al2"")))What about arrays? ==== Destructuring Arrays The (((""assignment destructuring"", ""arrays"", id=""ad2a"")))(((""destructuring"", ""arrays"", id=""d2a"")))(((""arrays"", id=""a2d"")))syntax for destructuring arrays is similar to that of objects. The (((""coordinates object"")))following example shows a `coordinates` object that's destructured into two variables: `x` and `y`. Note how the notation uses square brackets instead of curly braces; this denotes we're using array destructuring instead of object destructuring. Instead of having to sprinkle your code with implementation details like `x = coordinates[0]`, with destructuring you can convey your meaning clearly and without explicitly referencing the indices, naming the values instead. [source,javascript] ---- var coordinates = [12, -7] var [x, y] = coordinates console.log(x) // <- 12 ---- When destructuring arrays, you can skip uninteresting properties or those that you otherwise don't need to reference. [source,javascript] ---- var names = ['James', 'L.', 'Howlett'] var [ firstName, , lastName ] = names console.log(lastName) // <- 'Howlett' ---- Array destructuring allows for default values just like object destructuring. [source,javascript] ---- var names = ['James', 'L.'] var [ firstName = 'John', , lastName = 'Doe' ] = names console.log(lastName) // <- 'Doe' ---- In ES5, when you have to swap the values of two variables, you typically resort to a third, temporary variable, as in the following snippet. [source,javascript] ---- var left = 5 var right = 7 var aux = left left = right right = aux ---- Destructuring helps you avoid the `aux` declaration and focus on your intent. Once again, destructuring helps us convey intent more tersely and effectively for the use case. [source,javascript] ---- var left = 5 var right = 7 [left, right] = [right, left] ---- The last area of destructuring we'll be covering is (((""assignment destructuring"", ""arrays"", startref=""ad2a"")))(((""destructuring"", ""arrays"", startref=""d2a"")))(((""arrays"", startref=""a2d"")))function parameters. ==== Function Parameter Defaults Function parameters (((""assignment destructuring"", ""function parameters"", id=""ad2fpd"")))(((""destructuring"", ""function parameters"", id=""d2fpd"")))(((""function parameters"", id=""fpd2"")))in ES6 enjoy the ability of specifying default values as well. The following example defines a default `exponent` with the most commonly used value. [source,javascript] ---- function powerOf(base, exponent = 2) { return Math.pow(base, exponent) } ---- Defaults can be applied to arrow function parameters as well. When we have default values in an arrow function we must wrap the parameter list in parentheses, even when there's a single parameter. [source,javascript] ---- var double = (input = 0) => input * 2 ---- Default values aren't limited to the rightmost parameters of a function, as in a few other programming languages. You could provide default values for any parameter, in any position. [source,javascript] ---- function sumOf(a = 1, b = 2, c = 3) { return a + b + c } console.log(sumOf(undefined, undefined, 4)) // <- 1 + 2 + 4 = 7 ---- In JavaScript it's not uncommon to provide a function with an `options` object, containing several properties. You could determine a default `options` object (((""options object"", id=""oo2"")))if one isn't provided, as shown in the next snippet. [source,javascript] ---- var defaultOptions = { brand: 'Volkswagen', make: 1999 } function carFactory(options = defaultOptions) { console.log(options.brand) console.log(options.make) } carFactory() // <- 'Volkswagen' // <- 1999 ---- The problem with this approach is that as soon as the consumer of `carFactory` provides an `options` object, you lose all of your defaults. [source,javascript] ---- carFactory({ make: 2000 }) // <- undefined // <- 2000 ---- We can mix function parameter default values with destructuring, and get the best of both worlds. ==== Function Parameter Destructuring A better approach than merely providing a default value might be to destructure `options` entirely, providing default values for each property, individually, within the destructuring pattern. This approach also lets you reference each option without going through an `options` object, but you lose the ability to reference `options` directly, which might represent an issue in some situations. [source,javascript] ---- function carFactory({ brand = 'Volkswagen', make = 1999 }) { console.log(brand) console.log(make) } carFactory({ make: 2000 }) // <- 'Volkswagen' // <- 2000 ---- In this case, however, we've once again lost the default value for the case where the consumer doesn't provide any `options`. Meaning `carFactory()` will now throw when an `options` object isn't provided. This can be remedied by using the syntax shown in the following snippet of code, which adds a default `options` value of an empty object. The empty object is then filled, property by property, with the default values on the destructuring pattern. [source,javascript] ---- function carFactory({ brand = 'Volkswagen', make = 1999 } = {}) { console.log(brand) console.log(make) } carFactory() // <- 'Volkswagen' // <- 1999 ---- Besides default values, you can use destructuring in function parameters to describe the shape of objects your function can handle. Consider the following code snippet, where we have a `car` object with several properties. The `car` object describes its owner, what kind of car it is, who manufactured it, when, and the owner's preferences when he (((""options object"", startref=""oo2"")))purchased the car. [source,javascript] ---- var car = { owner: { id: 'e2c3503a4181968c', name: 'Donald Draper' }, brand: 'Peugeot', make: 2017, model: '208', preferences: { airbags: true, airconditioning: false, color: 'red' } } ---- If we wanted to implement a function that only takes into account certain properties of a parameter, it might be a good idea to reference those properties explicitly by destructuring up front. The upside is that we become aware of every required property upon reading the function's signature. When we destructure everything up front, it's easy to spot when input doesn't adhere to the contract of a function. The following example shows how every property we need could be specified in the parameter list, laying bare the shape of the objects we can handle in the `getCarProductModel` API. [source,javascript] ---- var getCarProductModel = ({ brand, make, model }) => ({ sku: brand + ':' + make + ':' + model, brand, make, model }) getCarProductModel(car) ---- Besides default values and filling an `options` object, let's explore what else destructuring is good at. ==== Use Cases for Destructuring Whenever (((""assignment destructuring"", ""use cases for"", id=""ad2ucf"")))(((""destructuring"", ""use cases for"", id=""d2ucf"")))there's a function that returns an object or an array, destructuring makes it much terser to interact with. The following example shows a function that returns an object with some coordinates, where we grab only the ones we're interested in: `x` and `y`. We're avoiding an intermediate `point` variable declaration that often gets in the way without adding a lot of value to the readability of your code. [source,javascript] ---- function getCoordinates() { return { x: 10, y: 22, z: -1, type: '3d' } } var { x, y } = getCoordinates() ---- The case for default option values bears repeating. Imagine you have a `random` function that produces random integers between a `min` and a `max` value, and that it should default to values between 1 and 10. This is particularly interesting as an alternative to named parameters in languages with strong typing features, such as Python and C#. This pattern, where you're able to define default values for options and then let consumers override them individually, offers great flexibility. [source,javascript] ---- function random({ min = 1, max = 10 } = {}) { return Math.floor(Math.random() * (max - min)) + min } console.log(random()) // <- 7 console.log(random({ max: 24 })) // <- 18 ---- Regular (((""assignment destructuring"", ""function parameters"", startref=""ad2fpd"")))(((""destructuring"", ""function parameters"", startref=""d2fpd"")))(((""function parameters"", startref=""fpd2"")))expressions are another great fit for destructuring. Destructuring empowers you to name groups from a match without having to resort to index numbers. Here's an example `RegExp` that could be used for parsing simple dates, and an example of destructuring those dates into each of their components. The first entry in the resulting array is reserved for the full matched text, and we can discard it. [source,javascript] ---- function splitDate(date) { var rdate = /(\\d+).(\\d+).(\\d+)/ return rdate.exec(date) } var [ , year, month, day] = splitDate('2017-11-06') ---- You'll want to be careful when the regular expression doesn't match, as that returns `null`. Perhaps a better approach would be to test for the failure case before destructuring, as shown in the following bit of code. [source,javascript] ---- var matches = splitDate('2017-11-06') if (matches === null) { return } var [, year, month, day] = matches ---- Let's turn our attention to spread and rest operators (((""assignment destructuring"", ""use cases for"", startref=""ad2ucf"")))(((""destructuring"", ""use cases for"", startref=""d2ucf"")))(((""assignment destructuring"", startref=""ad2"")))(((""destructuring"", startref=""d2"")))next. === Rest Parameter and Spread Operator Before ES6, interacting with an arbitrary amount of function parameters was complicated. You had to use `arguments`, which isn't an array but has a `length` property. Usually you'd end up casting the `arguments` object into an actual array using `Array#slice.call`, and going from there, as shown in the following snippet. [source,javascript] ---- function join() { var list = Array.prototype.slice.call(arguments) return list.join(', ') } join('first', 'second', 'third') // <- 'first, second, third' ---- ES6 has a better solution to the problem, and that's rest parameters. ==== Rest Parameters You (((""rest parameters"", id=""rp2"")))can now precede the last parameter in any JavaScript function with three dots, converting it into a special ""rest parameter."" When the rest parameter is the only parameter in a function, it gets all arguments passed to the function: it works just like the `.slice` solution we saw earlier, but you avoid the need for a complicated construct like `arguments`, and it's specified in the parameter list. [source,javascript] ---- function join(...list) { return list.join(', ') } join('first', 'second', 'third') // <- 'first, second, third' ---- Named parameters before the rest parameter won't be included in the `list`. [source,javascript] ---- function join(separator, ...list) { return list.join(separator) } join('; ', 'first', 'second', 'third') // <- 'first; second; third' ---- Note that arrow functions with a rest parameter must include parentheses, even when it's the only parameter. Otherwise, a `SyntaxError` would be thrown. The following piece of code is a beautiful example of how combining arrow functions and rest parameters can yield concise functional expressions. [source,javascript] ---- var sumAll = (...numbers) => numbers.reduce( (total, next) => total + next ) console.log(sumAll(1, 2, 5)) // <- 8 ---- Compare that with the ES5 version of the same function. Granted, it's all in the complexity. While terse, the `sumAll` function can be confusing to readers unused to the `.reduce` method, or because it uses two arrow functions. This is a complexity trade-off that we'll cover in the second part of the book. [source,javascript] ---- function sumAll() { var numbers = Array.prototype.slice.call(arguments) return numbers.reduce(function (total, next) { return total + next }) } console.log(sumAll(1, 2, 5)) // <- 8 ---- Next up we have the spread operator. It's also denoted with three dots, but it serves a slightly different (((""rest parameters"", startref=""rp2"")))purpose. ==== Spread Operator The (((""spread operator"", id=""so2"")))spread operator can be used to cast any iterable object into an array. Spreading effectively expands an expression onto a target such as an array literal or a function call. The following example uses `...arguments` to cast function parameters into an array literal. [source,javascript] ---- function cast() { return [...arguments] } cast('a', 'b', 'c') // <- ['a', 'b', 'c'] ---- We could use the spread operator to split a string into an array with each code point that makes up the string. [source,javascript] ---- [...'show me'] // <- ['s', 'h', 'o', 'w', ' ', 'm', 'e'] ---- You can place additional elements to the left and to the right of a spread operation and still get the result you would expect. [source,javascript] ---- function cast() { return ['left', ...arguments, 'right'] } cast('a', 'b', 'c') // <- ['left', 'a', 'b', 'c', 'right'] ---- Spread is an useful way of combining multiple arrays. The following example shows how you can spread arrays anywhere into an array literal, expanding their elements into place. [source,javascript] ---- var all = [1, ...[2, 3], 4, ...[5], 6, 7] console.log(all) // <- [1, 2, 3, 4, 5, 6, 7] ---- Note that the spread operator isn't limited to arrays and `arguments`. The spread operator can be used with any iterable object. Iterable is a protocol in ES6 that allows you to turn any object into something that can be iterated over. We'll research the (((""iterable protocol"")))iterable protocol in <>. .Shifting and Spreading **** When you want to extract an element or two from the beginning of an array, the common approach is to ((("".shift()"", primary-sortas=""shift"")))((("".shift()"")))use `.shift`. While functional, the following snippet of code can be hard to understand at a glance, because it uses `.shift` twice to grab a different item from the beginning of the `list` each time. The focus is, like in many other pre-ES6 situations, placed on getting the language to do what we want. [source,javascript] ---- var list = ['a', 'b', 'c', 'd', 'e'] var first = list.shift() var second = list.shift() console.log(first) // <- 'a' ---- In ES6, you can combine spread with array destructuring. The following piece of code is similar to the preceding one, except we're using a single line of code, and that single line is more descriptive of what we're doing than repeatedly calling `list.shift()` in the previous example. [source,javascript] ---- var [first, second, ...other] = ['a', 'b', 'c', 'd', 'e'] console.log(other) // <- ['c', 'd', 'e'] ---- Using the spread operator you can focus on implementing the functionality you need while the language stays out of the way. Improving expressiveness and decreasing time spent working around language limitations is a common pattern we can observe in ES6 features. **** Before ES6, whenever you had a dynamic list of arguments that needed to be applied to a function call, you'd use `.apply`. This ((("".apply()"", primary-sortas=""apply"", id=""apply2"")))is inelegant because `.apply` also takes a context for `this`, which, in this scenario, you don't want to concern yourself with. [source,javascript] ---- fn.apply(null, ['a', 'b', 'c']) ---- Besides spreading onto arrays, you can also spread items onto function calls. The following example shows how you could use the spread operator to pass an arbitrary number of arguments to the `multiply` (((""multiply()"")))function. [source,javascript] ---- function multiply(left, right) { return left * right } var result = multiply(...[2, 3]) console.log(result) // <- 6 ---- Spreading arguments onto a function call can be combined with regular arguments as much as necessary, just like with array literals. The next example calls `print` with a couple of regular arguments and a couple of arrays being spread over the parameter list. Note how conveniently the rest `list` parameter matches all the provided arguments. Spread and rest can help make code intent more clear without diluting your codebase. [source,javascript] ---- function print(...list) { console.log(list) } print(1, ...[2, 3], 4, ...[5]) // <- [1, 2, 3, 4, 5] ---- Another limitation of `.apply` is that combining it with the `new` keyword, when instantiating an object, becomes very verbose. Here's an example of combining `new` and `.apply` to create a `Date` object. Ignore for a moment that months in JavaScript dates are zero-based, turning `11` into December, and consider how much of the following line of code is spent bending the language in our favor, ((("".apply()"", primary-sortas=""apply"", startref=""apply2"")))just to instantiate a `Date` object. [source,javascript] ---- new (Date.bind.apply(Date, [null, 2017, 11, 31])) // <- Thu Dec 31 2017 ---- As shown in the next snippet, the spread operator strips away all the complexity and we're only left with the important bits. It's a `new` instance, it uses `...` to spread a dynamic list of arguments over the function call, and it's a `Date`. (((""Date()"")))That's it. [source,javascript] ---- new Date(...[2017, 11, 31]) // <- Thu Dec 31 2017 ---- The following table summarizes the use cases we've discussed for the spread operator. [options=""header""] |======= |Use case|ES5|ES6 |Concatenation|`[1, 2].concat(more)`|`[1, 2, ...more]` |Push an array onto list|`list.push.apply(list, items)`|`list.push(...items)` |Destructuring|`a = list[0], other = list.slice(1)` | `[a, ...other] = list` |`new` and `apply`|`new (Date.bind.apply(Date, [null,2017,11,31]))`| `new Date(...[2017,11,31])` |======= [[template_literals]] === Template Literals Template (((""spread operator"", startref=""so2"")))(((""template literals"", id=""templ2"")))literals are a vast improvement upon regular JavaScript strings. Instead of using single or double quotes, template literals are declared using backticks, as shown next. [source,javascript] ---- var text = `This is my first template literal` ---- Given that template literals are delimited by backticks, you're now able to declare strings with both `'` and `""` quotation marks in them without having to escape either, as shown here. [source,javascript] ---- var text = `I'm ""amazed"" at these opportunities!` ---- One of the most appealing features of template literals is their ability to interpolate JavaScript expressions. ==== String Interpolation With (((""template literals"", ""string interpolation"", id=""temp2si"")))(((""string interpolation"", id=""si2"")))template literals, you're able to interpolate any JavaScript expressions inside your templates. When the template literal expression is reached, it's evaluated and you get back the compiled result. The following example interpolates a `name` variable into a template literal. [source,javascript] ---- var name = 'Shannon' var text = `Hello, ${ name }!` console.log(text) // <- 'Hello, Shannon!' ---- We've already established that you can use any JavaScript expressions, and not just variables. You can think of each expression in a template literal as defining a variable before the template runs, and then concatenating each variable with the rest of the string. However, the code becomes easier to maintain because it doesn't involve manually concatenating strings and JavaScript expressions. The variables you use in those expressions, the functions you call, and so on, should all be available to the current scope. It will be up to your coding style guides to decide how much logic you want to cram into the interpolation expressions. The following code snippet, for example, instantiates a `Date` object and formats it into a human-readable date inside a template literal. [source,javascript] ---- `The time and date is ${ new Date().toLocaleString() }.` // <- 'the time and date is 8/26/2017, 3:15:20 PM' ---- You could interpolate mathematical operations. [source,javascript] ---- `The result of 2+3 equals ${ 2 + 3 }` // <- 'The result of 2+3 equals 5' ---- You could even nest template literals, as they are also valid JavaScript expressions. [source,javascript] ---- `This template literal ${ `is ${ 'nested' }` }!` // <- 'This template literal is nested!' ---- Another perk of template literals is their multiline string representation (((""template literals"", ""string interpolation"", startref=""temp2si"")))(((""string interpolation"", startref=""si2"")))support. ==== Multiline Template Literals Before (((""template literals"", ""multiline string representation"", id=""templ2msr"")))(((""multiline strings"", id=""ms2"")))(((""strings, multiline"", id=""sm2"")))template literals, if you wanted to represent strings in multiple lines of JavaScript, you had to resort to escaping, concatenation, arrays, or even elaborate hacks using comments. The following snippet summarizes some of the most common multiline string representations prior to ES6. [source,javascript] ---- var escaped = 'The first line\\n\\ A second line\\n\\ Then a third line' var concatenated = 'The first line\\n' + 'A second line\\n' + 'Then a third line' var joined = [ 'The first line', 'A second line', 'Then a third line' ].join('\\n') ---- Under ES6, you could use backticks instead. Template literals support multiline strings by default. Note how there are no `\\n` escapes, no concatenation, and no arrays involved. [source,javascript] ---- var multiline = `The first line A second line Then a third line` ---- Multiline strings really shine when you have, for instance, a chunk of HTML you want to interpolate some variables into. If you need to display a list within the template, you could iterate the list, mapping its items into the corresponding markup, and then return the joined result from an interpolated expression. This makes it a breeze to declare subcomponents within your templates, as shown in the following piece of code. [source,javascript] ---- var book = { title: 'Modular ES6', excerpt: 'Here goes some properly sanitized HTML', tags: ['es6', 'template-literals', 'es6-in-depth'] } var html = `

${ book.title }

${ book.excerpt }
    ${ book.tags .map(tag => `
  • ${ tag }
  • `) .join('\\n ') }
` ---- The template we've just prepared would produce output like what's shown in the following snippet of code. Note how spacing was preserved,footnoteref:[multi-line-indentation,When using multiline template literals, spacing isn't preserved automatically. However, in many cases we can provide just enough indentation to make it work. Be wary of indented code blocks that may result in undesired indentation due to our code block being nested.] and how `
  • ` tags are properly indented thanks to how we joined them together using a few spaces. [source,html] ----

    Modular ES6

    Here goes some properly sanitized HTML
    • es6
    • template-literals
    • es6-in-depth
    ---- A downside when it comes to multiline template literals is indentation. The following example shows a typically indented piece of code with a template literal contained in a function. While we may have expected no indentation, the string has four spaces of indentation. [source,javascript] ---- function getParagraph() { return ` Dear Rod, This is a template literal string that's indented four spaces. However, you may have expected for it to be not indented at all. Nico ` } ---- While not ideal, we could get away with a utility function to remove indentation from each line in the resulting string. [source,javascript] ---- function unindent(text) { return text .split('\\n') .map(line => line.slice(4)) .join('\\n') .trim() } ---- Sometimes, it might be a good idea to pre-process the results of interpolated expressions before inserting them into your templates. For these advanced kinds of use cases, it's possible to use another feature of template literals called _tagged templates_.(((""template literals"", ""multiline string representation"", startref=""templ2msr"")))(((""multiline strings"", startref=""ms2"")))(((""strings, multiline"", startref=""sm2""))) ==== Tagged Templates By (((""template literals"", ""tagged templates"", id=""tl2tt"")))(((""tagged templates"", id=""tt2"")))default, JavaScript interprets `\\` as an escape character with special meaning. For example, `\\n` is interpreted as a newline, `\\u00f1` is interpreted as `ñ`, etc. You could avoid these rules using the `String.raw` tagged template. The next snippet shows a template literal using `String.raw`, which prevents `\\n` from being interpreted as a newline. [source,javascript] ---- var text = String.raw`""\\n"" is taken literally. It'll be escaped instead of interpreted.` console.log(text) // ""\\n"" is taken literally. // It'll be escaped instead of interpreted. ---- The `String.raw` prefix we've added to our template literal is a tagged template. It's used to parse the template. Tagged templates receive a parameter with an array containing the static parts of the template, as well as the result of evaluating each expression, each in its own parameter. As an example, consider the tagged template literal in the next code snippet. [source,javascript] ---- tag`Hello, ${ name }. I am ${ emotion } to meet you!` ---- That tagged template expression would, in practice, be translated into the following function call. [source,javascript] ---- tag( ['Hello, ', '. I am ', ' to meet you!'], 'Maurice', 'thrilled' ) ---- The resulting string is built by taking each part of the template and placing one of the expressions next to it, until there are no more parts of the template left. It might be hard to interpret the argument list without looking at a potential implementation of the default template literal `tag`, so let's do that. The following snippet of code shows a possible implementation of the default `tag`. It provides the same functionality as a template literal does when a tagged template isn't explicitly provided. It reduces the `parts` array into a single value, the result of evaluating the template literal. The result is initialized with the first `part`, and then each other `part` of the template is preceded by one of the `values`. We've used the rest parameter syntax for `...values` in order to make it easier to grab the result of evaluating each expression in the template. We're using an arrow function with an implicit `return` statement, given that its expression is relatively simple. [source,javascript] ---- function tag(parts, ...values) { return parts.reduce( (all, part, index) => all + values[index - 1] + part ) } ---- You can try the `tag` template using code like in the following snippet. You'll notice you get the same output as if you omitted `tag`, since we're copying the default behavior. [source,javascript] ---- var name = 'Maurice' var emotion = 'thrilled' var text = tag`Hello, ${ name }. I am ${ emotion } to meet you!` console.log(text) // <- 'Hello, Maurice. I am thrilled to meet you!' ---- Multiple use cases apply to tagged templates. One possible use case might be to make user input uppercase, making the string sound satirical. That's what the following piece of code does. We've modified `tag` slightly so that any interpolated strings are uppercased. [source,javascript] ---- function upper(parts, ...values) { return parts.reduce((all, part, index) => all + values[index - 1].toUpperCase() + part ) } var name = 'Maurice' var emotion = 'thrilled' upper`Hello, ${ name }. I am ${ emotion } to meet you!` // <- 'Hello, MAURICE. I am THRILLED to meet you!' ---- A decidedly more useful use case would be to sanitize expressions interpolated into your templates, automatically, using a tagged template. Given a template where all expressions are considered user input, we could use a hypothetical `sanitize` library to remove HTML tags and similar hazards, preventing cross-site scripting (XSS) attacks where users might inject malicious HTML into our websites. [source,javascript] ---- function sanitized(parts, ...values) { return parts.reduce((all, part, index) => all + sanitize(values[index - 1]) + part ) } var comment = 'Evil comment' var html = sanitized`
    ${ comment }
    ` console.log(html) // <- '
    Evil comment
    ' ---- Phew, (((""template literals"", ""tagged templates"", startref=""tl2tt"")))(((""tagged templates"", startref=""tt2"")))(((""template literals"", startref=""templ2"")))that malicious `