text,length,is_long_context,metric_val,label_metric "//// 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. //// = TinkerPop 3.3.0 image::https://raw.githubusercontent.com/apache/tinkerpop/master/docs/static/images/gremlin-mozart.png[width=225] *Gremlin Symphony #40 in G Minor* == TinkerPop 3.3.5 *Release Date: January 2, 2019* Please see the link:https://github.com/apache/tinkerpop/blob/3.3.5/CHANGELOG.asciidoc#release-3-3-5[changelog] for a complete list of all the modifications that are part of this release. === Upgrading for Users ==== AnonymousTraversalSource The `AnonymousTraversalSource` provides for a more unified syntax for `TraversalSource` construction by placing greater user emphasis on the creation of the source rather than the `Graph` it is connected to. It has a number of different static `traversal()` methods available and when imported as: [source,java] import static org.apache.tinkerpop.gremlin.process.traversal.AnonymousTraversalSource.traversal; allows `TraversalSource` construction syntax such as: [source,text] ---- gremlin> g = traversal().withGraph(TinkerFactory.createModern()) ==>graphtraversalsource[tinkergraph[vertices:6 edges:6], standard] gremlin> g = traversal().withRemote('conf/remote-graph.properties') ==>graphtraversalsource[emptygraph[empty], standard] gremlin> g = traversal().withRemote(DriverRemoteConnection.using('localhost',8182)) ==>graphtraversalsource[emptygraph[empty], standard] ---- Typically, this syntax is used for ""remote"" traversal construction for bytecode based requests, but has the option to bind a local `Graph` instance to it as well. It doesn't save much typing to do so obviously, so it may not be best used in that situation. Python, Javascript and .NET have similar syntax. See: link:https://issues.apache.org/jira/browse/TINKERPOP-2078[TINKERPOP-2078] ==== Bytecode Command The Gremlin Console now has a new `:bytecode` command to help users work more directly with Gremlin bytecode. The command is more of a debugging tool than something that would be used for every day purposes. It is sometimes helpful to look at Gremlin bytecode directly and the process for viewing it in human readable format is not a single step process. It is also not immediately clear how to convert bytecode to a Gremlin string. The `:bytecode` command aims to help with both of these issues: [source,text] ---- gremlin> g = TinkerFactory.createModern().traversal() ==>graphtraversalsource[tinkergraph[vertices:6 edges:6], standard] gremlin> :bytecode from g.V().out('knows') <1> ==>{""@type"":""g:Bytecode"",""@value"":{""step"":[[""V""],[""out"",""knows""]]}} gremlin> :bytecode translate g {""@type"":""g:Bytecode"",""@value"":{""step"":[[""V""],[""out"",""knows""]]}} <2> ==>g.V().out(""knows"") ---- See: link:https://issues.apache.org/jira/browse/TINKERPOP-2050[TINKERPOP-2050], link:http://tinkerpop.apache.org/docs/3.3.5/reference/#_console_commands[Reference Documentation - Console Commands] ==== Configurable Class Map Cache The ""class map"" cache in Gremlin Server (specifically the `GremlinGroovyScriptEngine`) that holds compiled scripts is now fully configurable via the `GroovyCompilerGremlinPlugin.classMapCacheSpecification`. See: link:https://issues.apache.org/jira/browse/TINKERPOP-2038[TINKERPOP-2038], link:http://tinkerpop.apache.org/docs/3.3.5/reference/#gremlin-server-cache[Reference Documentation - Cache Management] === Upgrading for Providers ==== Graph Database Providers ===== OptOut on GraphProvider It is not uncommon for those utilizing the TinkerPop test suite to have multiple configurations of their graph under test. The multiple configurations typically manifest as multiple `GraphProvider` implementations which supply the different configurations to test. It is sometimes the case, that a particular `Graph` configuration cannot support all of the tests in the suite at which point some less than straightforward approaches to dealing with that present as solutions. It has always been possible to apply an `OptOut` annotation to a `Graph` instance, to avoid a particular test execution. It is now possible to apply that same `OptOut` to a `GraphProvider` instance for that same purpose. Hopefully, this feature will make multiple configuration testing easier. == TinkerPop 3.3.4 *Release Date: October 15, 2018* Please see the link:https://github.com/apache/tinkerpop/blob/3.3.4/CHANGELOG.asciidoc#release-3-3-4[changelog] for a complete list of all the modifications that are part of this release. === Upgrading for Users ==== Introducing Order.asc and Order.desc The `Order` enum originally introduced `incr` for ascending order and `decr` for descending order. It's not clear why they were named this way when common querying parlance would call for `asc` and `desc` for those respective cases. Note that `incr` and `decr` have not been removed - just deprecated and thus marked for future removal. Prefer `asc` and `desc` going forward when writing Gremlin and look to update existing code using the deprecated values. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1956[TINKERPOP-1956] ==== TimedInterrupt In Gremlin Server, it is best not to use the `timedInterrupt` option on `GroovyCompilerGremlinPlugin` because it can compete with the `scriptEvaluationTimeout` setting and produce a different error path. Simply rely on `scriptEvaluationTimeout` as it covers both script evaluation time and result iteration time. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1778[TINKERPOP-1778] == TinkerPop 3.3.3 *Release Date: May 8, 2018* Please see the link:https://github.com/apache/tinkerpop/blob/3.3.3/CHANGELOG.asciidoc#release-3-3-3[changelog] for a complete list of all the modifications that are part of this release. === Upgrading for Users ==== Credential DSL Changes The Credential DSL has been modified to work as a standard Java-based Gremlin DSL. The now deprecated old approach used a ""graph wrapping"" style that was developed long before the link:http://tinkerpop.apache.org/docs/current/reference/#gremlin-java-dsl[recommended method] for building DSLs was published. Under this new model, the DSL is initialized via traversal as follows: [source,java] ---- CredentialTraversalSource credentials = graph.traversal(CredentialTraversalSource.class) credentials.user(""stephen"",""password"").iterate() credentials.users(""stephen"").valueMap().next() credentials.users().count().next() credentials.users(""stephen"").drop().iterate() ---- See: link:https://issues.apache.org/jira/browse/TINKERPOP-1903[TINKERPOP-1903], link:http://tinkerpop.apache.org/docs/3.3.2/reference/#security[Reference Documentation - Security] == TinkerPop 3.3.2 *Release Date: April 2, 2018* Please see the link:https://github.com/apache/tinkerpop/blob/3.3.2/CHANGELOG.asciidoc#release-3-3-2[changelog] for a complete list of all the modifications that are part of this release. === Upgrading for Users ==== Gremlin Python Sets Graph traversals that return a `Set` from Java are now coerced to a `List` in Python. This change ensures that Python results match Java results for the same traversal. It is possible to see this problem in prior versions of gremlin-python where a `Set` of numbers of different types are returned. In Java, a set of: [source,text] ---- [1,1.0d,2,2.0d] ---- would be deserialized to the following in Python: [source,text] ---- [1,2] ---- Now that the Java `Set` is coerced to a `List` in Gremin Python, the Java `Set` can be fully represented. Users who require a `Set` will need to manually convert their `List` to a `Set`. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1844[TINKERPOP-1844] == TinkerPop 3.3.1 *Release Date: December 17, 2017* Please see the link:https://github.com/apache/tinkerpop/blob/3.3.1/CHANGELOG.asciidoc#release-3-3-1[changelog] for a complete list of all the modifications that are part of this release. === Upgrading for Users ==== Gremlin Python path() There was a bug in GraphSON 3.0 serialization that prevented proper handling of results contain `Path` object. As a result, traversals that used and returned results from the `path()`-step in Python would return unusable results, but did not actually cause an exception condition. This problem is now resolved. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1799[TINKERPOP-1799] ==== Added `math()`-step for Scientific Traversal Computing `GraphTraversal.math(String)` was added. This step provides scientific calculator capabilities to a Gremlin traversal. [source,groovy] ---- gremlin> g.V().as('a').out('knows').as('b').math('a + b').by('age') ==>56.0 ==>61.0 gremlin> g.V().as('a').out('created').as('b'). ......1> math('b + a'). ......2> by(both().count().math('_ + 100')). ......3> by('age') ==>132.0 ==>133.0 ==>135.0 ==>138.0 gremlin> g.withSack(1).V(1).repeat(sack(sum).by(constant(1))).times(10).emit().sack().math('sin _') ==>0.9092974268256817 ==>0.1411200080598672 ==>-0.7568024953079282 ==>-0.9589242746631385 ==>-0.27941549819892586 ==>0.6569865987187891 ==>0.9893582466233818 ==>0.4121184852417566 ==>-0.5440211108893698 ==>-0.9999902065507035 ---- See: link:https://issues.apache.org/jira/browse/TINKERPOP-1632[TINKERPOP-1632] ==== Changed Typing on `from()` and `to()` The `from()` and `to()`-steps of `GraphTraversal` have a `Traversal` overload. The `E` has been changed to `?` in order to reduce `< >`-based coersion in strongly type Gremlin language variants. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1793[TINKERPOP-1793] ==== addV(traversal) and addE(traversal) The `GraphTraversal` and `GraphTraversalSource` methods of `addV()` and `addE()` have been extended to support dynamic label determination upon element creation. Both these methods can take a `Traversal` where the first `String` returned by the traversal is used as the label of the respective element. [source,groovy] ---- gremlin> g = TinkerFactory.createModern().traversal() ==>graphtraversalsource[tinkergraph[vertices:6 edges:6], standard] gremlin> g.addV(V().has('name','marko').label()). property('name','stephen') ==>v[13] gremlin> g.V().has('name','stephen').valueMap(true) ==>[name:[stephen],label:person,id:13] gremlin> g.V().has('name','stephen'). addE(V().hasLabel('software').inE().label()). to(V().has('name','lop')) ==>e[15][13-created->3] gremlin> g.V().has('name','stephen').outE().valueMap(true) ==>[label:created,id:15] gremlin> ---- See: link:https://issues.apache.org/jira/browse/TINKERPOP-1793[TINKERPOP-1793] ==== PageRankVertexProgram There were two major bugs in the way in which PageRank was being calculated in `PageRankVertexProgram`. First, teleportation energy was not being distributed correctly amongst the vertices at each round. Second, terminal vertices (i.e. vertices with no outgoing edges) did not have their full gathered energy distributed via teleportation. For users upgrading, note that while the relative rank orders will remain ""the same,"" the actual PageRank values will differ from prior TinkerPop versions. ``` VERTEX iGRAPH TINKERPOP marko 0.1119788 0.11375485828040575 vadas 0.1370267 0.14598540145985406 lop 0.2665600 0.30472082661863686 josh 0.1620746 0.14598540145985406 ripple 0.2103812 0.1757986539008437 peter 0.1119788 0.11375485828040575 ``` Normalization preserved through computation: ``` 0.11375485828040575 + 0.14598540145985406 + 0.30472082661863686 + 0.14598540145985406 + 0.1757986539008437 + 0.11375485828040575 ==>1.00000000000000018 ``` Two other additions to `PageRankVertexProgram` were provided as well. 1. It now calculates the vertex count and thus, no longer requires the user to specify the vertex count. 2. It now allows the user to leverage an epsilon-based convergence instead of having to specify the number of iterations to execute. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1783[TINKERPOP-1783] ==== IO Defaults While 3.3.0 released Gryo 3.0 and GraphSON 3.0 and these versions were defaulted in a number of places, it seems that some key defaults were missed. Specifically, calls to `Graph.io(graphson())` and `Graph.io(gryo())` were still using the old versions. The defaults have now been changed to ensure 3.0 is properly referenced in those cases. ==== Upgrade Neo4j See Neo4j's link:https://neo4j.com/guides/upgrade/[3.2 Upgrade FAQ] for a complete guide on how to upgrade from the previous 2.3.3 version. Also note that many of the configuration settings have link:https://neo4j.com/developer/kb/manually-migrating-configuration-settings-from-neo4j-2x-to-neo4j-3x/[changed from neo4j 2x to 3x] In particular, these properties referenced in TinkerPop documentation and configuration were renamed: [width=""100%"",cols=""2"",options=""header""] |========================================================= |Neo4j 2.3 (TinkerPop \\<= 3.3.0) |Neo4j 3.2 (TinkerPop 3.3.1) |node_auto_indexing |dbms.auto_index.nodes.enabled |relationship_auto_indexing |dbms.auto_index.relationships.enabled |ha.cluster_server |ha.host.coordination |ha.server |ha.host.data |========================================================= === Upgrading for Providers IMPORTANT: It is recommended that providers also review all the upgrade instructions specified for users. Many of the changes there may prove important for the provider's implementation. ==== Graph Database Providers ===== IO Version Check In the `Graph.io()` method, providers are to bootstrap the `Io` instance returned with their own custom serializers typically provided through a custom `IoRegistry` instance. Prior to this change it was not possible to easily determine the version of `Io` that was expected (nor was it especially necessary as TinkerPop didn't have breaking format changes between versions). As of 3.3.0 however, there could be IO test incompatibilities for some providers who need to register a different `IoRegistry` instance depending on the version the user wants. To allow for that check, the `Io` interface now has the following method: [source,java] ---- public boolean requiresVersion(final V version); ---- which allows the graph provider to check if a specific `GryoVersion` or `GraphSONVersion` is required. Using that information, the provider could then assign the right `IoRegistry` to match that. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1767[TINKERPOP-1767] == TinkerPop 3.3.0 *Release Date: August 21, 2017* Please see the link:https://github.com/apache/tinkerpop/blob/3.3.0/CHANGELOG.asciidoc#release-3-3-0[changelog] for a complete list of all the modifications that are part of this release. === Upgrading for Users ==== Packaged Data Files TinkerPop has always packaged sample graphs with its zip distributions. As of 3.3.0, the distributions will only include Gryo 3.0, GraphSON 3.0 and GraphML (which is unversioned) files. Other versions are not included, but could obviously be generated using the IO API directly. ==== GraphTraversal Has-Methods Re-Organized `GraphTraversal.hasXXX()`, where `XXX` is `Id`, `Label`, `Key`, `Value`, was faulty in that they relied on calling an intermediate method for flattening `Object[]` arguments and thus, yielding a non 1-to-1 correspondence between `GraphTraversal` and `Bytecode`. This has been remedied. Most users will not notice this change. Perhaps only some users that may use Java reflection over `GraphTraversal` might have a simple problem. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1520[TINKERPOP-1520] ==== Changes to IO ===== Gryo 3.0 With Gryo, TinkerPop skips version 2.0 and goes right to 3.0 (to maintain better parity with GraphSON versioning). Gryo 3.0 fixes a number of inconsistencies with Gryo 1.0 and hopefully marks a point where Gryo is better versioned over time. Gryo 3.0 is not compatible with Gryo 1.0 and is now the default version of Gryo exposed by TinkerPop in Gremlin Server and IO. It isn't hard to switch back to use of Gryo 1.0 if necessary. Here is the approach for writing an entire graph: [source,java] ---- Graph graph = TinkerFactory.createModern(); GryoMapper mapper = graph.io(IoCore.gryo()).mapper().version(GryoVersion.V1_0).create() try (OutputStream os = new FileOutputStream(""tinkerpop-modern.json"")) { graph.io(IoCore.gryo()).writer().mapper(mapper).create().writeGraph(os, graph) } final Graph newGraph = TinkerGraph.open(); try (InputStream stream = new FileInputStream(""tinkerpop-modern.json"")) { newGraph.io(IoCore.gryo()).reader().mapper(mapper).create().readGraph(stream, newGraph); } ---- Gremlin Server configurations don't include Gryo 1.0 by default: [source,yaml] ---- serializers: - { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV3d0, config: { ioRegistries: [org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV3d0] }} # application/vnd.gremlin-v3.0+gryo - { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV3d0, config: { serializeResultToString: true }} # application/vnd.gremlin-v3.0+gryo-stringd - { className: org.apache.tinkerpop.gremlin.driver.ser.GraphSONMessageSerializerV3d0, config: { ioRegistries: [org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV3d0] }} # application/json ---- but adding an entry as follows will add it back: [source,yaml] ---- serializers: - { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV1d0, config: { ioRegistries: [org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV1d0] }} # application/vnd.gremlin-v1.0+gryo - { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV3d0, config: { ioRegistries: [org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV3d0] }} # application/vnd.gremlin-v3.0+gryo - { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV3d0, config: { serializeResultToString: true }} # application/vnd.gremlin-v3.0+gryo-stringd - { className: org.apache.tinkerpop.gremlin.driver.ser.GraphSONMessageSerializerV3d0, config: { ioRegistries: [org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV3d0] }} # application/json ---- To use Gryo 1.0 with the Java driver, just specify the 1.0 serializer directly: [source,java] ---- GryoMapper.Builder builder = GryoMapper.build(). version(GryoVersion.V1_0). addRegistry(TinkerIoRegistryV1d0.instance()); Cluster cluster = Cluster.build().serializer(GryoMessageSerializerV1d0(builder)); ---- See: link:https://issues.apache.org/jira/browse/TINKERPOP-1698[TINKERPOP-1698] ===== GraphSON 3.0 GraphSON 3.0 finishes what GraphSON 2.0 began by taking the extra step to include the following types: `g:Map`, `g:List` and `g:Set`. With these types it is now possible to get expected Gremlin results in GLVs just as one would if using Java. This is especially true of the `g:Map` type, which allows non-string keys values, something not allowed in regular JSON maps. This allows for common traversals like `g.V().groupCount()` to work, where the traversal groups on a `Vertex` or some other complex object. Note that GraphSON 3.0 does not have an option to be without types. This was a feature of 1.0 and 2.0, but it is no longer supported. There is little point to such a feature as we see more movement toward GLVs, which require types, and less usage of scripts with custom parsing of results. Both TinkerGraph and Gremlin Server have been defaulted to work with GraphSON 3.0. For TinkerGraph this means that the following commands: [source,java] ---- Graph graph = TinkerFactory.createModern(); graph.io(IoCore.graphson()).writeGraph(""tinkerpop-modern.json""); final Graph newGraph = TinkerGraph.open(); newGraph.io(IoCore.graphson()).readGraph(""tinkerpop-modern.json""); ---- will write and read GraphSON 3.0 format rather than 1.0. To use 1.0 (or 2.0 for that matter) format simply set the `version()` on the appropriate builder methods: [source,java] ---- Graph graph = TinkerFactory.createModern(); GraphSONMapper mapper = graph.io(IoCore.graphson()).mapper().version(GraphSONVersion.V1_0).create() try (OutputStream os = new FileOutputStream(""tinkerpop-modern.json"")) { graph.io(IoCore.graphson()).writer().mapper(mapper).create().writeGraph(os, graph) } final Graph newGraph = TinkerGraph.open(); try (InputStream stream = new FileInputStream(""tinkerpop-modern.json"")) { newGraph.io(IoCore.graphson()).reader().mapper(mapper).create().readGraph(stream, newGraph); } ---- For Gremlin Server, this change means that the `application/json` mime type no longer returns GraphSON 1.0 without type embedding. Instead, Gremlin Server will return GraphSON 3.0 with partial types enabled (i.e. which is equivalent to `application/vnd.gremlin-v3.0+json`). The `serializers` section the sample Gremlin Server YAML files now typically look like this: [source,yaml] ---- serializers: - { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV3d0, config: { ioRegistries: [org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV3d0] }} # application/vnd.gremlin-v3.0+gryo - { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV3d0, config: { serializeResultToString: true }} # application/vnd.gremlin-v3.0+gryo-stringd - { className: org.apache.tinkerpop.gremlin.driver.ser.GraphSONMessageSerializerV3d0, config: { ioRegistries: [org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV1d0] }} # application/json ---- It is possible to bring back the original configuration for `application/json` by changing the last entry as follows: [source,yaml] ---- - { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV3d0, config: { ioRegistries: [org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV3d0] }} # application/vnd.gremlin-v3.0+gryo - { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV3d0, config: { serializeResultToString: true }} # application/vnd.gremlin-v3.0+gryo-stringd - { className: org.apache.tinkerpop.gremlin.driver.ser.GraphSONMessageSerializerV1d0, config: { ioRegistries: [org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV1d0] }} # application/json ---- See: link:https://issues.apache.org/jira/browse/TINKERPOP-1414[TINKERPOP-1414], link:https://issues.apache.org/jira/browse/TINKERPOP-1427[TINKERPOP-1427], link:https://issues.apache.org/jira/browse/TINKERPOP-1574[TINKERPOP-1574] ==== Graphite and Ganglia Graphite and Ganglia are no longer packaged with the Gremlin Server distribution. They are considered optional dependencies and therefore must be installed manually by the user. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1550[TINKERPOP-1550], link:http://tinkerpop.apache.org/docs/3.3.0/reference/#metrics[Reference Documentation - Metrics] ==== SelectStep Defaults to Pop.last `SelectStep` and `SelectOneStep` (`select()`) are the only `Scoping` steps that default to `Pop.mixed` as their labeled path selection criteria. All other steps, like `match()`, `where()` and `dedup()`, use `Pop.last`. In order to better enable optimizations around total `Pop.last` traversals, the `select()`-steps now default to `Pop.last`. Most users will not notice a difference as it is rare for repeated labels to be used in practice. However, formal backwards compatibility is possible as outlined below. Assuming that `x` is not a `Pop` argument: 1. Change all `select(x,y,z)` calls to `selectV3d2(x,y,z)` calls. 2. Change all `select(x,y,z)`-step calls to `select(Pop.mixed,x,y,z)`. If an explicit `Pop` argument is provided, then no changes are required. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1541[TINKERPOP-1541] ==== OptionalStep and Side-Effects The `optional()`-step was previously implemented using `ChooseStep`. However, if the optional branch contained side-effects, then unexpected behaviors can emerge. Thus, a potential backwards compatibility issue arises if side-effects were being used in `optional()`. However, the behavior would be unpredictable so this backwards incompatibility is desirable. See link:https://issues.apache.org/jira/browse/TINKERPOP-1506[TINKERPOP-1506] ==== Gremlin Console Initialization It is no longer possible to intialize the Gremlin Console with a script without use of `-e`. In other words, prior versions allowed: [source,text] bin/gremlin.sh gremlin.groovy Such a command must now be written as: [source,text] bin/gremlin.sh -i gremlin.groovy See: link:https://issues.apache.org/jira/browse/TINKERPOP-1283[TINKERPOP-1283], link:https://issues.apache.org/jira/browse/TINKERPOP-1651[TINKERPOP-1651] ==== GraphTraversal valueMap() Signature Updated `GraphTraversal.valueMap(includeTokens,propertyKeys...)` now returns a `Map` to account for the presence of `T.id` or `T.label` if you pass `true` to it. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1283[TINKERPOP-1483] ==== HADOOP_GREMLIN_LIBS and Spark The TinkerPop reference documentation has always mentioned that the `gremlin-spark` `/lib` directory needed to be added to `HADOOP_GREMLIN_LIBS` environment variable. In reality, that was not truly necessary. With Spark 1.x having `gremlin-spark` in `HADOOP_GREMLIN_LIBS` hasn't been a problem, but Spark 2.0 introduces a check for duplicate jars on the path which will cause job initialization to fail. As a result, going forward with TinkerPop 3.3.0, the `gremlin-spark` `lib` directory should not be included in `HADOOP_GREMLIN_LIBS`. ==== Deprecation Removal The following deprecated classes, methods or fields have been removed in this version: * `giraph-gremlin` ** `org.apache.tinkerpop.gremlin.giraph.groovy.plugin.GiraphGremlinPlugin` * `gremlin-console` ** `org.apache.tinkerpop.gremlin.console.Console(String)` ** `org.apache.tinkerpop.gremlin.console.ConsoleImportCustomizerProvider` ** `org.apache.tinkerpop.gremlin.console.plugin.*` ** `org.apache.tinkerpop.gremlin.console.groovy.plugin.DriverGremlinPlugin` ** `org.apache.tinkerpop.gremlin.console.groovy.plugin.DriverRemoteAcceptor` ** `org.apache.tinkerpop.gremlin.console.groovy.plugin.GephiGremlinPlugin` ** `org.apache.tinkerpop.gremlin.console.groovy.plugin.UtilitiesGremlinPlugin` * `gremlin-core` ** `org.apache.tinkerpop.gremlin.jsr223.CoreGremlinModule` ** `org.apache.tinkerpop.gremlin.jsr223.CoreGremlinPlugin#INSTANCE` ** `org.apache.tinkerpop.gremlin.jsr223.GremlinModule` ** `org.apache.tinkerpop.gremlin.jsr223.SingleGremlinScriptEngineManager#getInstance()` ** `org.apache.tinkerpop.gremlin.jsr223.GremlinScriptEngineManager#addModule(GremlinModule)` ** `org.apache.tinkerpop.gremlin.jsr223.console.PluginAcceptor` ** `org.apache.tinkerpop.gremlin.process.traversal.TraversalSource.Builder` ** `org.apache.tinkerpop.gremlin.process.traversal.util.ConnectiveP(P...)` ** `org.apache.tinkerpop.gremlin.process.traversal.util.AndP(P...)` ** `org.apache.tinkerpop.gremlin.process.traversal.util.OrP(P...)` ** `org.apache.tinkerpop.gremlin.process.traversal.util.TraversalScriptFunction` ** `org.apache.tinkerpop.gremlin.process.traversal.util.TraversalScriptHelper` ** `org.apache.tinkerpop.gremlin.process.traversal.Order.keyIncr` ** `org.apache.tinkerpop.gremlin.process.traversal.Order.valueIncr` ** `org.apache.tinkerpop.gremlin.process.traversal.Order.keyDecr` ** `org.apache.tinkerpop.gremlin.process.traversal.Order.valueIncr` ** `org.apache.tinkerpop.gremlin.process.traversal.dsl.GraphTraversal.mapKeys()` ** `org.apache.tinkerpop.gremlin.process.traversal.dsl.GraphTraversal.mapValues()` ** `org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal#addV(Object...)` ** `org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal#addE(Direction, String, String, Object...)` ** `org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal#addOutE(String, String, Object...)` ** `org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal#addInV(String, String, Object...)` ** `org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal#selectV3d2()` ** `org.apache.tinkerpop.gremlin.process.traversal.Bindings()` ** `org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource#withBindings(Bindings)` ** `org.apache.tinkerpop.gremlin.structure.Transaction.submit(Function)` ** `org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal#sack(BiFunction,String)` ** `org.apache.tinkerpop.gremlin.process.traversal.strategy.finalization.LazyBarrierStrategy` ** `org.apache.tinkerpop.gremlin.process.traversal.TraversalSideEffects` (various methods) ** `org.apache.tinkerpop.gremlin.process.computer.traversal.step.VertexComputing#generateComputer(Graph)` ** `org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal#groupV3d0(String)` ** `org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal#groupV3d0()` ** `org.apache.tinkerpop.gremlin.structure.Graph.Features.VertexPropertyFeatures#supportsAddProperty()` ** `org.apache.tinkerpop.gremlin.structure.Graph.Features.VertexPropertyFeatures#FEATURE_ADD_PROPERTY` ** `org.apache.tinkerpop.gremlin.structure.Graph.OptIn#SUITE_GROOVY_PROCESS_STANDARD` ** `org.apache.tinkerpop.gremlin.structure.Graph.OptIn#SUITE_GROOVY_PROCESS_COMPUTER` ** `org.apache.tinkerpop.gremlin.structure.Graph.OptIn#SUITE_GROOVY_ENVIRONMENT` ** `org.apache.tinkerpop.gremlin.structure.Graph.OptIn#SUITE_GROOVY_ENVIRONMENT_INTEGRATE` ** `org.apache.tinkerpop.gremlin.structure.io.Io.Builder#registry(IoRegistry)` ** `org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONMapper.Builder#embedTypes(boolean)` ** `org.apache.tinkerpop.gremlin.structure.Transaction.submit(Function)` ** `org.apache.tinkerpop.gremlin.structure.util.detached.DetachedEdge(Object,String,Map,Pair,Pair)` ** `org.apache.tinkerpop.gremlin.util.CoreImports` ** `org.apache.tinkerpop.gremlin.util.ScriptEngineCache` ** `org.apache.tinkerpop.gremlin.process.computer.util.ConfigurationTraversal` * `gremlin-driver` ** `org.apache.tinkerpop.gremlin.driver.Cluster$Builder#reconnectIntialDelay(int)` ** `org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV1d0(GryoMapper)` ** `org.apache.tinkerpop.gremlin.driver.ser.AbstractGraphSONMessageSerializerV2d0#TOKEN_USE_MAPPER_FROM_GRAPH` ** `org.apache.tinkerpop.gremlin.driver.ser.AbstractGryoSONMessageSerializerV2d0#TOKEN_USE_MAPPER_FROM_GRAPH` * `gremlin-groovy` ** `org.apache.tinkerpop.gremlin.groovy.AbstractImportCustomizerProvider` ** `org.apache.tinkerpop.gremlin.groovy.CompilerCustomizerProvider` ** `org.apache.tinkerpop.gremlin.groovy.DefaultImportCustomizerProvider` ** `org.apache.tinkerpop.gremlin.groovy.EmptyImportCustomizerProvider` ** `org.apache.tinkerpop.gremlin.groovy.ImportCustomizerProvider` ** `org.apache.tinkerpop.gremlin.groovy.NoImportCustomizerProvider` ** `org.apache.tinkerpop.gremlin.groovy.engine.ConcurrentBindings` ** `org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor#build(String,List,List,List,Map)` ** `org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor#getScriptEngines()` ** `org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor#getGlobalBindings()` ** `org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor.Builder#enabledPlugins(Set)` ** `org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor.Builder#addEngineSettings(String,List,List,List,Map)` ** `org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor.Builder#engineSettings(Map)` ** `org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor.Builder#use(List)` ** `org.apache.tinkerpop.gremlin.groovy.engine.ScriptEngines` ** `org.apache.tinkerpop.gremlin.groovy.function.*` ** `org.apache.tinkerpop.gremlin.groovy.plugin.*` ** `org.apache.tinkerpop.gremlin.groovy.plugin.credential.*` ** `org.apache.tinkerpop.gremlin.groovy.jsr223.DependencyManager` ** `org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine(ImportCustomizerProvider)` ** `org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine(CompilerCustomizerProvider)` ** `org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine#plugins()` ** `org.apache.tinkerpop.gremlin.groovy.jsr223.ScriptExecutor` ** `org.apache.tinkerpop.gremlin.groovy.jsr223.ScriptEnginePluginAcceptor` ** `org.apache.tinkerpop.gremlin.groovy.jsr223.customizer.SandboxExtension` ** `org.apache.tinkerpop.gremlin.groovy.jsr223.customizer.*` ** `org.apache.tinkerpop.gremlin.groovy.util.DependencyGrabber#deleteDependenciesFromPath(org.apache.tinkerpop.gremlin.groovy.plugin.Artifact)` ** `org.apache.tinkerpop.gremlin.groovy.util.DependencyGrabber#copyDependenciesToPath(org.apache.tinkerpop.gremlin.groovy.plugin.Artifact)` * `gremlin-python` ** `org.apache.tinkerpop.gremlin.python.jsr223.GremlinJythonScriptEngine#()` * `gremlin-server` ** `org.apache.tinkerpop.gremlin.server.GremlinServer(ServerGremlinExecutor)` ** `org.apache.tinkerpop.gremlin.server.Settings#plugins` ** `org.apache.tinkerpop.gremlin.server.auth.AllowAllAuthenticator.newSaslNegotiator()` ** `org.apache.tinkerpop.gremlin.server.auth.Authenticator.newSaslNegotiator()` ** `org.apache.tinkerpop.gremlin.server.auth.Krb5Authenticator.newSaslNegotiator()` ** `org.apache.tinkerpop.gremlin.server.auth.SimpleAuthenticator.newSaslNegotiator()` ** `org.apache.tinkerpop.gremlin.server.handler.IteratorHandler` ** `org.apache.tinkerpop.gremlin.server.handler.NioGremlinResponseEncoder` ** `org.apache.tinkerpop.gremlin.server.handler.WsGremlinResponseEncoder` ** `org.apache.tinkerpop.gremlin.server.handler.OpSelectorHandler.errorMeter` ** `org.apache.tinkerpop.gremlin.server.op.control.*` ** `org.apache.tinkerpop.gremlin.server.op.AbstractEvalOpProcessor.errorMeter` ** `org.apache.tinkerpop.gremlin.server.op.AbstractEvalOpProcessor.validBindingName` ** `org.apache.tinkerpop.gremlin.server.op.session.Session.kill()` ** `org.apache.tinkerpop.gremlin.server.op.session.Session.manualkill()` * `hadoop-gremlin` ** `org.apache.tinkerpop.gremlin.hadoop.Constants#GREMLIN_HADOOP_GRAPH_INPUT_FORMAT` ** `org.apache.tinkerpop.gremlin.hadoop.Constants#GREMLIN_HADOOP_GRAPH_OUTPUT_FORMAT` ** `org.apache.tinkerpop.gremlin.hadoop.Constants#GREMLIN_HADOOP_GRAPH_INPUT_FORMAT_HAS_EDGES` ** `org.apache.tinkerpop.gremlin.hadoop.Constants#GREMLIN_HADOOP_GRAPH_OUTPUT_FORMAT_HAS_EDGES` ** `org.apache.tinkerpop.gremlin.hadoop.Constants#GREMLIN_SPARK_GRAPH_INPUT_RDD` ** `org.apache.tinkerpop.gremlin.hadoop.Constants#GREMLIN_SPARK_GRAPH_OUTPUT_RDD` * `spark-gremlin` ** `org.apache.tinkerpop.gremlin.spark.groovy.plugin.SparkGremlinPlugin` * `tinkergraph-gremlin` ** `org.apache.tinkerpop.gremlin.tinkergraph.groovy.plugin.TinkerGraphGremlinPlugin` ** `org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph#CONFIG_*` ** `org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistry` ** `org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV1d0#getInstance()` ** `org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV2d0#getInstance()` Please see the javadoc deprecation notes or upgrade documentation specific to when the deprecation took place to understand how to resolve this breaking change. See: link:https://issues.apache.org/jira/browse/TINKERPOP-832[TINKERPOP-832], link:https://issues.apache.org/jira/browse/TINKERPOP-833[TINKERPOP-833], link:https://issues.apache.org/jira/browse/TINKERPOP-834[TINKERPOP-834], link:https://issues.apache.org/jira/browse/TINKERPOP-999[TINKERPOP-999], link:https://issues.apache.org/jira/browse/TINKERPOP-1010[TINKERPOP-1010], link:https://issues.apache.org/jira/browse/TINKERPOP-1028[TINKERPOP-1028], link:https://issues.apache.org/jira/browse/TINKERPOP-1040[TINKERPOP-1040], link:https://issues.apache.org/jira/browse/TINKERPOP-1046[TINKERPOP-1046], link:https://issues.apache.org/jira/browse/TINKERPOP-1049[TINKERPOP-1049], link:https://issues.apache.org/jira/browse/TINKERPOP-1142[TINKERPOP-1142], link:https://issues.apache.org/jira/browse/TINKERPOP-1169[TINKERPOP-1169], link:https://issues.apache.org/jira/browse/TINKERPOP-1171[TINKERPOP-1171], link:https://issues.apache.org/jira/browse/TINKERPOP-1275[TINKERPOP-1275], link:https://issues.apache.org/jira/browse/TINKERPOP-1283[TINKERPOP-1283], link:https://issues.apache.org/jira/browse/TINKERPOP-1289[TINKERPOP-1289], link:https://issues.apache.org/jira/browse/TINKERPOP-1291[TINKERPOP-1291], link:https://issues.apache.org/jira/browse/TINKERPOP-1420[TINKERPOP-1420], link:https://issues.apache.org/jira/browse/TINKERPOP-1421[TINKERPOP-1421], link:https://issues.apache.org/jira/browse/TINKERPOP-1465[TINKERPOP-1465], link:https://issues.apache.org/jira/browse/TINKERPOP-1481[TINKERPOP-1481], link:https://issues.apache.org/jira/browse/TINKERPOP-1526[TINKERPOP-1526], link:https://issues.apache.org/jira/browse/TINKERPOP-1603[TINKERPOP-1603], link:https://issues.apache.org/jira/browse/TINKERPOP-1612[TINKERPOP-1612], link:https://issues.apache.org/jira/browse/TINKERPOP-1622[TINKERPOP-1622], link:https://issues.apache.org/jira/browse/TINKERPOP-1651[TINKERPOP-1651], link:https://issues.apache.org/jira/browse/TINKERPOP-1694[TINKERPOP-1694], link:https://issues.apache.org/jira/browse/TINKERPOP-1700[TINKERPOP-1700], link:https://issues.apache.org/jira/browse/TINKERPOP-1706[TINKERPOP-1706], link:https://issues.apache.org/jira/browse/TINKERPOP-1721[TINKERPOP-1721], link:https://issues.apache.org/jira/browse/TINKERPOP-1719[TINKERPOP-1719], link:https://issues.apache.org/jira/browse/TINKERPOP-1720[TINKERPOP-1720], link:https://issues.apache.org/jira/browse/TINKERPOP-880[TINKERPOP-880], link:https://issues.apache.org/jira/browse/TINKERPOP-1170[TINKERPOP-1170], link:https://issues.apache.org/jira/browse/TINKERPOP-1729[TINKERPOP-1729] ==== Gremlin-server.sh and Init Scripts `gremlin-server.sh` is now also an init script and can no longer be started without parameters. To start it in the foreground with defaults like previous usage, please use the `console` parameter. Also, `gremlin-server.sh` will continue to start in the foreground when provided a yaml configuration file. How to install as a service has been added to the link:http://tinkerpop.apache.org/docs/3.3.0/reference/#_as_a_service[Reference Documentation - As A Service]. The switch name has changed for installing dependencies. `-i` has been deprecated and replaced by `install`. See: link:https://issues.apache.org/jira/browse/TINKERPOP-980[TINKERPOP-980], link:http://tinkerpop.apache.org/docs/3.3.0/reference/#_configuring_2[Reference Documentation - Server Configuration]. ==== Removal of useMapperFromGraph The `userMapperFromGraph` serialization configuration option was used to allow the IO configurations of a specific graph to be assigned to a specific serializer. This feature has been removed completely now. Please use the `ioRegistries` configuration option to add one or more specific `Graph` serialization capabilities to a serializer. [source,yaml] ---- serializers: - { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV1d0, config: { ioRegistries: [org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV1d0] }} # application/vnd.gremlin-v1.0+gryo ---- see: link:https://issues.apache.org/jira/browse/TINKERPOP-1699[TINKERPOP-1699] ==== Gremlin-server.bat The switch name has changed for installing dependencies. `-i` has been deprecated and replaced by `install`. ==== SparkGraphComputer GryoRegistrator Historically, `SparkGraphComputer` has used `GryoSerializer` to handle the serialization of objects in Spark. The reason this exists is because TinkerPop uses a shaded version of Kryo and thus, couldn't use the standard `KryoSerializer`-model provided by Spark. However, a ""shim model"" was created which allows for the shaded and unshaded versions of Kryo to interact with one another. To this end, `KryoSerializer` can now be used with a `GryoRegistrator`. The properties file for a `SparkGraphComputer` now looks as follows: ``` spark.serializer=org.apache.spark.serializer.KryoSerializer spark.kryo.registrator=org.apache.tinkerpop.gremlin.spark.structure.io.gryo.GryoRegistrator ``` If the old `GryoSerializer` model is desired, then the properties file should simply look as before: ``` spark.serializer=org.apache.tinkerpop.gremlin.spark.structure.io.gryo.GryoSerializer ``` See: link:https://issues.apache.org/jira/browse/TINKERPOP-1389[TINKERPOP-1389] ==== ScriptInputFormat The API for the script provided to a `ScriptInputFormat` has changed slightly. The signature for `parse(line, factory)` is now simply `parse(line)`. The inclusion of `factory` was deprecated in 3.1.2. Instead of using the {{factory}} to get the {{StarGraph}} there is a {{graph}} variable in the glocal context of the script. Simply use that directly in the script. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1137[TINKERPOP-1137], link:http://tinkerpop.apache.org/docs/3.3.0-SNAPSHOT/reference/#script-io-format[Reference Documentation - Script I/O Format] === Upgrading for Providers IMPORTANT: It is recommended that providers also review all the upgrade instructions specified for users. Many of the changes there may prove important for the provider's implementation. ==== Graph System Providers ===== GremlinPlugin The previously deprecated `GremlinPlugin` system has been removed. The old `GremlinPlugin` interface formerly resided in the `org.apache.tinkerpop.gremlin.groovy.plugin` package of `gremlin-groovy`. This interface was replaced by an interface of the same name in 3.2.4, which now resides in the `org.apache.tinkerpop.gremlin.jsr223` package in `gremlin-core`. Obviously, existing plugins will need to be updated to use this new interface. The plugin model has changed slightly to be more generic and not specifically bound to Groovy based script engines. Under the new model, the plugin simply returns `Customizer` instances that can be applied generically to any `ScriptEngine` or specifically to a particular `ScriptEngine`. More details can be found in the link:http://tinkerpop.apache.org/docs/x.y.z/dev/provider/#gremlin-plugins[Provider Documentation] ==== Graph Database Providers ===== Test Suite Removal A number of test suites that were previously deprecated have been removed which should reduce the burden on graph providers who are implementing TinkerPop. Test suites related to perfrmance based on `junit-benchmarks` have been removed as have the suites in `gremlin-groovy-test` (in fact, this entire module has been removed). Specifically, providers should be concerned with breaking changes related to the removal of: * `StructurePerformanceSuite` * `ProcessPerformanceSuite` * `GroovyEnvironmentPerformanceSuite` * `GroovyProcessStandardSuite` * `GroovyProcessComputerSuite` * `GroovyEnvironmentSuite` * `GroovyEnvironmentIntegrateSuite` Those graph providers who relied on these tests should simply remove them from their respective test suites. Beware of `OptOut` annotations that reference tests in these suites as test failure will occur if those references are not removed. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1235[TINKERPOP-1235], link:https://issues.apache.org/jira/browse/TINKERPOP-1612[TINKERPOP-1612] ===== TransactionException The `AbstractTransaction.TransactionException` class is now just `TransactionException` which extends `RuntimeExcetpion` rather than `Exception`. Providers should consider using this exception to wrap their own on calls to `Transaction.commit()` or `Transaction.rollback()`. By throwing this exception, the TinkerPop stack can better respond to transaction problems and it allows for more common, generalized error handling for users. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1004[TINKERPOP-1004] ==== Driver Providers ===== SASL Byte Array Gremlin Server no longer supports accepting a byte array for the value passed to the ""sasl"" parameter in authentication messages. It only accepts a Base64 encoded string. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1603[TINKERPOP-1603] ",12391,True,2547.040514719774,median "[[configuration-interfaces]] == Configure traffic capturing options //TODO: Break this file down into multiple source files (one for each html page) ++++ Traffic sniffing ++++ There are two main ways of deploying Packetbeat: * On dedicated servers, getting the traffic from mirror ports or tap devices. * On your existing application servers. The first option has the big advantage that there is no overhead of any kind on your application servers. But it requires dedicated networking gear, which is generally not available on cloud setups. In both cases, the sniffing performance (reading packets passively from the network) is very important. In the case of a dedicated server, better sniffing performance means that less hardware is required. When Packetbeat is installed on an existing application server, better sniffing performance means less overhead. Currently Packetbeat has several options for traffic capturing: * `pcap`, which uses the libpcap library and works on most platforms, but it's not the fastest option. * `af_packet`, which uses memory mapped sniffing. This option is faster than libpcap and doesn't require a kernel module, but it's Linux-specific. The `af_packet` option, also known as ""memory-mapped sniffing,"" makes use of a Linux-specific https://www.kernel.org/doc/Documentation/networking/packet_mmap.txt[feature]. This could be the optimal sniffing mode for both the dedicated server and when Packetbeat is deployed on an existing application server. The way it works is that both the kernel and the user space program map the same memory zone, and a simple circular buffer is organized in this memory zone. The kernel writes packets into the circular buffer, and the user space program reads from it. The poll system call is used for getting a notification for the first packet available, but the remaining available packets can be simply read via memory access. The `af_packet` sniffer can be further tuned to use more memory in exchange for better performance. The larger the size of the circular buffer, the fewer system calls are needed, which means that fewer CPU cycles are consumed. The default size of the buffer is 30 MB, but you can increase it like this: [source,yaml] ------------------------------------------------------------------------------ packetbeat.interfaces.device: eth0 packetbeat.interfaces.type: af_packet packetbeat.interfaces.buffer_size_mb: 100 ------------------------------------------------------------------------------ [float] === Sniffing configuration options You can specify the following options in the `packetbeat.interfaces` section of the +{beatname_lc}.yml+ config file. Here is an example configuration: [source,yaml] ------------------------------------------------------------------------------ packetbeat.interfaces.device: any packetbeat.interfaces.snaplen: 1514 packetbeat.interfaces.type: af_packet packetbeat.interfaces.buffer_size_mb: 100 ------------------------------------------------------------------------------ [float] ==== `device` The network device to capture traffic from. The specified device is set automatically to promiscuous mode, meaning that Packetbeat can capture traffic from other hosts on the same LAN. Example: [source,yaml] ------------------------------------------------------------------------------ packetbeat.interfaces.device: eth0 ------------------------------------------------------------------------------ On Linux, you can specify `any` for the device, and Packetbeat captures all messages sent or received by the server where Packetbeat is installed. NOTE: When you specify `any` for the device, the interfaces are not set to promiscuous mode. The `device` option also accepts specifying the device by its index in the list of devices available for sniffing. To obtain the list of available devices, run Packetbeat with the following command: [""source"",""sh"",subs=""attributes,callouts""] ---------------------------------------------------------------------- packetbeat devices ---------------------------------------------------------------------- This command returns a list that looks something like the following: [""source"",""sh"",subs=""attributes,callouts""] ---------------------------------------------------------------------- 0: en0 (No description available) 1: awdl0 (No description available) 2: bridge0 (No description available) 3: fw0 (No description available) 4: en1 (No description available) 5: en2 (No description available) 6: p2p0 (No description available) 7: en4 (No description available) 8: lo0 (No description available) ---------------------------------------------------------------------- The following example sets up sniffing on the first interface in the list: [source,yaml] ------------------------------------------------------------------------------ packetbeat.interfaces.device: 0 ------------------------------------------------------------------------------ Specifying the index is especially useful on Windows where device names can be long. [float] ==== `snaplen` The maximum size of the packets to capture. The default is 65535, which is large enough for almost all networks and interface types. If you sniff on a physical network interface, the optimal setting is the MTU size. On virtual interfaces, however, it's safer to accept the default value. Example: [source,yaml] ------------------------------------------------------------------------------ packetbeat.interfaces.device: eth0 packetbeat.interfaces.snaplen: 1514 ------------------------------------------------------------------------------ [float] ==== `type` Packetbeat supports these sniffer types: * `pcap`, which uses the libpcap library and works on most platforms, but it's not the fastest option. * `af_packet`, which uses memory-mapped sniffing. This option is faster than libpcap and doesn't require a kernel module, but it's Linux-specific. The default sniffer type is `pcap`. Here is an example configuration that specifies the `af_packet` sniffing type: [source,yaml] ------------------------------------------------------------------------------ packetbeat.interfaces.device: eth0 packetbeat.interfaces.type: af_packet ------------------------------------------------------------------------------ On Linux, if you are trying to optimize the CPU usage of Packetbeat, we recommend trying the `af_packet` option. If you use the `af_packet` sniffer, you can tune its behaviour by specifying the following options: [float] ==== `buffer_size_mb` The maximum size of the shared memory buffer to use between the kernel and user space. A bigger buffer usually results in lower CPU usage, but consumes more memory. This setting is only available for the `af_packet` sniffer type. The default is 30 MB. Example: [source,yaml] ------------------------------------------------------------------------------ packetbeat.interfaces.device: eth0 packetbeat.interfaces.type: af_packet packetbeat.interfaces.buffer_size_mb: 100 ------------------------------------------------------------------------------ [float] ==== `auto_promisc_mode` With `auto_promisc_mode` Packetbeat puts interface in promiscuous mode automatically on startup. This option does not work with `any` interface device. The default option is false and requires manual set-up of promiscuous mode. Warning: under some circumstances (e.g beat crash) promiscuous mode can stay enabled even after beat is shut down. Example: [source,yaml] ------------------------------------------------------------------------------ packetbeat.interfaces.device: eth0 packetbeat.interfaces.type: af_packet packetbeat.interfaces.buffer_size_mb: 100 packetbeat.interfaces.auto_promisc_mode: true ------------------------------------------------------------------------------ [float] ==== `with_vlans` Packetbeat automatically generates a https://en.wikipedia.org/wiki/Berkeley_Packet_Filter[BPF] for capturing only the traffic on ports where it expects to find known protocols. For example, if you have configured port 80 for HTTP and port 3306 for MySQL, Packetbeat generates the following BPF filter: `""port 80 or port 3306""`. However, if the traffic contains https://en.wikipedia.org/wiki/IEEE_802.1Q[VLAN] tags, the filter that Packetbeat generates is ineffective because the offset is moved by four bytes. To fix this, you can enable the `with_vlans` option, which generates a BPF filter that looks like this: `""port 80 or port 3306 or (vlan and (port 80 or port 3306))""`. [float] ==== `bpf_filter` Packetbeat automatically generates a https://en.wikipedia.org/wiki/Berkeley_Packet_Filter[BPF] for capturing only the traffic on ports where it expects to find known protocols. For example, if you have configured port 80 for HTTP and port 3306 for MySQL, Packetbeat generates the following BPF filter: `""port 80 or port 3306""`. You can use the `bpf_filter` setting to overwrite the generated BPF filter. For example: [source,yaml] ------------------------------------------------------------------------------ packetbeat.interfaces.device: eth0 packetbeat.interfaces.bpf_filter: ""net 192.168.238.0/0 and port 80 or port 3306"" ------------------------------------------------------------------------------ NOTE: This setting disables automatic generation of the BPF filter. If you use this setting, it's your responsibility to keep the BPF filters in sync with the ports defined in the `protocols` section. [float] ==== `ignore_outgoing` If the `ignore_outgoing` option is enabled, Packetbeat ignores all the transactions initiated from the server running Packetbeat. This is useful when two Packetbeat instances publish the same transactions. Because one Packetbeat sees the transaction in its outgoing queue and the other sees it in its incoming queue, you can end up with duplicate transactions. To remove the duplicates, you can enable the `packetbeat.ignore_outgoing` option on one of the servers. For example, in the following scenario, you see a 3-server architecture where a Beat is installed on each server. t1 is the transaction exchanged between Server1 and Server2, and t2 is the transaction between Server2 and Server3. image::./images/option_ignore_outgoing.png[Beats Architecture] By default, each transaction is indexed twice because Beat2 sees both transactions. So you would see the following published transactions (when `ignore_outgoing` is false): - Beat1: t1 - Beat2: t1 and t2 - Beat3: t2 To avoid duplicates, you can force your Beats to send only the incoming transactions and ignore the transactions created by the local server. So you would see the following published transactions (when `ignore_outgoing` is true): - Beat1: none - Beat2: t1 - Beat3: t2 [[configuration-flows]] == Configure flows to monitor network traffic ++++ Network flows ++++ You can configure Packetbeat to collect and report statistics on network flows. A _flow_ is a group of packets sent over the same time period that share common properties, such as the same source and destination address and protocol. You can use this feature to analyze network traffic over specific protocols on your network. For each flow, Packetbeat reports the number of packets and the total number of bytes sent from the source to the destination. Each flow event also contains information about the source and destination hosts, such as their IP address. For bi-directional flows, Packetbeat reports statistics for the reverse flow. Packetbeat collects and reports statistics up to and including the transport layer. See <> for more info about the exported data. Here's an example of flow events visualized in the Flows dashboard: image::./images/flows.png[] To configure flows, use the `packetbeat.flows` option in the +{beatname_lc}.yml+ config file. Flows are enabled by default. If this section is missing from the configuration file, network flows are disabled. [source,yaml] -------------------------------------------------------------------------------- packetbeat.flows: timeout: 30s period: 10s -------------------------------------------------------------------------------- Here’s an example of a flow information sent by Packetbeat. See <> for a description of each field. [""source"",""json"",subs=""attributes""] -------------------------------------------------------------------------------- { ""@timestamp"": ""2018-11-15T14:41:24.000Z"", ""agent"": { ""hostname"": ""host.example.com"", ""name"": ""host.example.com"", ""version"": ""{version}"" }, ""destination"": { ""bytes"": 460, ""ip"": ""198.51.100.2"", ""mac"": ""06:05:04:03:02:01"", ""packets"": 2, ""port"": 80 }, ""event"": { ""dataset"": ""flow"", ""duration"": 3000000000, ""end"": ""2018-11-15T14:41:24.000Z"", ""start"": ""2018-11-15T14:41:21.000Z"" }, ""flow"": { ""final"": true, <1> ""id"": ""FQQA/wz/Dv//////Fv8BAQEBAgMEBQYGBQQDAgGrAMsAcQPGM2QC9ZdQAA"", ""vlan"": 171 }, ""network"": { ""bytes"": 470, ""community_id"": ""1:t9T66/2c66NQyftAEsr4aMZv4Hc="", ""packets"": 3, ""transport"": ""tcp"", ""type"": ""ipv4"" }, ""source"": { ""bytes"": 10, ""ip"": ""203.0.113.3"", ""mac"": ""01:02:03:04:05:06"", ""packets"": 1, ""port"": 38901 } } -------------------------------------------------------------------------------- <1> Packetbeat sets the `flow.final` flag to `false` to indicate that the event contains an intermediate report about a flow that it's tracking. When the flow completes, Packetbeat sends one last event with `flow.final` set to `true`. If you want to aggregate sums of traffic, you need to filter on `final:true`, or use some other technique, so that you get only the latest update from each flow. You can disable intermediate reports by setting `period: -1s`. [float] === Configuration options You can specify the following options in the `packetbeat.flows` section of the +{beatname_lc}.yml+ config file: [float] ==== `enabled` Enables flows support if set to true. Set to false to disable network flows support without having to delete or comment out the flows section. The default value is true. [float] ==== `timeout` Timeout configures the lifetime of a flow. If no packets have been received for a flow within the timeout time window, the flow is killed and reported. The default value is 30s. [float] ==== `period` Configure the reporting interval. All flows are reported at the very same point in time. Periodical reporting can be disabled by setting the value to -1. If disabled, flows are still reported once being timed out. The default value is 10s. [float] [[packetbeat-configuration-flows-fields]] ==== `fields` Optional fields that you can specify to add additional information to the output. For example, you might add fields that you can use for filtering log data. Fields can be scalar values, arrays, dictionaries, or any nested combination of these. By default, the fields that you specify here will be grouped under a `fields` sub-dictionary in the output document. To store the custom fields as top-level fields, set the `fields_under_root` option to true. If a duplicate field is declared in the general configuration, then its value will be overwritten by the value declared here. [float] ==== `fields_under_root` If this option is set to true, the custom <> are stored as top-level fields in the output document instead of being grouped under a `fields` sub-dictionary. If the custom field names conflict with other field names added by Packetbeat, then the custom fields overwrite the other fields. [float] ==== `tags` A list of tags that will be sent with the protocol event. This setting is optional. [float] ==== `processors` A list of processors to apply to the data generated by the protocol. See <> for information about specifying processors in your config. [float] ==== `keep_null` If this option is set to true, fields with `null` values will be published in the output document. By default, `keep_null` is set to `false`. [[configuration-protocols]] == Configure which transaction protocols to monitor ++++ Protocols ++++ The `packetbeat.protocols` section of the +{beatname_lc}.yml+ config file contains configuration options for each supported protocol, including common options like `enabled`, `ports`, `send_request`, `send_response`, and options that are protocol-specific. Currently, Packetbeat supports the following protocols: include::./shared-protocol-list.asciidoc[] Example configuration: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: icmp enabled: true - type: dhcpv4 ports: [67, 68] - type: dns ports: [53] - type: http ports: [80, 8080, 8000, 5000, 8002] - type: amqp ports: [5672] - type: cassandra ports: [9042] - type: memcache ports: [11211] - type: mysql ports: [3306,3307] - type: redis ports: [6379] - type: pgsql ports: [5432] - type: thrift ports: [9090] - type: tls ports: [443, 993, 995, 5223, 8443, 8883, 9243] ------------------------------------------------------------------------------ [[common-protocol-options]] === Common protocol options The following options are available for all protocols: [float] ==== `enabled` The enabled setting is a boolean setting to enable or disable protocols without having to comment out configuration sections. If set to false, the protocol is disabled. The default value is true. [float] ==== `ports` Exception: For ICMP the option `enabled` has to be used instead. The ports where Packetbeat will look to capture traffic for specific protocols. Packetbeat installs a https://en.wikipedia.org/wiki/Berkeley_Packet_Filter[BPF] filter based on the ports specified in this section. If a packet doesn't match the filter, very little CPU is required to discard the packet. Packetbeat also uses the ports specified here to determine which parser to use for each packet. [float] [[send-request-option]] ==== `send_request` If this option is enabled, the raw message of the request (`request` field) is sent to Elasticsearch. The default is false. This option is useful when you want to index the whole request. Note that for HTTP, the body is not included by default, only the HTTP headers. [float] [[send-response-option]] ==== `send_response` If this option is enabled, the raw message of the response (`response` field) is sent to Elasticsearch. The default is false. This option is useful when you want to index the whole response. Note that for HTTP, the body is not included by default, only the HTTP headers. [float] [[transaction-timeout-option]] ==== `transaction_timeout` The per protocol transaction timeout. Expired transactions will no longer be correlated to incoming responses, but sent to Elasticsearch immediately. [float] [[packetbeat-configuration-fields]] ==== `fields` Optional fields that you can specify to add additional information to the output. For example, you might add fields that you can use for filtering log data. Fields can be scalar values, arrays, dictionaries, or any nested combination of these. By default, the fields that you specify here will be grouped under a `fields` sub-dictionary in the output document. To store the custom fields as top-level fields, set the `fields_under_root` option to true. If a duplicate field is declared in the general configuration, then its value will be overwritten by the value declared here. [source,yaml] -------------------------------------------------------------------------------- packetbeat.protocols: - type: http ports: [80] fields: service_id: nginx -------------------------------------------------------------------------------- [float] [[packetbeat-fields-under-root]] ==== `fields_under_root` If this option is set to true, the custom <> are stored as top-level fields in the output document instead of being grouped under a `fields` sub-dictionary. If the custom field names conflict with other field names added by Packetbeat, then the custom fields overwrite the other fields. [float] ==== `tags` A list of tags that will be sent with the transaction event. This setting is optional. [float] ==== `processors` A list of processors to apply to the data generated by the protocol. See <> for information about specifying processors in your config. [float] ==== `keep_null` If this option is set to true, fields with `null` values will be published in the output document. By default, `keep_null` is set to `false`. [[packetbeat-icmp-options]] === Capture ICMP traffic ++++ ICMP ++++ The `icmp` section of the +{beatname_lc}.yml+ config file specifies options for the ICMP protocol. Here is a sample configuration section for ICMP: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: icmp enabled: true ------------------------------------------------------------------------------ ==== Configuration options Also see <>. ===== `enabled` The ICMP protocol can be enabled/disabled via this option. The default is true. If enabled Packetbeat will generate the following BPF filter: `""icmp or icmp6""`. [[packetbeat-dns-options]] === Capture DNS traffic ++++ DNS ++++ The `dns` section of the +{beatname_lc}.yml+ config file specifies configuration options for the DNS protocol. The DNS protocol supports processing DNS messages on TCP and UDP. Here is a sample configuration section for DNS: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: dns ports: [53] include_authorities: true include_additionals: true ------------------------------------------------------------------------------ ==== Configuration options Also see <>. ===== `include_authorities` If this option is enabled, dns.authority fields (authority resource records) are added to DNS events. The default is false. ===== `include_additionals` If this option is enabled, dns.additionals fields (additional resource records) are added to DNS events. The default is false. [[packetbeat-http-options]] === Capture HTTP traffic ++++ HTTP ++++ The HTTP protocol has several specific configuration options. Here is a sample configuration for the `http` section of the +{beatname_lc}.yml+ config file: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: http ports: [80, 8080, 8000, 5000, 8002] hide_keywords: [""pass"", ""password"", ""passwd""] send_headers: [""User-Agent"", ""Cookie"", ""Set-Cookie""] split_cookie: true real_ip_header: ""X-Forwarded-For"" ------------------------------------------------------------------------------ ==== Configuration options Also see <>. ===== `hide_keywords` A list of query parameters that Packetbeat will automatically censor in the transactions that it saves. The values associated with these parameters are replaced by `'xxxxx'`. By default, no changes are made to the HTTP messages. Packetbeat has this option because, unlike SQL traffic, which typically only contains the hashes of the passwords, HTTP traffic may contain sensitive data. To reduce security risks, you can configure this option to avoid sending the contents of certain HTTP POST parameters. WARNING: This option replaces query parameters from GET requests and top-level parameters from POST requests. If sensitive data is encoded inside a parameter that you don't specify here, Packetbeat cannot censor it. Also, note that if you configure Packetbeat to save the raw request and response fields (see the <> and the <> options), sensitive data may be present in those fields. ===== `redact_authorization` When this option is enabled, Packetbeat obscures the value of `Authorization` and `Proxy-Authorization` HTTP headers, and censors those strings in the response. You should set this option to true for transactions that use Basic Authentication because they may contain the base64 unencrypted username and password. ===== `send_headers` A list of header names to capture and send to Elasticsearch. These headers are placed under the `headers` dictionary in the resulting JSON. ===== `send_all_headers` Instead of sending a white list of headers to Elasticsearch, you can send all headers by setting this option to true. The default is false. ===== `redact_headers` A list of headers to redact if present in the HTTP request. This will keep the header field present, but will redact it's value to show the header's presence. ===== `include_body_for` The list of content types for which Packetbeat exports the full HTTP payload. The HTTP body is available under `http.request.body.content` and `http.response.body.content` for these Content-Types. In addition, if <> option is enabled, then the HTTP body is exported together with the HTTP headers under `response` and if <> enabled, then `request` contains the entire HTTP message including the body. In the following example, the HTML attachments of the HTTP responses are exported under the `response` field and under `http.request.body.content` or `http.response.body.content`: [source,yml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: http ports: [80, 8080] send_response: true include_body_for: [""text/html""] ------------------------------------------------------------------------------ ===== `decode_body` A boolean flag that controls decoding of HTTP payload. It interprets the `Content-Encoding` and `Transfer-Encoding` headers and uncompresses the entity body. Supported encodings are `gzip` and `deflate`. This option is only applicable in the cases where the HTTP payload is exported, that is, when one of the `include_*_body_for` options is specified or a POST request contains url-encoded parameters. ===== `split_cookie` If the `Cookie` or `Set-Cookie` headers are sent, this option controls whether they are split into individual values. For example, with this option set, an HTTP response might result in the following JSON: [source,json] ------------------------------------------------------------------------------ ""response"": { ""code"": 200, ""headers"": { ""connection"": ""close"", ""content-language"": ""en"", ""content-type"": ""text/html; charset=utf-8"", ""date"": ""Fri, 21 Nov 2014 17:07:34 GMT"", ""server"": ""gunicorn/19.1.1"", ""set-cookie"": { <1> ""csrftoken"": ""S9ZuJF8mvIMT5CL4T1Xqn32wkA6ZSeyf"", ""expires"": ""Fri, 20-Nov-2015 17:07:34 GMT"", ""max-age"": ""31449600"", ""path"": ""/"" }, ""vary"": ""Cookie, Accept-Language"" }, ""status_phrase"": ""OK"" } ------------------------------------------------------------------------------ <1> Note that `set-cookie` is a map containing the cookie names as keys. The default is false. ===== `real_ip_header` The header field to extract the real IP from. This setting is useful when you want to capture traffic behind a reverse proxy, but you want to get the geo-location information. If this header is present and contains a valid IP addresses, the information is used for the `network.forwarded_ip` field. ===== `max_message_size` If an individual HTTP message is larger than this setting (in bytes), it will be trimmed to this size. Unless this value is very small (<1.5K), Packetbeat is able to still correctly follow the transaction and create an event for it. The default is 10485760 (10 MB). [[packetbeat-amqp-options]] === Capture AMQP traffic ++++ AMQP ++++ The `amqp` section of the +{beatname_lc}.yml+ config file specifies configuration options for the AMQP 0.9.1 protocol. Here is a sample configuration: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: amqp ports: [5672] max_body_length: 1000 parse_headers: true parse_arguments: false hide_connection_information: true ------------------------------------------------------------------------------ ==== Configuration options Also see <>. ===== `max_body_length` The maximum size in bytes of the message displayed in the request or response fields. Messages that are bigger than the specified size are truncated. Use this option to avoid publishing huge messages when <> or <> is enabled. The default is 1000 bytes. ===== `parse_headers` If set to true, Packetbeat parses the additional arguments specified in the headers field of a message. Those arguments are key-value pairs that specify information such as the content type of the message or the message priority. The default is true. ===== `parse_arguments` If set to true, Packetbeat parses the additional arguments specified in AMQP methods. Those arguments are key-value pairs specified by the user and can be of any length. The default is true. ===== `hide_connection_information` If set to false, the connection layer methods of the protocol are also displayed, such as the opening and closing of connections and channels by clients, or the quality of service negotiation. The default is true. [[configuration-cassandra]] === Capture Cassandra traffic ++++ Cassandra ++++ The following settings are specific to the Cassandra protocol. Here is a sample configuration for the `cassandra` section of the +{beatname_lc}.yml+ config file: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: cassandra send_request_header: true send_response_header: true compressor: ""snappy"" ignored_ops: [""SUPPORTED"",""OPTIONS""] ------------------------------------------------------------------------------ ==== Configuration options Also see <>. ===== `send_request_header` If this option is enabled, the raw message of the response (`cassandra_request.request_headers` field) is sent to Elasticsearch. The default is true. enable `send_request` first before enable this option. ===== `send_response_header` If this option is enabled, the raw message of the response (`cassandra_response.response_headers` field) is included in published events. The default is true. enable `send_response` first before enable this option. ===== `ignored_ops` This option indicates which Operator/Operators captured will be ignored. currently support: `ERROR` ,`STARTUP` ,`READY` ,`AUTHENTICATE` ,`OPTIONS` ,`SUPPORTED` , `QUERY` ,`RESULT` ,`PREPARE` ,`EXECUTE` ,`REGISTER` ,`EVENT` , `BATCH` ,`AUTH_CHALLENGE`,`AUTH_RESPONSE` ,`AUTH_SUCCESS` . ===== `compressor` Configures the default compression algorithm being used to uncompress compressed frames by name. Currently only `snappy` is can be configured. By default no compressor is configured. [[packetbeat-memcache-options]] === Capture Memcache traffic ++++ Memcache ++++ The `memcache` section of the +{beatname_lc}.yml+ config file specifies configuration options for the memcache protocol. Here is a sample configuration section for memcache: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: memcache ports: [11211] parseunknown: false maxvalues: 0 maxbytespervalue: 100 transaction_timeout: 200 udptransactiontimeout: 200 ------------------------------------------------------------------------------ ==== Configuration options Also see <>. ===== `parseunknown` When this option is enabled, it forces the memcache text protocol parser to accept unknown commands. NOTE: The unknown commands MUST NOT contain a data part. ===== `maxvalues` The maximum number of values to store in the message (multi-get). All values will be base64 encoded. The possible settings for this option are: * `maxvalue: -1`, which stores all values (text based protocol multi-get) * `maxvalue: 0`, which stores no values (default) * `maxvalue: N`, which stores up to N values ===== `maxbytespervalue` The maximum number of bytes to be copied for each value element. NOTE: Values will be base64 encoded, so the actual size in the JSON document will be 4 times the value that you specify for `maxbytespervalue`. ===== `udptransactiontimeout` The transaction timeout in milliseconds. The defaults is 10000 milliseconds. NOTE: Quiet messages in UDP binary protocol get responses only if there is an error. The memcache protocol analyzer will wait for the number of milliseconds specified by `udptransactiontimeout` before publishing quiet messages. Non-quiet messages or quiet requests with an error response are published immediately. [[packetbeat-mysql-options]] === Capture MySQL traffic ++++ MySQL ++++ The `mysql` section of the +{beatname_lc}.yml+ config file specifies configuration options for the MySQL protocols. [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: mysql ports: [3306,3307] ------------------------------------------------------------------------------ ==== Configuration options Also see <>. ===== `max_rows` The maximum number of rows from the SQL message to publish to Elasticsearch. The default is 10 rows. ===== `max_row_length` The maximum length in bytes of a row from the SQL message to publish to Elasticsearch. The default is 1024 bytes. ==== `statement_timeout` The duration for which prepared statements are cached after their last use. Valid time units are ""ns"", ""us"" (or ""µs""), ""ms"", ""s"", ""m"", ""h"". The default is `1h`. [[packetbeat-pgsql-options]] === Capture PgSQL traffic ++++ PgSQL ++++ The `pgsql` sections of the +{beatname_lc}.yml+ config file specifies configuration options for the PgSQL protocols. [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: pgsql ports: [5432] ------------------------------------------------------------------------------ ==== Configuration options Also see <>. ===== `max_rows` The maximum number of rows from the SQL message to publish to Elasticsearch. The default is 10 rows. ===== `max_row_length` The maximum length in bytes of a row from the SQL message to publish to Elasticsearch. The default is 1024 bytes. [[configuration-thrift]] === Capture Thrift traffic ++++ Thrift ++++ https://thrift.apache.org/[Apache Thrift] is a communication protocol and RPC framework initially created at Facebook. It is sometimes used in http://martinfowler.com/articles/microservices.html[microservices] architectures because it provides better performance when compared to the more obvious HTTP/RESTful API choice, while still supporting a wide range of programming languages and frameworks. Packetbeat works based on a copy of the traffic, which means that you get performance management features without having to modify your services in any way and without any latency overhead. Packetbeat captures the transactions from the network and indexes them in Elasticsearch so that they can be analyzed and searched. Packetbeat indexes the method, parameters, return value, and exceptions of each Thrift-RPC call. You can search by and create statistics based on any of these fields. Packetbeat automatically fills in the `status` column with either `OK` or `Error`, so it's easy to find the problematic RPC calls. A transaction is put into the `Error` state if it returned an exception. Packetbeat also indexes the `event.duration` field so you can get performance analytics and find the slow RPC calls. Here is an example performance dashboard: image::./images/thrift-dashboard.png[Thrift-RPC dashboard] Thrift supports multiple http://en.wikipedia.org/wiki/Apache_Thrift[transport and protocol types]. Currently Packetbeat supports the default `TSocket` transport as well as the `TFramed` transport. From the protocol point of view, Packetbeat currently supports only the default `TBinary` protocol. Packetbeat also has several configuration options that allow you to get the right balance between visibility, disk usage, and data protection. You can, for example, choose to obfuscate all strings or to store the requests but not the responses, while still capturing the response time for each of the RPC calls. You can also choose to limit the size of strings and lists to a given number of elements, so you can fine tune how much data you want to have stored in Elasticsearch. The Thrift protocol has several specific configuration options. Here is an example configuration section for the Thrift protocol in the +{beatname_lc}.yml+ config file: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: thrift transport_type: socket protocol_type: binary idl_files: [""tutorial.thrift"", ""shared.thrift""] string_max_size: 200 collection_max_size: 20 capture_reply: true obfuscate_strings: true drop_after_n_struct_fields: 100 ------------------------------------------------------------------------------ Providing the Thrift IDL files to Packetbeat is optional. The binary Thrift messages include the called method name and enough structural information to decode the messages without needing the IDL files. However, if you provide the IDL files, Packetbeat can also resolve the service name, arguments, and exception names. ==== Configuration options Also see <>. ===== `transport_type` The Thrift transport type. Currently this option accepts the values `socket` for TSocket, which is the default Thrift transport, and `framed` for the TFramed Thrift transport. The default is `socket`. ===== `protocol_type` The Thrift protocol type. Currently the only accepted value is `binary` for the TBinary protocol, which is the default Thrift protocol. ===== `idl_files` The Thrift interface description language (IDL) files for the service that Packetbeat is monitoring. Providing the IDL files is optional, because the Thrift messages contain enough information to decode them without having the IDL files. However, providing the IDL enables Packetbeat to include parameter and exception names. ===== `string_max_size` The maximum length for strings in parameters or return values. If a string is longer than this value, the string is automatically truncated to this length. Packetbeat adds dots at the end of the string to mark that it was truncated. The default is 200. ===== `collection_max_size` The maximum number of elements in a Thrift list, set, map, or structure. If a collection has more elements than this value, Packetbeat captures only the specified number of elements. Packetbeat adds a fictive last element `...` to the end of the collection to mark that it was truncated. The default is 15. ===== `capture_reply` If this option is set to false, Packetbeat decodes the method name from the reply and simply skips the rest of the response message. This setting can be useful for performance, disk usage, or data retention reasons. The default is true. ===== `obfuscate_strings` If this option is set to true, Packetbeat replaces all strings found in method parameters, return codes, or exception structures with the `""*""` string. ===== `drop_after_n_struct_fields` The maximum number of fields that a structure can have before Packetbeat ignores the whole transaction. This is a memory protection mechanism (so that Packetbeat's memory doesn't grow indefinitely), so you would typically set this to a relatively high value. The default is 500. [[configuration-mongodb]] === Capture MongoDB traffic ++++ MongoDB ++++ The following settings are specific to the MongoDB protocol. Here is a sample configuration for the `mongodb` section of the +{beatname_lc}.yml+ config file: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: mongodb send_request: true send_response: true max_docs: 0 max_doc_length: 0 ------------------------------------------------------------------------------ ==== Configuration options The `max_docs` and `max_doc_length` settings are useful for limiting the amount of data Packetbeat indexes in the `response` fields. Also see <>. ===== `max_docs` The maximum number of documents from the response to index in the `response` field. The default is 10. You can set this to 0 to index an unlimited number of documents. Packetbeat adds a `[...]` line at the end to signify that there were additional documents that weren't saved because of this setting. ===== `max_doc_length` The maximum number of characters in a single document indexed in the `response` field. The default is 5000. You can set this to 0 to index an unlimited number of characters per document. If the document is trimmed because of this setting, Packetbeat adds the string `...` at the end of the document. Note that limiting documents in this way means that they are no longer correctly formatted JSON objects. [[configuration-tls]] === Capture TLS traffic ++++ TLS ++++ TLS is a cryptographic protocol that provides secure communications on top of an existing application protocol, like HTTP or MySQL. Packetbeat intercepts the initial handshake in a TLS connection and extracts useful information that helps operators diagnose problems and strengthen the security of their network and systems. It does not decrypt any information from the encapsulated protocol, nor does it reveal any sensitive information such as cryptographic keys. TLS versions 1.0 to 1.3 and SSL 3.0 are supported. It works by intercepting the client and server ""hello"" messages, which contain the negotiated parameters for the connection such as cryptographic ciphers and protocol versions. It can also intercept TLS alerts, which are sent by one of the parties to signal a problem with the negotiation, such as an expired certificate or a cryptographic error. An example of indexed event: [source,json] ------------------------------------------------------------------------------ ""tls"": { ""client"": { ""supported_ciphers"": [ ""TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"", ""TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"", ""TLS_RSA_WITH_3DES_EDE_CBC_SHA"", ""TLS_EMPTY_RENEGOTIATION_INFO_SCSV"" ], ""ja3"": ""e6573e91e6eb777c0933c5b8f97f10cd"", ""server_name"": ""example.net"" }, ""server"": { ""subject"": ""CN=www.example.org,OU=Technology,O=Internet Corporation for Assigned Names and Numbers,L=Los Angeles,ST=California,C=US"", ""issuer"": ""CN=DigiCert SHA2 Secure Server CA,O=DigiCert Inc,C=US"", ""not_before"": ""2018-11-28T00:00:00.000Z"", ""not_after"": ""2020-12-02T12:00:00.000Z"", ""hash"": { ""sha1"": ""7BB698386970363D2919CC5772846984FFD4A889"" } }, ""version"": ""1.2"", ""version_protocol"": ""tls"", ""cipher"": ""TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"", ""established"": true, ""next_protocol"": ""h2"", ""detailed"": { ""server_certificate"": { ""subject"": { ""common_name"": ""www.example.org"", ""country"": ""US"", ""organization"": ""Internet Corporation for Assigned Names and Numbers"", ""organizational_unit"": ""Technology"", ""locality"": ""Los Angeles"", ""province"": ""California"" }, ""not_after"": ""2020-12-02T12:00:00.000Z"", ""public_key_size"": 2048, ""alternative_names"": [ ""www.example.org"", ""example.com"", ""example.edu"", ""example.net"", ""example.org"", ""www.example.com"", ""www.example.edu"", ""www.example.net"" ], ""signature_algorithm"": ""SHA256-RSA"", ""version"": 3, ""issuer"": { ""organization"": ""DigiCert Inc"", ""common_name"": ""DigiCert SHA2 Secure Server CA"", ""country"": ""US"" }, ""not_before"": ""2018-11-28T00:00:00.000Z"", ""public_key_algorithm"": ""RSA"", ""serial_number"": ""21020869104500376438182461249190639870"" }, ""server_certificate_chain"": [ { ""public_key_algorithm"": ""RSA"", ""not_before"": ""2013-03-08T12:00:00.000Z"", ""not_after"": ""2023-03-08T12:00:00.000Z"", ""version"": 3, ""serial_number"": ""2646203786665923649276728595390119057"", ""issuer"": { ""organizational_unit"": ""www.digicert.com"", ""common_name"": ""DigiCert Global Root CA"", ""country"": ""US"", ""organization"": ""DigiCert Inc"" }, ""subject"": { ""country"": ""US"", ""organization"": ""DigiCert Inc"", ""common_name"": ""DigiCert SHA2 Secure Server CA"" }, ""public_key_size"": 2048, ""signature_algorithm"": ""SHA256-RSA"" }, { ""public_key_algorithm"": ""RSA"", ""subject"": { ""common_name"": ""DigiCert Global Root CA"", ""country"": ""US"", ""organization"": ""DigiCert Inc"", ""organizational_unit"": ""www.digicert.com"" }, ""issuer"": { ""country"": ""US"", ""organization"": ""DigiCert Inc"", ""organizational_unit"": ""www.digicert.com"", ""common_name"": ""DigiCert Global Root CA"" }, ""signature_algorithm"": ""SHA1-RSA"", ""serial_number"": ""10944719598952040374951832963794454346"", ""not_before"": ""2006-11-10T00:00:00.000Z"", ""not_after"": ""2031-11-10T00:00:00.000Z"", ""public_key_size"": 2048, ""version"": 3 } ], ""client_certificate_requested"": false, ""version"": ""TLS 1.2"", ""client_hello"": { ""version"": ""3.3"", ""supported_compression_methods"": [ ""NULL"" ], ""extensions"": { ""ec_points_formats"": [ ""uncompressed"" ], ""supported_groups"": [ ""x25519"", ""secp256r1"", ""secp384r1"" ], ""signature_algorithms"": [ ""rsa_pkcs1_sha512"", ""ecdsa_secp521r1_sha512"", ""(unknown:0xefef)"", ""rsa_pkcs1_sha384"", ""ecdsa_secp384r1_sha384"", ""rsa_pkcs1_sha256"", ""ecdsa_secp256r1_sha256"", ""(unknown:0xeeee)"", ""(unknown:0xeded)"", ""(unknown:0x0301)"", ""(unknown:0x0303)"", ""rsa_pkcs1_sha1"", ""ecdsa_sha1"" ], ""application_layer_protocol_negotiation"": [ ""h2"", ""http/1.1"" ], ""server_name_indication"": [ ""example.net"" ] } }, ""server_hello"": { ""version"": ""3.3"", ""session_id"": ""23bb2aed5d215e1228220b0a51d7aa220785e9e4b83b4f430229117971e9913f"", ""selected_compression_method"": ""NULL"", ""extensions"": { ""application_layer_protocol_negotiation"": [ ""h2"" ], ""_unparsed_"": [ ""renegotiation_info"", ""server_name_indication"" ], ""ec_points_formats"": [ ""uncompressed"", ""ansiX962_compressed_prime"", ""ansiX962_compressed_char2"" ] } } } } ------------------------------------------------------------------------------ The TLS events generated by {beatname_uc} follow the Elastic Common Schema (ECS) format. See {ecs-ref}/ecs-tls.html[ECS TLS fields] for a description of the populated fields. Detailed information that is not defined in ECS is added under the `tls.detailed` key. The <> configuration flag is used to control whether this information is exported. The fields under `tls.detailed.client_hello` contain the algorithms and extensions supported by the client, as well as the maximum TLS version it supports. Fields under `tls.detailed.server_hello` contain the final settings for the TLS session: The selected cipher, compression method, TLS version to use and other extensions such as application layer protocol negotiation (ALPN). See the <> section for more information. The following settings are specific to the TLS protocol. Here is a sample configuration for the `tls` section of the +{beatname_lc}.yml+ config file: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: tls send_certificates: true include_raw_certificates: false include_detailed_fields: true fingerprints: [ md5, sha1, sha256 ] ------------------------------------------------------------------------------ ==== Configuration options The `send_certificates` and `include_detailed_fields` settings are useful for limiting the amount of data Packetbeat indexes, as multiple certificates are usually exchanged in a single transaction, and those can take a considerable amount of storage. Also see <>. ===== `send_certificates` This setting causes information about the certificates presented by the client and server to be included in the detailed fields. The server's certificate is indexed under `tls.detailed.server_certificate` and its certification chain under `tls.detailed.server_certificate_chain`. For the client, the `client_certificate` and `client_certificate_chain` fields are used. The default is true. ===== `include_raw_certificates` You can set `include_raw_certificates` to include the raw certificate chains encoded in PEM format, under the `tls.server.certificate_chain` and `tls.client.certificate_chain` fields. The default is false. [[include_detailed_fields]] ===== `include_detailed_fields` Controls whether the <> are added to exported documents. When set to `false`, only {ecs-ref}/ecs-tls.html[ECS TLS fields] are included. The default is `true`. ===== `fingerprints` Defines a list of hash algorithms to calculate the certificate's fingerprints. Valid values are `sha1`, `sha256` and `md5`. The default is to output SHA-1 fingerprints. [[packetbeat-redis-options]] === Capture Redis traffic ++++ Redis ++++ The Redis protocol has several specific configuration options. Here is a sample configuration for the `redis` section of the +{beatname_lc}.yml+ config file: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: redis ports: [6379] queue_max_bytes: 1048576 queue_max_messages: 20000 ------------------------------------------------------------------------------ ==== Configuration options Also see <>. ===== `queue_max_bytes` and `queue_max_messages` In order for request/response correlation to work, {beatname_uc} needs to store requests in memory until a response is received. These settings impose a limit on the number of bytes (`queue_max_bytes`) and number of requests (`queue_max_messages`) that can be stored. These limits are per-connection. The default is to queue up to 1MB or 20.000 requests per connection, which allows to use request pipelining while at the same time limiting the amount of memory consumed by replication sessions. [[configuration-processes]] == Configure which processes to monitor ++++ Processes ++++ This section of the +{beatname_lc}.yml+ config file is optional, but configuring the processes enables Packetbeat to show you not only the servers that the traffic is flowing between, but also the processes. Packetbeat can even show you the traffic between two processes running on the same host, which is particularly useful when you have many services running on the same server. By default, process enrichment is disabled. When Packetbeat starts, and then periodically afterwards, it scans the process table for processes that match the configuration file. For each of these processes, it monitors which file descriptors it has opened. When a new packet is captured, it reads the list of active TCP and UDP connections and matches the corresponding one with the list of file descriptors. All this information is available via system interfaces: The `/proc` file system in Linux and the IP Helper API (`iphlpapi.dll`) on Windows, so {beatname_uc} doesn't need a kernel module. NOTE: Process monitoring is currently only supported on Linux and Windows systems. Packetbeat automatically disables process monitoring when it detects other operating systems. Example configuration: [source,yaml] ------------------------------------------------------------------------------ packetbeat.procs.enabled: true ------------------------------------------------------------------------------ When the process monitor is enabled, it will enrich all the events whose source or destination is a local process. The `source.process` and/or `destination.process` fields will be added to an event, when the server side or client side of the connection belong to a local process, respectively. [float] === Configuration options You can specify the following process monitoring options in the `monitored` section of the +{beatname_lc}.yml+ config file to customize the name of process: [float] ==== `process` The name of the process as it will appear in the published transactions. The name doesn't have to match the name of the executable, so feel free to choose something more descriptive (for example, ""myapp"" instead of ""gunicorn""). [float] ==== `cmdline_grep` The name used to identify the process at run time. When Packetbeat starts, and then periodically afterwards, it scans the process table for processes that match the values specified for this option. The match is done against the process' command line as read from `/proc//cmdline`. [float] [[shutdown-timeout]] ==== `shutdown_timeout` How long Packetbeat waits on shutdown. By default, this option is disabled. Packetbeat will wait for `shutdown_timeout` and then close. It will not track if all events were sent previously. Example configuration: [source,yaml] ------------------------------------------------------------------------------------- packetbeat.shutdown_timeout: 5s ------------------------------------------------------------------------------------- ",12410,False,2168.394642739032,median "CLASS zcl_abapgit_objects DEFINITION PUBLIC CREATE PUBLIC . PUBLIC SECTION. TYPES: ty_types_tt TYPE SORTED TABLE OF tadir-object WITH UNIQUE KEY table_line. TYPES: BEGIN OF ty_serialization, files TYPE zif_abapgit_definitions=>ty_files_tt, item TYPE zif_abapgit_definitions=>ty_item, END OF ty_serialization . CLASS-METHODS serialize IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item !iv_language TYPE spras !iv_serialize_master_lang_only TYPE abap_bool DEFAULT abap_false !it_translation_langs TYPE zif_abapgit_definitions=>ty_languages OPTIONAL RETURNING VALUE(rs_files_and_item) TYPE ty_serialization RAISING zcx_abapgit_exception . CLASS-METHODS deserialize IMPORTING !io_repo TYPE REF TO zcl_abapgit_repo !is_checks TYPE zif_abapgit_definitions=>ty_deserialize_checks !ii_log TYPE REF TO zif_abapgit_log RETURNING VALUE(rt_accessed_files) TYPE zif_abapgit_definitions=>ty_file_signatures_tt RAISING zcx_abapgit_exception . CLASS-METHODS deserialize_checks IMPORTING !io_repo TYPE REF TO zcl_abapgit_repo RETURNING VALUE(rs_checks) TYPE zif_abapgit_definitions=>ty_deserialize_checks RAISING zcx_abapgit_exception . CLASS-METHODS delete IMPORTING !it_tadir TYPE zif_abapgit_definitions=>ty_tadir_tt !is_checks TYPE zif_abapgit_definitions=>ty_delete_checks OPTIONAL !ii_log TYPE REF TO zif_abapgit_log OPTIONAL RAISING zcx_abapgit_exception . CLASS-METHODS jump IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item !iv_line_number TYPE i OPTIONAL !iv_sub_obj_name TYPE zif_abapgit_definitions=>ty_item-obj_name OPTIONAL !iv_sub_obj_type TYPE zif_abapgit_definitions=>ty_item-obj_type OPTIONAL RAISING zcx_abapgit_exception . CLASS-METHODS changed_by IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item RETURNING VALUE(rv_user) TYPE xubname RAISING zcx_abapgit_exception . CLASS-METHODS is_supported IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item !iv_native_only TYPE abap_bool DEFAULT abap_false RETURNING VALUE(rv_bool) TYPE abap_bool . CLASS-METHODS exists IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item RETURNING VALUE(rv_bool) TYPE abap_bool . CLASS-METHODS supported_list RETURNING VALUE(rt_types) TYPE ty_types_tt . CLASS-METHODS is_active IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item RETURNING VALUE(rv_active) TYPE abap_bool RAISING zcx_abapgit_exception . PROTECTED SECTION. PRIVATE SECTION. TYPES: BEGIN OF ty_obj_serializer_item, item TYPE zif_abapgit_definitions=>ty_item, metadata TYPE zif_abapgit_definitions=>ty_metadata, END OF ty_obj_serializer_item . TYPES: ty_obj_serializer_map TYPE SORTED TABLE OF ty_obj_serializer_item WITH UNIQUE KEY item . CLASS-DATA gt_obj_serializer_map TYPE ty_obj_serializer_map . CLASS-METHODS files_to_deserialize IMPORTING !io_repo TYPE REF TO zcl_abapgit_repo !ii_log TYPE REF TO zif_abapgit_log OPTIONAL RETURNING VALUE(rt_results) TYPE zif_abapgit_definitions=>ty_results_tt RAISING zcx_abapgit_exception . CLASS-METHODS check_duplicates IMPORTING !it_files TYPE zif_abapgit_definitions=>ty_files_tt RAISING zcx_abapgit_exception . CLASS-METHODS prioritize_deser IMPORTING !it_results TYPE zif_abapgit_definitions=>ty_results_tt RETURNING VALUE(rt_results) TYPE zif_abapgit_definitions=>ty_results_tt . CLASS-METHODS class_name IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item RETURNING VALUE(rv_class_name) TYPE string . CLASS-METHODS warning_overwrite_adjust IMPORTING !it_overwrite TYPE zif_abapgit_definitions=>ty_overwrite_tt CHANGING !ct_results TYPE zif_abapgit_definitions=>ty_results_tt RAISING zcx_abapgit_exception . CLASS-METHODS checks_adjust IMPORTING !io_repo TYPE REF TO zcl_abapgit_repo !is_checks TYPE zif_abapgit_definitions=>ty_deserialize_checks CHANGING !ct_results TYPE zif_abapgit_definitions=>ty_results_tt RAISING zcx_abapgit_exception . CLASS-METHODS warning_overwrite_find IMPORTING !it_results TYPE zif_abapgit_definitions=>ty_results_tt RETURNING VALUE(rt_overwrite) TYPE zif_abapgit_definitions=>ty_overwrite_tt . CLASS-METHODS warning_package_adjust IMPORTING !io_repo TYPE REF TO zcl_abapgit_repo !it_overwrite TYPE zif_abapgit_definitions=>ty_overwrite_tt CHANGING !ct_results TYPE zif_abapgit_definitions=>ty_results_tt RAISING zcx_abapgit_exception . CLASS-METHODS warning_package_find IMPORTING !it_results TYPE zif_abapgit_definitions=>ty_results_tt !io_repo TYPE REF TO zcl_abapgit_repo RETURNING VALUE(rt_overwrite) TYPE zif_abapgit_definitions=>ty_overwrite_tt RAISING zcx_abapgit_exception . CLASS-METHODS update_package_tree IMPORTING !iv_package TYPE devclass . CLASS-METHODS delete_object IMPORTING !iv_package TYPE devclass !is_item TYPE zif_abapgit_definitions=>ty_item RAISING zcx_abapgit_exception . CLASS-METHODS compare_remote_to_local IMPORTING !ii_object TYPE REF TO zif_abapgit_object !it_remote TYPE zif_abapgit_definitions=>ty_files_tt !is_result TYPE zif_abapgit_definitions=>ty_result !ii_log TYPE REF TO zif_abapgit_log RAISING zcx_abapgit_exception . CLASS-METHODS deserialize_objects IMPORTING !is_step TYPE zif_abapgit_objects=>ty_step_data !ii_log TYPE REF TO zif_abapgit_log CHANGING !ct_files TYPE zif_abapgit_definitions=>ty_file_signatures_tt RAISING zcx_abapgit_exception . CLASS-METHODS check_objects_locked IMPORTING !iv_language TYPE spras !it_items TYPE zif_abapgit_definitions=>ty_items_tt RAISING zcx_abapgit_exception . CLASS-METHODS create_object IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item !iv_language TYPE spras !is_metadata TYPE zif_abapgit_definitions=>ty_metadata OPTIONAL !iv_native_only TYPE abap_bool DEFAULT abap_false RETURNING VALUE(ri_obj) TYPE REF TO zif_abapgit_object RAISING zcx_abapgit_exception . CLASS-METHODS map_tadir_to_items IMPORTING !it_tadir TYPE zif_abapgit_definitions=>ty_tadir_tt RETURNING VALUE(rt_items) TYPE zif_abapgit_definitions=>ty_items_tt . CLASS-METHODS map_results_to_items IMPORTING !it_results TYPE zif_abapgit_definitions=>ty_results_tt RETURNING VALUE(rt_items) TYPE zif_abapgit_definitions=>ty_items_tt . CLASS-METHODS filter_files_to_deserialize IMPORTING !it_results TYPE zif_abapgit_definitions=>ty_results_tt !ii_log TYPE REF TO zif_abapgit_log OPTIONAL RETURNING VALUE(rt_results) TYPE zif_abapgit_definitions=>ty_results_tt . CLASS-METHODS adjust_namespaces IMPORTING !it_results TYPE zif_abapgit_definitions=>ty_results_tt RETURNING VALUE(rt_results) TYPE zif_abapgit_definitions=>ty_results_tt . CLASS-METHODS get_deserialize_steps RETURNING VALUE(rt_steps) TYPE zif_abapgit_objects=>ty_step_data_tt . CLASS-METHODS check_main_package IMPORTING !iv_package TYPE devclass !iv_obj_type TYPE tadir-object RAISING zcx_abapgit_exception . ENDCLASS. CLASS zcl_abapgit_objects IMPLEMENTATION. METHOD adjust_namespaces. FIELD-SYMBOLS: LIKE LINE OF rt_results. rt_results = it_results. LOOP AT rt_results ASSIGNING . REPLACE ALL OCCURRENCES OF '#' IN -obj_name WITH '/'. ENDLOOP. ENDMETHOD. METHOD changed_by. DATA: li_obj TYPE REF TO zif_abapgit_object. IF is_item IS NOT INITIAL. li_obj = create_object( is_item = is_item iv_language = zif_abapgit_definitions=>c_english ). rv_user = li_obj->changed_by( ). ENDIF. IF rv_user IS INITIAL. * eg. "".abapgit.xml"" file rv_user = zcl_abapgit_objects_super=>c_user_unknown. ENDIF. ENDMETHOD. METHOD checks_adjust. warning_overwrite_adjust( EXPORTING it_overwrite = is_checks-overwrite CHANGING ct_results = ct_results ). warning_package_adjust( EXPORTING io_repo = io_repo it_overwrite = is_checks-warning_package CHANGING ct_results = ct_results ). ENDMETHOD. METHOD check_duplicates. DATA: lt_files TYPE zif_abapgit_definitions=>ty_files_tt, lv_path TYPE string, lv_filename TYPE string, lt_duplicates TYPE STANDARD TABLE OF string WITH DEFAULT KEY, lv_duplicates LIKE LINE OF lt_duplicates, lv_all_duplicates TYPE string. FIELD-SYMBOLS: LIKE LINE OF it_files. lt_files = it_files. SORT lt_files BY path ASCENDING filename ASCENDING. LOOP AT lt_files ASSIGNING . IF lv_path = -path AND lv_filename = -filename. CONCATENATE -path -filename INTO lv_duplicates. APPEND lv_duplicates TO lt_duplicates. ENDIF. lv_path = -path. lv_filename = -filename. ENDLOOP. IF lt_duplicates IS NOT INITIAL. CONCATENATE LINES OF lt_duplicates INTO lv_all_duplicates SEPARATED BY `, `. zcx_abapgit_exception=>raise( |Duplicates: { lv_all_duplicates }| ). ENDIF. ENDMETHOD. METHOD check_main_package. "" check package restrictions, closed package, descriptive or "" functional package cl_pak_object_types=>check_object_type( EXPORTING i_working_mode = 'I' i_package_name = iv_package i_pgmid = 'R3TR' i_object_type = iv_obj_type EXCEPTIONS wrong_object_type = 1 package_not_extensible = 2 package_not_loaded = 3 OTHERS = 4 ). CASE sy-subrc. WHEN 0. RETURN. WHEN 2. zcx_abapgit_exception=>raise( |Object type { iv_obj_type } not allowed for package { iv_package }| ). WHEN OTHERS. zcx_abapgit_exception=>raise_t100( ). ENDCASE. ENDMETHOD. METHOD check_objects_locked. DATA: li_obj TYPE REF TO zif_abapgit_object. FIELD-SYMBOLS: LIKE LINE OF it_items. LOOP AT it_items ASSIGNING . "" You should remember that we ignore not supported objects here, "" because otherwise the process aborts which is not desired IF is_supported( ) = abap_false. CONTINUE. ENDIF. li_obj = create_object( is_item = iv_language = iv_language ). IF li_obj->is_locked( ) = abap_true. zcx_abapgit_exception=>raise( |Object { -obj_type } { -obj_name } | && |is locked. Action not possible.| ). ENDIF. ENDLOOP. ENDMETHOD. METHOD class_name. CONCATENATE 'ZCL_ABAPGIT_OBJECT_' is_item-obj_type INTO rv_class_name. ENDMETHOD. METHOD compare_remote_to_local. * this method is used for comparing local with remote objects * before pull, this is useful eg. when overwriting a TABL object. * only the main XML file is used for comparison DATA: ls_remote_file TYPE zif_abapgit_definitions=>ty_file, li_remote_version TYPE REF TO zif_abapgit_xml_input, lv_count TYPE i, ls_result TYPE zif_abapgit_comparator=>ty_result, lv_answer TYPE string, li_comparator TYPE REF TO zif_abapgit_comparator, lv_gui_is_available TYPE abap_bool, ls_item TYPE zif_abapgit_definitions=>ty_item. FIND ALL OCCURRENCES OF '.' IN is_result-filename MATCH COUNT lv_count. IF is_result-filename CS '.XML' AND lv_count = 2. IF ii_object->exists( ) = abap_false. RETURN. ENDIF. READ TABLE it_remote WITH KEY filename = is_result-filename INTO ls_remote_file. IF sy-subrc <> 0. ""if file does not exist in remote, we don't need to validate RETURN. ENDIF. li_comparator = ii_object->get_comparator( ). IF NOT li_comparator IS BOUND. RETURN. ENDIF. CREATE OBJECT li_remote_version TYPE zcl_abapgit_xml_input EXPORTING iv_xml = zcl_abapgit_convert=>xstring_to_string_utf8( ls_remote_file-data ) iv_filename = ls_remote_file-filename. ls_result = li_comparator->compare( ii_remote = li_remote_version ii_log = ii_log ). IF ls_result-text IS INITIAL. RETURN. ENDIF. ""log comparison result ls_item-obj_type = is_result-obj_type. ls_item-obj_name = is_result-obj_name. ii_log->add_warning( iv_msg = ls_result-text is_item = ls_item ). ""continue or abort? lv_gui_is_available = zcl_abapgit_ui_factory=>get_gui_functions( )->gui_is_available( ). IF lv_gui_is_available = abap_true. CALL FUNCTION 'POPUP_TO_CONFIRM' EXPORTING titlebar = 'Warning' text_question = ls_result-text text_button_1 = 'Abort' icon_button_1 = 'ICON_CANCEL' text_button_2 = 'Pull anyway' icon_button_2 = 'ICON_OKAY' default_button = '2' display_cancel_button = abap_false IMPORTING answer = lv_answer EXCEPTIONS text_not_found = 1 OTHERS = 2. IF sy-subrc <> 0 OR lv_answer = 1. zcx_abapgit_exception=>raise( |Deserialization for object { is_result-obj_name } | & |(type { is_result-obj_type }) aborted by user| ). ENDIF. ELSE. zcx_abapgit_exception=>raise( |Deserialization for object { is_result-obj_name } | & |(type { is_result-obj_type }) aborted, user descision required| ). ENDIF. ENDIF. ENDMETHOD. METHOD create_object. DATA: lv_message TYPE string, lv_class_name TYPE string, ls_obj_serializer_map LIKE LINE OF gt_obj_serializer_map. READ TABLE gt_obj_serializer_map INTO ls_obj_serializer_map WITH KEY item = is_item. IF sy-subrc = 0. lv_class_name = ls_obj_serializer_map-metadata-class. ELSEIF is_metadata IS NOT INITIAL. * Metadata is provided only on serialization * Once this has been triggered, the same serializer shall be used * for subsequent processes. * Thus, buffer the metadata afterwards ls_obj_serializer_map-item = is_item. ls_obj_serializer_map-metadata = is_metadata. INSERT ls_obj_serializer_map INTO TABLE gt_obj_serializer_map. lv_class_name = is_metadata-class. ELSE. lv_class_name = class_name( is_item ). ENDIF. REPLACE FIRST OCCURRENCE OF 'LCL' IN lv_class_name WITH 'ZCL_ABAPGIT'. TRY. CREATE OBJECT ri_obj TYPE (lv_class_name) EXPORTING is_item = is_item iv_language = iv_language. CATCH cx_sy_create_object_error. lv_message = |Object type { is_item-obj_type } not supported, serialize|. IF iv_native_only = abap_false. TRY. "" 2nd step, try looking for plugins CREATE OBJECT ri_obj TYPE zcl_abapgit_objects_bridge EXPORTING is_item = is_item. CATCH cx_sy_create_object_error. zcx_abapgit_exception=>raise( lv_message ). ENDTRY. ELSE. "" No native support? -> fail zcx_abapgit_exception=>raise( lv_message ). ENDIF. ENDTRY. ENDMETHOD. METHOD delete. DATA: ls_item TYPE zif_abapgit_definitions=>ty_item, li_progress TYPE REF TO zif_abapgit_progress, lt_tadir LIKE it_tadir, lt_deleted LIKE it_tadir, lt_items TYPE zif_abapgit_definitions=>ty_items_tt, lx_error TYPE REF TO zcx_abapgit_exception, lv_count TYPE i. FIELD-SYMBOLS: LIKE LINE OF it_tadir. lt_tadir = it_tadir. IF is_checks-transport-required = abap_true. zcl_abapgit_default_transport=>get_instance( )->set( is_checks-transport-transport ). ENDIF. TRY. zcl_abapgit_dependencies=>resolve( CHANGING ct_tadir = lt_tadir ). li_progress = zcl_abapgit_progress=>get_instance( lines( lt_tadir ) ). lt_items = map_tadir_to_items( lt_tadir ). check_objects_locked( iv_language = zif_abapgit_definitions=>c_english it_items = lt_items ). CATCH zcx_abapgit_exception INTO lx_error. zcl_abapgit_default_transport=>get_instance( )->reset( ). RAISE EXCEPTION lx_error. ENDTRY. lv_count = 1. DO. CLEAR lt_deleted. LOOP AT lt_tadir ASSIGNING . li_progress->show( iv_current = lv_count iv_text = |Delete { -obj_name }| ). CLEAR ls_item. ls_item-obj_type = -object. ls_item-obj_name = -obj_name. TRY. delete_object( iv_package = -devclass is_item = ls_item ). INSERT INTO TABLE lt_deleted. DELETE lt_tadir. lv_count = lv_count + 1. "" make sure to save object deletions COMMIT WORK. CATCH zcx_abapgit_exception INTO lx_error. IF ii_log IS BOUND. ii_log->add_exception( ix_exc = lx_error is_item = ls_item ). ii_log->add_error( iv_msg = |Deletion of object { ls_item-obj_name } failed| is_item = ls_item ). ENDIF. ENDTRY. ENDLOOP. "" Exit if done or nothing else was deleted IF lines( lt_tadir ) = 0 OR lines( lt_deleted ) = 0. EXIT. ENDIF. ENDDO. zcl_abapgit_default_transport=>get_instance( )->reset( ). IF lx_error IS BOUND AND lines( lt_tadir ) > 0. zcx_abapgit_exception=>raise( 'Error during uninstall. Check the log.' ). ENDIF. li_progress->off( ). ENDMETHOD. METHOD delete_object. DATA: li_obj TYPE REF TO zif_abapgit_object. IF is_supported( is_item ) = abap_true. li_obj = create_object( is_item = is_item iv_language = zif_abapgit_definitions=>c_english ). li_obj->delete( iv_package ). IF li_obj->get_metadata( )-delete_tadir = abap_true. CALL FUNCTION 'TR_TADIR_INTERFACE' EXPORTING wi_delete_tadir_entry = abap_true wi_tadir_pgmid = 'R3TR' wi_tadir_object = is_item-obj_type wi_tadir_obj_name = is_item-obj_name wi_test_modus = abap_false EXCEPTIONS OTHERS = 1 ##FM_SUBRC_OK. "" We deliberately ignore the subrc, because throwing an exception would "" break the deletion of lots of object types. On the other hand we have "" to catch the exceptions because otherwise messages would directly be issued "" by the function module and change the control flow. Thus breaking the "" deletion of TOBJ and other object types. "" TODO: This is not very clean and has to be improved in the future. See PR 2741. ENDIF. ENDIF. ENDMETHOD. METHOD deserialize. DATA: ls_item TYPE zif_abapgit_definitions=>ty_item, li_obj TYPE REF TO zif_abapgit_object, lt_remote TYPE zif_abapgit_definitions=>ty_files_tt, lv_package TYPE devclass, lo_files TYPE REF TO zcl_abapgit_objects_files, lo_xml TYPE REF TO zif_abapgit_xml_input, lt_results TYPE zif_abapgit_definitions=>ty_results_tt, li_progress TYPE REF TO zif_abapgit_progress, lv_path TYPE string, lt_items TYPE zif_abapgit_definitions=>ty_items_tt, lt_steps_id TYPE zif_abapgit_definitions=>ty_deserialization_step_tt, lt_steps TYPE zif_abapgit_objects=>ty_step_data_tt, lx_exc TYPE REF TO zcx_abapgit_exception. DATA: lo_folder_logic TYPE REF TO zcl_abapgit_folder_logic. FIELD-SYMBOLS: TYPE zif_abapgit_definitions=>ty_result, TYPE LINE OF zif_abapgit_definitions=>ty_deserialization_step_tt, TYPE LINE OF zif_abapgit_objects=>ty_step_data_tt, TYPE LINE OF zif_abapgit_objects=>ty_deserialization_tt. lt_steps = get_deserialize_steps( ). lv_package = io_repo->get_package( ). IF is_checks-transport-required = abap_true. zcl_abapgit_default_transport=>get_instance( )->set( is_checks-transport-transport ). ENDIF. zcl_abapgit_objects_activation=>clear( ). lt_remote = io_repo->get_files_remote( ). lt_results = files_to_deserialize( io_repo = io_repo ii_log = ii_log ). checks_adjust( EXPORTING io_repo = io_repo is_checks = is_checks CHANGING ct_results = lt_results ). li_progress = zcl_abapgit_progress=>get_instance( lines( lt_results ) ). lt_items = map_results_to_items( lt_results ). check_objects_locked( iv_language = io_repo->get_dot_abapgit( )->get_master_language( ) it_items = lt_items ). lo_folder_logic = zcl_abapgit_folder_logic=>get_instance( ). LOOP AT lt_results ASSIGNING . li_progress->show( iv_current = sy-tabix iv_text = |Deserialize { -obj_name }| ). CLEAR ls_item. ls_item-obj_type = -obj_type. ls_item-obj_name = -obj_name. ""error handling & logging added TRY. "" If package does not exist yet, it will be created with this call lv_package = lo_folder_logic->path_to_package( iv_top = io_repo->get_package( ) io_dot = io_repo->get_dot_abapgit( ) iv_path = -path ). check_main_package( iv_package = lv_package iv_obj_type = ls_item-obj_type ). IF ls_item-obj_type = 'DEVC'. "" Packages have the same filename across different folders. The path needs to be supplied "" to find the correct file. lv_path = -path. ENDIF. CREATE OBJECT lo_files EXPORTING is_item = ls_item iv_path = lv_path. lo_files->set_files( lt_remote ). ""analyze XML in order to instantiate the proper serializer lo_xml = lo_files->read_xml( ). li_obj = create_object( is_item = ls_item iv_language = io_repo->get_dot_abapgit( )->get_master_language( ) is_metadata = lo_xml->get_metadata( ) ). compare_remote_to_local( ii_object = li_obj it_remote = lt_remote is_result = ii_log = ii_log ). li_obj->mo_files = lo_files. ""get required steps for deserialize the object lt_steps_id = li_obj->get_deserialize_steps( ). LOOP AT lt_steps_id ASSIGNING . READ TABLE lt_steps WITH KEY step_id = ASSIGNING . ASSERT sy-subrc = 0. IF -is_ddic = abap_true AND li_obj->get_metadata( )-ddic = abap_false. "" DDIC only for DDIC objects zcx_abapgit_exception=>raise( |Step { } is only for DDIC objects| ). ENDIF. APPEND INITIAL LINE TO -objects ASSIGNING . -item = ls_item. -obj = li_obj. -xml = lo_xml. -package = lv_package. ENDLOOP. CLEAR: lv_path, lv_package. CATCH zcx_abapgit_exception INTO lx_exc. ii_log->add_exception( ix_exc = lx_exc is_item = ls_item ). ii_log->add_error( iv_msg = |Import of object { ls_item-obj_name } failed| is_item = ls_item ). ""object should not be part of any deserialization step CONTINUE. ENDTRY. ENDLOOP. ""run deserialize for all steps and it's objects SORT lt_steps BY order. LOOP AT lt_steps ASSIGNING . deserialize_objects( EXPORTING is_step = ii_log = ii_log CHANGING ct_files = rt_accessed_files ). ENDLOOP. update_package_tree( io_repo->get_package( ) ). SORT rt_accessed_files BY path ASCENDING filename ASCENDING. DELETE ADJACENT DUPLICATES FROM rt_accessed_files. "" Just in case zcl_abapgit_default_transport=>get_instance( )->reset( ). li_progress->off( ). ENDMETHOD. METHOD deserialize_checks. DATA: lt_results TYPE zif_abapgit_definitions=>ty_results_tt, li_package TYPE REF TO zif_abapgit_sap_package. lt_results = files_to_deserialize( io_repo ). rs_checks-overwrite = warning_overwrite_find( lt_results ). rs_checks-warning_package = warning_package_find( io_repo = io_repo it_results = lt_results ). IF lines( lt_results ) > 0. li_package = zcl_abapgit_factory=>get_sap_package( io_repo->get_package( ) ). rs_checks-transport-required = li_package->are_changes_recorded_in_tr_req( ). IF NOT rs_checks-transport-required IS INITIAL. rs_checks-transport-type = li_package->get_transport_type( ). ENDIF. ENDIF. ENDMETHOD. METHOD deserialize_objects. DATA: li_progress TYPE REF TO zif_abapgit_progress, li_exit TYPE REF TO zif_abapgit_exit, lx_exc TYPE REF TO zcx_abapgit_exception. FIELD-SYMBOLS: LIKE LINE OF is_step-objects. zcl_abapgit_objects_activation=>clear( ). li_progress = zcl_abapgit_progress=>get_instance( lines( is_step-objects ) ). LOOP AT is_step-objects ASSIGNING . li_progress->show( iv_current = sy-tabix iv_text = |Deserialize { is_step-descr } - { -item-obj_name }| ). TRY. -obj->deserialize( iv_package = -package io_xml = -xml iv_step = is_step-step_id ii_log = ii_log ). APPEND LINES OF -obj->mo_files->get_accessed_files( ) TO ct_files. ii_log->add_success( iv_msg = |Object { -item-obj_name } imported| is_item = -item ). CATCH zcx_abapgit_exception INTO lx_exc. ii_log->add_exception( ix_exc = lx_exc is_item = -item ). ii_log->add_error( iv_msg = |Import of object { -item-obj_name } failed| is_item = -item ). ENDTRY. ENDLOOP. CASE is_step-step_id. WHEN zif_abapgit_object=>gc_step_id-ddic. zcl_abapgit_objects_activation=>activate( is_step-is_ddic ). WHEN zif_abapgit_object=>gc_step_id-abap. zcl_abapgit_objects_activation=>activate( is_step-is_ddic ). WHEN zif_abapgit_object=>gc_step_id-late. "" late can have both DDIC (like TABL with REF TO) and non-DDIC objects zcl_abapgit_objects_activation=>activate( abap_true ). zcl_abapgit_objects_activation=>activate( abap_false ). ENDCASE. li_progress->off( ). * Call postprocessing li_exit = zcl_abapgit_exit=>get_instance( ). li_exit->deserialize_postprocess( is_step = is_step ii_log = ii_log ). ENDMETHOD. METHOD exists. DATA: li_obj TYPE REF TO zif_abapgit_object. TRY. li_obj = create_object( is_item = is_item iv_language = zif_abapgit_definitions=>c_english ). rv_bool = li_obj->exists( ). CATCH zcx_abapgit_exception. * ignore all errors and assume the object exists rv_bool = abap_true. ENDTRY. ENDMETHOD. METHOD files_to_deserialize. rt_results = adjust_namespaces( prioritize_deser( filter_files_to_deserialize( it_results = zcl_abapgit_file_status=>status( io_repo ) ii_log = ii_log ) ) ). ENDMETHOD. METHOD filter_files_to_deserialize. DATA lt_objects LIKE rt_results. DATA lr_object TYPE REF TO zif_abapgit_definitions=>ty_result. DATA ls_item TYPE zif_abapgit_definitions=>ty_item. DATA lv_tabix TYPE sy-tabix. rt_results = it_results. ""preparation for object logging, sort all file entries by objects IF ii_log IS BOUND. lt_objects = rt_results. SORT lt_objects BY obj_type obj_name. DELETE ADJACENT DUPLICATES FROM lt_objects COMPARING obj_type obj_name. DELETE lt_objects WHERE obj_type IS INITIAL AND obj_name IS INITIAL. ENDIF. ""ignore objects w/o changes DELETE rt_results WHERE match = abap_true. "" Full match ""log objects w/o changes IF sy-subrc = 0 AND ii_log IS BOUND. SORT rt_results BY obj_type obj_name. LOOP AT lt_objects REFERENCE INTO lr_object. lv_tabix = sy-tabix. READ TABLE rt_results WITH KEY obj_type = lr_object->obj_type obj_name = lr_object->obj_name BINARY SEARCH TRANSPORTING NO FIELDS. IF sy-subrc <> 0. ""all parts of the objects have not changed ls_item-devclass = lr_object->package. ls_item-obj_type = lr_object->obj_type. ls_item-obj_name = lr_object->obj_name. ii_log->add_success( iv_msg = |Object { ls_item-obj_name } (type { ls_item-obj_type }) not changed; no import required| is_item = ls_item ). ""ignore object for further messages DELETE lt_objects INDEX lv_tabix. ENDIF. ENDLOOP. ENDIF. ""ignore objects w/o object type DELETE rt_results WHERE obj_type IS INITIAL. ""log objects w/o object type IF sy-subrc = 0 AND ii_log IS BOUND. LOOP AT lt_objects REFERENCE INTO lr_object WHERE obj_type IS INITIAL. CHECK lr_object->obj_name IS NOT INITIAL. ls_item-devclass = lr_object->package. ls_item-obj_type = lr_object->obj_type. ls_item-obj_name = lr_object->obj_name. ii_log->add_warning( iv_msg = |Object type for { ls_item-obj_name } not defined - will be ignored by abapGit| is_item = ls_item ). ENDLOOP. DELETE lt_objects WHERE obj_type IS INITIAL. ENDIF. ""ignore objects that exists only local DELETE rt_results WHERE lstate = zif_abapgit_definitions=>c_state-added AND rstate IS INITIAL. ""ignore objects that where deleted remotely DELETE rt_results WHERE rstate = zif_abapgit_definitions=>c_state-deleted. ""log objects that exists only local or where deleted remotely IF sy-subrc = 0 AND ii_log IS BOUND. SORT rt_results BY obj_type obj_name. LOOP AT lt_objects REFERENCE INTO lr_object. lv_tabix = sy-tabix. READ TABLE rt_results WITH KEY obj_type = lr_object->obj_type obj_name = lr_object->obj_name BINARY SEARCH TRANSPORTING NO FIELDS. IF sy-subrc <> 0. ""all parts exists only local ""no log message; ignore object for further messages DELETE lt_objects INDEX lv_tabix. ENDIF. ENDLOOP. ENDIF. SORT rt_results BY obj_type ASCENDING obj_name ASCENDING rstate DESCENDING "" ensures that non-empty rstate is kept lstate DESCENDING. "" ensures that non-empty lstate is kept DELETE ADJACENT DUPLICATES FROM rt_results COMPARING obj_type obj_name. ENDMETHOD. METHOD get_deserialize_steps. FIELD-SYMBOLS: TYPE LINE OF zif_abapgit_objects=>ty_step_data_tt. APPEND INITIAL LINE TO rt_steps ASSIGNING . -step_id = zif_abapgit_object=>gc_step_id-ddic. -descr = 'Import DDIC objects'. -is_ddic = abap_true. -syntax_check = abap_false. -order = 1. APPEND INITIAL LINE TO rt_steps ASSIGNING . -step_id = zif_abapgit_object=>gc_step_id-abap. -descr = 'Import objects main'. -is_ddic = abap_false. -syntax_check = abap_false. -order = 2. APPEND INITIAL LINE TO rt_steps ASSIGNING . -step_id = zif_abapgit_object=>gc_step_id-late. -descr = 'Import late objects'. -is_ddic = abap_false. -syntax_check = abap_true. -order = 3. ENDMETHOD. METHOD is_active. DATA: li_object TYPE REF TO zif_abapgit_object. TRY. li_object = create_object( is_item = is_item iv_language = sy-langu ). rv_active = li_object->is_active( ). CATCH cx_sy_dyn_call_illegal_method cx_sy_ref_is_initial zcx_abapgit_exception. rv_active = abap_true. ENDTRY. ENDMETHOD. METHOD is_supported. TRY. create_object( is_item = is_item iv_language = zif_abapgit_definitions=>c_english iv_native_only = iv_native_only ). rv_bool = abap_true. CATCH zcx_abapgit_exception. rv_bool = abap_false. ENDTRY. ENDMETHOD. METHOD jump. DATA: li_obj TYPE REF TO zif_abapgit_object, lv_adt_jump_enabled TYPE abap_bool. li_obj = create_object( is_item = is_item iv_language = zif_abapgit_definitions=>c_english ). IF li_obj->exists( ) = abap_false. zcx_abapgit_exception=>raise( |Object { is_item-obj_type } { is_item-obj_name } doesn't exist| ). ENDIF. lv_adt_jump_enabled = zcl_abapgit_persist_settings=>get_instance( )->read( )->get_adt_jump_enabled( ). IF lv_adt_jump_enabled = abap_true. TRY. zcl_abapgit_objects_super=>jump_adt( iv_obj_name = is_item-obj_name iv_obj_type = is_item-obj_type iv_sub_obj_name = iv_sub_obj_name iv_sub_obj_type = iv_sub_obj_type iv_line_number = iv_line_number ). CATCH zcx_abapgit_exception. li_obj->jump( ). ENDTRY. ELSEIF iv_line_number IS NOT INITIAL AND iv_sub_obj_type IS NOT INITIAL AND iv_sub_obj_name IS NOT INITIAL. "" For the line navigation we have to supply the sub object type (i_sub_obj_type). "" If we use is_item-obj_type it navigates only to the object. CALL FUNCTION 'RS_TOOL_ACCESS' EXPORTING operation = 'SHOW' object_name = is_item-obj_name object_type = iv_sub_obj_type include = iv_sub_obj_name position = iv_line_number in_new_window = abap_true EXCEPTIONS not_executed = 1 invalid_object_type = 2 OTHERS = 3. IF sy-subrc <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. ELSE. li_obj->jump( ). ENDIF. ENDMETHOD. METHOD map_results_to_items. DATA: ls_item LIKE LINE OF rt_items. FIELD-SYMBOLS: TYPE zif_abapgit_definitions=>ty_result. LOOP AT it_results ASSIGNING . ls_item-devclass = -package. ls_item-obj_type = -obj_type. ls_item-obj_name = -obj_name. INSERT ls_item INTO TABLE rt_items. ENDLOOP. ENDMETHOD. METHOD map_tadir_to_items. DATA: ls_item LIKE LINE OF rt_items. FIELD-SYMBOLS: TYPE zif_abapgit_definitions=>ty_tadir. LOOP AT it_tadir ASSIGNING . ls_item-devclass = -devclass. ls_item-obj_type = -object. ls_item-obj_name = -obj_name. INSERT ls_item INTO TABLE rt_items. ENDLOOP. ENDMETHOD. METHOD prioritize_deser. * todo, refactor this method FIELD-SYMBOLS: LIKE LINE OF it_results. * WEBI has to be handled before SPRX. LOOP AT it_results ASSIGNING WHERE obj_type = 'WEBI'. APPEND TO rt_results. ENDLOOP. * SPRX has to be handled before depended objects CLAS/INFT/TABL etc. LOOP AT it_results ASSIGNING WHERE obj_type = 'SPRX'. APPEND TO rt_results. ENDLOOP. * XSLT has to be handled before CLAS/PROG LOOP AT it_results ASSIGNING WHERE obj_type = 'XSLT'. APPEND TO rt_results. ENDLOOP. * PROG before internet services, as the services might use the screens LOOP AT it_results ASSIGNING WHERE obj_type = 'PROG'. APPEND TO rt_results. ENDLOOP. * ISAP has to be handled before ISRP LOOP AT it_results ASSIGNING WHERE obj_type = 'IASP'. APPEND TO rt_results. ENDLOOP. * ENHS has to be handled before ENHO LOOP AT it_results ASSIGNING WHERE obj_type = 'ENHS'. APPEND TO rt_results. ENDLOOP. * DDLS has to be handled before DCLS LOOP AT it_results ASSIGNING WHERE obj_type = 'DDLS'. APPEND TO rt_results. ENDLOOP. * IOBJ has to be handled before ODSO LOOP AT it_results ASSIGNING WHERE obj_type = 'IOBJ'. APPEND TO rt_results. ENDLOOP. * TOBJ has to be handled before SCP1 LOOP AT it_results ASSIGNING WHERE obj_type = 'TOBJ'. APPEND TO rt_results. ENDLOOP. * OTGR has to be handled before CHAR LOOP AT it_results ASSIGNING WHERE obj_type = 'OTGR'. APPEND TO rt_results. ENDLOOP. LOOP AT it_results ASSIGNING WHERE obj_type <> 'IASP' AND obj_type <> 'PROG' AND obj_type <> 'XSLT' AND obj_type <> 'PINF' AND obj_type <> 'DEVC' AND obj_type <> 'ENHS' AND obj_type <> 'DDLS' AND obj_type <> 'SPRX' AND obj_type <> 'WEBI' AND obj_type <> 'IOBJ' AND obj_type <> 'TOBJ' AND obj_type <> 'OTGR'. APPEND TO rt_results. ENDLOOP. * PINF after everything as it can expose objects LOOP AT it_results ASSIGNING WHERE obj_type = 'PINF'. APPEND TO rt_results. ENDLOOP. * DEVC after PINF, as it can refer for package interface usage LOOP AT it_results ASSIGNING WHERE obj_type = 'DEVC'. APPEND TO rt_results. ENDLOOP. ENDMETHOD. METHOD serialize. DATA: li_obj TYPE REF TO zif_abapgit_object, li_xml TYPE REF TO zif_abapgit_xml_output, lo_files TYPE REF TO zcl_abapgit_objects_files, ls_i18n_params TYPE zif_abapgit_definitions=>ty_i18n_params. FIELD-SYMBOLS: LIKE LINE OF rs_files_and_item-files. rs_files_and_item-item = is_item. IF is_supported( rs_files_and_item-item ) = abap_false. zcx_abapgit_exception=>raise( |Object type ignored, not supported: { rs_files_and_item-item-obj_type }-{ rs_files_and_item-item-obj_name }| ). ENDIF. CREATE OBJECT lo_files EXPORTING is_item = rs_files_and_item-item. li_obj = create_object( is_item = rs_files_and_item-item iv_language = iv_language ). li_obj->mo_files = lo_files. CREATE OBJECT li_xml TYPE zcl_abapgit_xml_output. ls_i18n_params-main_language = iv_language. ls_i18n_params-main_language_only = iv_serialize_master_lang_only. ls_i18n_params-translation_languages = it_translation_langs. li_xml->i18n_params( ls_i18n_params ). li_obj->serialize( li_xml ). lo_files->add_xml( ii_xml = li_xml is_metadata = li_obj->get_metadata( ) ). rs_files_and_item-files = lo_files->get_files( ). check_duplicates( rs_files_and_item-files ). rs_files_and_item-item-inactive = boolc( li_obj->is_active( ) = abap_false ). LOOP AT rs_files_and_item-files ASSIGNING . -sha1 = zcl_abapgit_hash=>sha1_blob( -data ). ENDLOOP. ENDMETHOD. METHOD supported_list. DATA: lt_objects TYPE STANDARD TABLE OF ko100, lv_supported TYPE abap_bool, ls_item TYPE zif_abapgit_definitions=>ty_item. FIELD-SYMBOLS LIKE LINE OF lt_objects. CALL FUNCTION 'TR_OBJECT_TABLE' TABLES wt_object_text = lt_objects EXCEPTIONS OTHERS = 1 ##FM_SUBRC_OK. LOOP AT lt_objects ASSIGNING WHERE pgmid = 'R3TR'. ls_item-obj_type = -object. lv_supported = is_supported( is_item = ls_item iv_native_only = abap_true ). IF lv_supported = abap_true. INSERT -object INTO TABLE rt_types. ENDIF. ENDLOOP. ENDMETHOD. METHOD update_package_tree. DATA: lt_packages TYPE zif_abapgit_sap_package=>ty_devclass_tt, lv_package LIKE LINE OF lt_packages, lv_tree TYPE dirtree-tname. lt_packages = zcl_abapgit_factory=>get_sap_package( iv_package )->list_subpackages( ). APPEND iv_package TO lt_packages. LOOP AT lt_packages INTO lv_package. * update package tree for SE80 lv_tree = 'EU_' && lv_package. CALL FUNCTION 'WB_TREE_ACTUALIZE' EXPORTING tree_name = lv_tree without_crossreference = abap_true with_tcode_index = abap_true. ENDLOOP. ENDMETHOD. METHOD warning_overwrite_adjust. DATA: lt_overwrite LIKE it_overwrite, ls_overwrite LIKE LINE OF lt_overwrite. FIELD-SYMBOLS: LIKE LINE OF lt_overwrite. * make sure to get the current status, as something might have changed in the meanwhile lt_overwrite = warning_overwrite_find( ct_results ). LOOP AT lt_overwrite ASSIGNING . READ TABLE it_overwrite INTO ls_overwrite WITH TABLE KEY object_type_and_name COMPONENTS obj_type = -obj_type obj_name = -obj_name. IF sy-subrc <> 0 OR ls_overwrite-decision IS INITIAL. zcx_abapgit_exception=>raise( |Overwrite { -obj_type } { -obj_name } undecided| ). ENDIF. IF ls_overwrite-decision = 'N'. DELETE ct_results WHERE obj_type = -obj_type AND obj_name = -obj_name. ASSERT sy-subrc = 0. ENDIF. ENDLOOP. ENDMETHOD. METHOD warning_overwrite_find. DATA: ls_overwrite LIKE LINE OF rt_overwrite. FIELD-SYMBOLS: LIKE LINE OF it_results. LOOP AT it_results ASSIGNING WHERE NOT obj_type IS INITIAL. IF -lstate IS NOT INITIAL AND NOT ( -lstate = zif_abapgit_definitions=>c_state-added AND -rstate IS INITIAL ). "" current object has been modified or deleted locally, add to table CLEAR ls_overwrite. MOVE-CORRESPONDING TO ls_overwrite. APPEND ls_overwrite TO rt_overwrite. ENDIF. ENDLOOP. SORT rt_overwrite. DELETE ADJACENT DUPLICATES FROM rt_overwrite. ENDMETHOD. METHOD warning_package_adjust. DATA: lt_overwrite LIKE it_overwrite, ls_overwrite LIKE LINE OF lt_overwrite. FIELD-SYMBOLS: LIKE LINE OF lt_overwrite. * make sure to get the current status, as something might have changed in the meanwhile lt_overwrite = warning_package_find( it_results = ct_results io_repo = io_repo ). LOOP AT lt_overwrite ASSIGNING . READ TABLE it_overwrite INTO ls_overwrite WITH TABLE KEY object_type_and_name COMPONENTS obj_type = -obj_type obj_name = -obj_name. IF sy-subrc <> 0 OR ls_overwrite-decision IS INITIAL. zcx_abapgit_exception=>raise( |Overwrite of package { -obj_type } { -obj_name } undecided| ). ENDIF. IF ls_overwrite-decision = 'N'. DELETE ct_results WHERE obj_type = -obj_type AND obj_name = -obj_name. ASSERT sy-subrc = 0. ENDIF. ENDLOOP. ENDMETHOD. METHOD warning_package_find. DATA: lv_package TYPE devclass, lt_overwrite_unique TYPE HASHED TABLE OF zif_abapgit_definitions=>ty_overwrite WITH UNIQUE KEY obj_type obj_name devclass, ls_overwrite LIKE LINE OF rt_overwrite, ls_tadir TYPE zif_abapgit_definitions=>ty_tadir. DATA: lo_folder_logic TYPE REF TO zcl_abapgit_folder_logic. FIELD-SYMBOLS: LIKE LINE OF it_results. lo_folder_logic = zcl_abapgit_folder_logic=>get_instance( ). LOOP AT it_results ASSIGNING . lv_package = lo_folder_logic->path_to_package( iv_top = io_repo->get_package( ) io_dot = io_repo->get_dot_abapgit( ) iv_path = -path iv_create_if_not_exists = abap_false ). ls_tadir = zcl_abapgit_factory=>get_tadir( )->read_single( iv_object = -obj_type iv_obj_name = -obj_name ). IF NOT ls_tadir IS INITIAL AND ls_tadir-devclass <> lv_package. * overwriting object from different package than expected CLEAR ls_overwrite. ls_overwrite-obj_type = -obj_type. ls_overwrite-obj_name = -obj_name. ls_overwrite-devclass = ls_tadir-devclass. INSERT ls_overwrite INTO TABLE lt_overwrite_unique. ENDIF. ENDLOOP. rt_overwrite = lt_overwrite_unique. ENDMETHOD. ENDCLASS. ",11814,True,2533.4732545410693,median "[MusicConfig] Location=20309 Rex - Heart of Witch/Heart of Witch.mp3 Extension=mp3 MD5=10‌​52‌​47‌​7f‌​50‌​9d‌​b4‌​f1‌​8a‌​83‌​36‌​29‌​56‌​0b‌​dc‌​a9 Source=OSU MetreNumber=4 Title=Heart of Witch [TagConfig] Tagger=Carra Time=2017/2/6 17:56:18 Confidence=2 [MiscConfig] LinkedFile=20309 Rex - Heart of Witch/Rex - Heart of Witch (yeahyeahyeahhh) [MXStyle].osu osuMapID=20309 [BeatInfo] Count=268 Beat_0={0.634,1,B min,Bm} Beat_1={0.986941176470588,0,B min,Bm} Beat_2={1.3398823529411761,0,B min,C} Beat_3={1.692823529411764,0,B min,C} Beat_4={2.0457647058823518,1,B min,Bm} Beat_5={2.3987058823529397,0,B min,Em} Beat_6={2.751647058823528,0,B min,Bm} Beat_7={3.1045882352941159,0,B min,C} Beat_8={3.4575294117647037,1,B min,Bm} Beat_9={3.8104705882352916,0,B min,Bm} Beat_10={4.16341176470588,0,B min,C} Beat_11={4.5163529411764678,0,B min,C} Beat_12={4.8692941176470566,1,B min,Bm} Beat_13={5.2222352941176444,0,B min,Em} Beat_14={5.5751764705882323,0,B min,Bm} Beat_15={5.92811764705882,0,B min,C} Beat_16={6.281058823529408,1,B min,Bm} Beat_17={6.6339999999999959,0,B min,Bm} Beat_18={6.9869411764705838,0,B min,Em} Beat_19={7.3398823529411716,0,B min,Bm} Beat_20={7.6928235294117595,1,B min,Bm} Beat_21={8.0457647058823483,0,B min,C} Beat_22={8.3987058823529352,0,B min,C} Beat_23={8.751647058823524,0,B min,Bb} Beat_24={9.1045882352941128,1,B min,Bm} Beat_25={9.4575294117647,0,B min,Bm} Beat_26={9.8104705882352885,0,B min,Em} Beat_27={10.163411764705876,0,B min,D} Beat_28={10.516352941176464,1,B min,D} Beat_29={10.869294117647051,0,B min,C} Beat_30={11.22223529411764,0,B min,C} Beat_31={11.575176470588227,0,B min,Bb} Beat_32={11.928117647058816,1,B min,B} Beat_33={12.281058823529405,0,B min,B} Beat_34={12.633999999999992,0,B min,B} Beat_35={12.98694117647058,0,B min,B} Beat_36={13.339882352941167,1,B min,B} Beat_37={13.692823529411756,0,B min,B} Beat_38={14.045764705882343,0,B min,B} Beat_39={14.398705882352932,0,B min,B} Beat_40={14.751647058823519,1,B min,B} Beat_41={15.104588235294107,0,B min,B} Beat_42={15.457529411764696,0,B min,B} Beat_43={15.810470588235283,0,B min,Em} Beat_44={16.16341176470587,1,B min,Em} Beat_45={16.516352941176457,0,B min,Em} Beat_46={16.869294117647048,0,B min,D} Beat_47={17.222235294117635,0,B min,C} Beat_48={17.575176470588225,1,B min,B} Beat_49={17.928117647058812,0,B min,B} Beat_50={18.2810588235294,0,B min,B} Beat_51={18.633999999999986,0,B min,G} Beat_52={18.986941176470577,1,B min,B} Beat_53={19.339882352941164,0,B min,B} Beat_54={19.692823529411751,0,B min,B} Beat_55={20.045764705882338,0,B min,G} Beat_56={20.398705882352928,1,B min,Bm} Beat_57={20.751647058823515,0,B min,Bm} Beat_58={21.104588235294102,0,B min,Bm} Beat_59={21.457529411764693,0,B min,Em} Beat_60={21.81047058823528,1,B min,Em} Beat_61={22.163411764705867,0,B min,Em} Beat_62={22.516352941176454,0,B min,D} Beat_63={22.869294117647044,0,B min,C} Beat_64={23.222235294117631,1,B min,C} Beat_65={23.575176470588218,0,B min,C} Beat_66={23.928117647058809,0,B min,D} Beat_67={24.281058823529396,0,B min,A} Beat_68={24.633999999999983,1,B min,G} Beat_69={24.98694117647057,0,B min,A} Beat_70={25.33988235294116,0,B min,Bm} Beat_71={25.692823529411747,0,B min,Bm} Beat_72={26.045764705882334,1,B min,Bm} Beat_73={26.398705882352925,0,B min,Bm} Beat_74={26.751647058823512,0,B min,Bm} Beat_75={27.1045882352941,0,B min,C#m} Beat_76={27.457529411764686,1,B min,Bm} Beat_77={27.810470588235276,0,B min,A} Beat_78={28.163411764705863,0,B min,G} Beat_79={28.51635294117645,0,B min,B} Beat_80={28.869294117647037,1,B min,B} Beat_81={29.222235294117628,0,B min,Em} Beat_82={29.575176470588215,0,B min,D} Beat_83={29.9281176470588,0,B min,A} Beat_84={30.281058823529392,1,B min,Bm} Beat_85={30.633999999999979,0,B min,A} Beat_86={30.986941176470566,0,B min,G} Beat_87={31.339882352941153,0,B min,Bm} Beat_88={31.692823529411744,1,B min,Bm} Beat_89={32.045764705882327,0,B min,Em} Beat_90={32.398705882352914,0,B min,D} Beat_91={32.751647058823508,0,B min,C#m} Beat_92={33.104588235294095,1,B min,Bm} Beat_93={33.457529411764682,0,B min,A} Beat_94={33.810470588235269,0,B min,G} Beat_95={34.163411764705856,0,B min,F#} Beat_96={34.51635294117645,1,B min,Em} Beat_97={34.869294117647037,0,B min,Em} Beat_98={35.222235294117624,0,B min,Em} Beat_99={35.575176470588211,0,B min,Em} Beat_100={35.9281176470588,1,B min,Em} Beat_101={36.281058823529385,0,B min,Bm} Beat_102={36.633999999999972,0,B min,Bm} Beat_103={36.986941176470559,0,B min,Bm} Beat_104={37.339882352941153,1,B min,C} Beat_105={37.69282352941174,0,B min,C} Beat_106={38.045764705882327,0,B min,C} Beat_107={38.398705882352914,0,B min,C} Beat_108={38.7516470588235,1,B min,C#dim} Beat_109={39.104588235294088,0,B min,C#dim} Beat_110={39.457529411764675,0,B min,C#dim} Beat_111={39.810470588235269,0,B min,C#dim} Beat_112={40.163411764705856,1,B min,Em} Beat_113={40.516352941176443,0,B min,Em} Beat_114={40.86929411764703,0,B min,Em} Beat_115={41.222235294117617,0,B min,Em} Beat_116={41.575176470588204,1,B min,Bm} Beat_117={41.928117647058791,0,B min,Bm} Beat_118={42.281058823529385,0,B min,Bm} Beat_119={42.633999999999972,0,B min,Bm} Beat_120={42.986941176470559,1,B min,C} Beat_121={43.339882352941146,0,B min,C} Beat_122={43.692823529411733,0,B min,C} Beat_123={44.04576470588232,0,B min,C} Beat_124={44.398705882352907,1,B min,C#} Beat_125={44.7516470588235,0,B min,C#} Beat_126={45.104588235294088,0,B min,C#} Beat_127={45.457529411764675,0,B min,C#} Beat_128={45.810470588235262,1,B min,C} Beat_129={46.163411764705849,0,B min,C} Beat_130={46.516352941176436,0,B min,C} Beat_131={46.869294117647023,0,B min,C} Beat_132={47.222235294117617,1,B min,C#} Beat_133={47.575176470588204,0,B min,C#} Beat_134={47.928117647058791,0,B min,C#} Beat_135={48.281058823529378,0,B min,C#} Beat_136={48.633999999999965,1,B min,Em} Beat_137={48.986941176470552,0,B min,Em} Beat_138={49.339882352941139,0,B min,Em} Beat_139={49.692823529411733,0,B min,Em} Beat_140={50.04576470588232,1,B min,Em} Beat_141={50.398705882352907,0,B min,Em} Beat_142={50.751647058823494,0,B min,Em} Beat_143={51.104588235294081,0,B min,Em} Beat_144={51.457529411764668,1,B min,B} Beat_145={51.810470588235255,0,B min,B} Beat_146={52.163411764705849,0,B min,B} Beat_147={52.516352941176436,0,B min,C} Beat_148={52.869294117647023,1,B min,B} Beat_149={53.22223529411761,0,B min,B} Beat_150={53.5751764705882,0,B min,B} Beat_151={53.928117647058784,0,B min,C} Beat_152={54.281058823529371,1,B min,B} Beat_153={54.633999999999965,0,B min,B} Beat_154={54.986941176470552,0,B min,B} Beat_155={55.339882352941139,0,B min,C} Beat_156={55.692823529411726,1,B min,B} Beat_157={56.045764705882313,0,B min,Em} Beat_158={56.3987058823529,0,B min,D} Beat_159={56.751647058823487,0,B min,C} Beat_160={57.104588235294074,1,B min,B} Beat_161={57.457529411764668,0,B min,B} Beat_162={57.810470588235255,0,B min,B} Beat_163={58.163411764705842,0,B min,G} Beat_164={58.516352941176429,1,B min,B} Beat_165={58.869294117647016,0,B min,B} Beat_166={59.2222352941176,0,B min,B} Beat_167={59.57517647058819,0,B min,G} Beat_168={59.928117647058784,1,B min,Bm} Beat_169={60.281058823529371,0,B min,Bm} Beat_170={60.633999999999958,0,B min,Bm} Beat_171={60.986941176470545,0,B min,Em} Beat_172={61.339882352941132,1,B min,Em} Beat_173={61.692823529411719,0,B min,Em} Beat_174={62.045764705882306,0,B min,D} Beat_175={62.3987058823529,0,B min,C} Beat_176={62.751647058823487,1,B min,Bm} Beat_177={63.104588235294074,0,B min,Bm} Beat_178={63.457529411764661,0,B min,F#} Beat_179={63.810470588235248,0,B min,F#} Beat_180={64.163411764705828,1,B min,Bm} Beat_181={64.516352941176422,0,B min,Bm} Beat_182={64.869294117647016,0,B min,F#} Beat_183={65.2222352941176,0,B min,F#} Beat_184={65.57517647058819,1,B min,C#m} Beat_185={65.928117647058784,0,B min,C#m} Beat_186={66.281058823529364,0,B min,Ab} Beat_187={66.633999999999958,0,B min,Ab} Beat_188={66.986941176470538,1,B min,C#m} Beat_189={67.339882352941132,0,B min,C#m} Beat_190={67.692823529411712,0,B min,C#m} Beat_191={68.0457647058823,0,B min,Ab} Beat_192={68.3987058823529,1,B min,Bm} Beat_193={68.75164705882348,0,B min,Bm} Beat_194={69.104588235294074,0,B min,Bm} Beat_195={69.457529411764654,0,B min,C#m} Beat_196={69.810470588235248,1,B min,C#m} Beat_197={70.163411764705828,0,B min,C#m} Beat_198={70.516352941176422,0,B min,Ab} Beat_199={70.869294117647,0,B min,Ab} Beat_200={71.2222352941176,1,B min,Em} Beat_201={71.57517647058819,0,B min,Bm} Beat_202={71.92811764705877,0,B min,C#dim} Beat_203={72.281058823529364,0,B min,Bm} Beat_204={72.633999999999944,1,B min,F#} Beat_205={72.986941176470538,0,B min,F#} Beat_206={73.339882352941117,0,B min,F#} Beat_207={73.692823529411712,0,B min,F#} Beat_208={74.0457647058823,1,B min,Bm} Beat_209={74.398705882352886,0,B min,Bm} Beat_210={74.75164705882348,0,B min,Bm} Beat_211={75.104588235294059,0,B min,Bm} Beat_212={75.457529411764654,1,B min,Bm} Beat_213={75.810470588235233,0,B min,Bm} Beat_214={76.163411764705828,0,B min,Bm} Beat_215={76.516352941176422,0,B min,Bm} Beat_216={76.869294117647,1,B min,Bm} Beat_217={77.2222352941176,0,B min,Bm} Beat_218={77.575176470588175,0,B min,Bm} Beat_219={77.92811764705877,0,B min,Bm} Beat_220={78.281058823529349,1,B min,Bm} Beat_221={78.633999999999944,0,B min,Bm} Beat_222={78.986941176470538,0,B min,F} Beat_223={79.339882352941117,0,B min,Em} Beat_224={79.692823529411712,1,B min,Bm} Beat_225={80.045764705882291,0,B min,Bm} Beat_226={80.398705882352886,0,B min,Bm} Beat_227={80.751647058823465,0,B min,Bm} Beat_228={81.104588235294059,1,B min,Bm} Beat_229={81.457529411764654,0,B min,Bm} Beat_230={81.810470588235233,0,B min,Bm} Beat_231={82.163411764705828,0,B min,Bm} Beat_232={82.516352941176407,1,B min,Bm} Beat_233={82.869294117647,0,B min,Bm} Beat_234={83.222235294117581,0,B min,Bm} Beat_235={83.575176470588175,0,B min,Bm} Beat_236={83.92811764705877,1,B min,B} Beat_237={84.281058823529349,0,B min,B} Beat_238={84.633999999999944,0,B min,B} Beat_239={84.986941176470523,0,B min,B} Beat_240={85.339882352941117,1,B min,B} Beat_241={85.6928235294117,0,B min,B} Beat_242={86.045764705882291,0,B min,B} Beat_243={86.398705882352886,0,B min,B} Beat_244={86.751647058823465,1,B min,B} Beat_245={87.104588235294059,0,B min,B} Beat_246={87.457529411764639,0,B min,B} Beat_247={87.810470588235233,0,B min,B} Beat_248={88.163411764705813,1,B min,B} Beat_249={88.516352941176407,0,B min,B} Beat_250={88.869294117647,0,B min,B} Beat_251={89.222235294117581,0,B min,B} Beat_252={89.575176470588175,1,B min,B} Beat_253={89.928117647058755,0,B min,B} Beat_254={90.281058823529349,0,B min,B} Beat_255={90.633999999999929,0,B min,N} Beat_256={90.986941176470523,1,B min,N} Beat_257={91.339882352941117,0,B min,N} Beat_258={91.6928235294117,0,B min,N} Beat_259={92.045764705882291,0,B min,N} Beat_260={92.398705882352871,1,B min,N} Beat_261={92.751647058823465,0,B min,N} Beat_262={93.104588235294045,0,B min,N} Beat_263={93.457529411764639,0,B min,N} Beat_264={93.810470588235233,1,B min,N} Beat_265={94.163411764705813,0,B min,N} Beat_266={94.516352941176407,0,B min,N} Beat_267={94.869294117646987,0,B min,N} ",8199,True,3007.193626756604,median "CLASS zcl_abapgit_object_clas DEFINITION PUBLIC INHERITING FROM zcl_abapgit_objects_program. PUBLIC SECTION. INTERFACES zif_abapgit_object. ALIASES mo_files FOR zif_abapgit_object~mo_files. METHODS: constructor IMPORTING is_item TYPE zif_abapgit_definitions=>ty_item iv_language TYPE spras. PROTECTED SECTION. DATA: mi_object_oriented_object_fct TYPE REF TO zif_abapgit_oo_object_fnc, mv_skip_testclass TYPE abap_bool, mv_classpool_name TYPE progname. METHODS: deserialize_abap IMPORTING io_xml TYPE REF TO zcl_abapgit_xml_input iv_package TYPE devclass RAISING zcx_abapgit_exception, deserialize_docu IMPORTING io_xml TYPE REF TO zcl_abapgit_xml_input RAISING zcx_abapgit_exception, deserialize_tpool IMPORTING io_xml TYPE REF TO zcl_abapgit_xml_input RAISING zcx_abapgit_exception, deserialize_sotr IMPORTING io_xml TYPE REF TO zcl_abapgit_xml_input iv_package TYPE devclass RAISING zcx_abapgit_exception, serialize_xml IMPORTING io_xml TYPE REF TO zcl_abapgit_xml_output RAISING zcx_abapgit_exception, serialize_attr IMPORTING !io_xml TYPE REF TO zcl_abapgit_xml_output !iv_clsname TYPE seoclsname RAISING zcx_abapgit_exception, serialize_descr IMPORTING !io_xml TYPE REF TO zcl_abapgit_xml_output !iv_clsname TYPE seoclsname RAISING zcx_abapgit_exception, serialize_docu IMPORTING !io_xml TYPE REF TO zcl_abapgit_xml_output !it_langu_additional TYPE zif_abapgit_lang_definitions=>tt_langu OPTIONAL !iv_clsname TYPE seoclsname RAISING zcx_abapgit_exception, serialize_tpool IMPORTING !io_xml TYPE REF TO zcl_abapgit_xml_output !it_langu_additional TYPE zif_abapgit_lang_definitions=>tt_langu OPTIONAL !iv_clsname TYPE seoclsname RAISING zcx_abapgit_exception, serialize_sotr IMPORTING !io_xml TYPE REF TO zcl_abapgit_xml_output RAISING zcx_abapgit_exception, source_apack_replacement CHANGING !ct_source TYPE seop_source_string RAISING zcx_abapgit_exception, repo_apack_replacement CHANGING !ct_source TYPE seop_source_string RAISING zcx_abapgit_exception. PRIVATE SECTION. METHODS: is_class_locked RETURNING VALUE(rv_is_class_locked) TYPE abap_bool RAISING zcx_abapgit_exception. ENDCLASS. CLASS ZCL_ABAPGIT_OBJECT_CLAS IMPLEMENTATION. METHOD constructor. super->constructor( is_item = is_item iv_language = iv_language ). CREATE OBJECT mi_object_oriented_object_fct TYPE zcl_abapgit_oo_class. mv_classpool_name = cl_oo_classname_service=>get_classpool_name( |{ is_item-obj_name }| ). ENDMETHOD. METHOD deserialize_abap. * same as in zcl_abapgit_object_clas, but without ""mo_object_oriented_object_fct->add_to_activation_list"" DATA: ls_vseoclass TYPE vseoclass, lt_source TYPE seop_source_string, lt_local_definitions TYPE seop_source_string, lt_local_implementations TYPE seop_source_string, lt_local_macros TYPE seop_source_string, lt_test_classes TYPE seop_source_string, lt_descriptions TYPE zif_abapgit_definitions=>ty_seocompotx_tt, ls_class_key TYPE seoclskey, lt_attributes TYPE zif_abapgit_definitions=>ty_obj_attribute_tt. lt_source = mo_files->read_abap( ). lt_local_definitions = mo_files->read_abap( iv_extra = 'locals_def' iv_error = abap_false ). lt_local_implementations = mo_files->read_abap( iv_extra = 'locals_imp' iv_error = abap_false ). lt_local_macros = mo_files->read_abap( iv_extra = 'macros' iv_error = abap_false ). lt_test_classes = mo_files->read_abap( iv_extra = 'testclasses' iv_error = abap_false ). ls_class_key-clsname = ms_item-obj_name. io_xml->read( EXPORTING iv_name = 'VSEOCLASS' CHANGING cg_data = ls_vseoclass ). io_xml->read( EXPORTING iv_name = 'ATTRIBUTES' CHANGING cg_data = lt_attributes ). mi_object_oriented_object_fct->create( EXPORTING iv_package = iv_package it_attributes = lt_attributes CHANGING cg_properties = ls_vseoclass ). mi_object_oriented_object_fct->generate_locals( is_key = ls_class_key iv_force = abap_true it_local_definitions = lt_local_definitions it_local_implementations = lt_local_implementations it_local_macros = lt_local_macros it_local_test_classes = lt_test_classes ). repo_apack_replacement( CHANGING ct_source = lt_source ). mi_object_oriented_object_fct->deserialize_source( is_key = ls_class_key it_source = lt_source ). io_xml->read( EXPORTING iv_name = 'DESCRIPTIONS' CHANGING cg_data = lt_descriptions ). mi_object_oriented_object_fct->update_descriptions( is_key = ls_class_key it_descriptions = lt_descriptions ). ENDMETHOD. METHOD deserialize_docu. DATA: lt_lines TYPE tlinetab, lv_object TYPE dokhl-object, lt_i18n_lines TYPE zif_abapgit_lang_definitions=>tt_i18n_lines, ls_i18n_lines TYPE zif_abapgit_lang_definitions=>ty_i18n_lines. io_xml->read( EXPORTING iv_name = 'LINES' CHANGING cg_data = lt_lines ). IF lines( lt_lines ) = 0. RETURN. ENDIF. lv_object = ms_item-obj_name. mi_object_oriented_object_fct->create_documentation( it_lines = lt_lines iv_object_name = lv_object iv_language = mv_language ). io_xml->read( EXPORTING iv_name = 'I18N_LINES' CHANGING cg_data = lt_i18n_lines ). LOOP AT lt_i18n_lines INTO ls_i18n_lines. mi_object_oriented_object_fct->create_documentation( it_lines = ls_i18n_lines-lines iv_object_name = lv_object iv_language = ls_i18n_lines-language iv_no_masterlang = abap_true ). ENDLOOP. ENDMETHOD. METHOD deserialize_sotr. ""OTR stands for Online Text Repository mi_object_oriented_object_fct->create_sotr( iv_object_name = ms_item-obj_name iv_package = iv_package io_xml = io_xml ). ENDMETHOD. METHOD deserialize_tpool. DATA: lv_clsname TYPE seoclsname, lt_tpool_ext TYPE zif_abapgit_definitions=>ty_tpool_tt, lt_tpool TYPE textpool_table, lt_i18n_tpool TYPE zif_abapgit_lang_definitions=>tt_i18n_tpool, ls_i18n_tpool TYPE zif_abapgit_lang_definitions=>ty_i18n_tpool. io_xml->read( EXPORTING iv_name = 'TPOOL' CHANGING cg_data = lt_tpool_ext ). lt_tpool = read_tpool( lt_tpool_ext ). IF lines( lt_tpool ) = 0. RETURN. ENDIF. lv_clsname = ms_item-obj_name. mi_object_oriented_object_fct->insert_text_pool( iv_class_name = lv_clsname it_text_pool = lt_tpool iv_language = mv_language ). io_xml->read( EXPORTING iv_name = 'I18N_TPOOL' CHANGING cg_data = lt_i18n_tpool ). LOOP AT lt_i18n_tpool INTO ls_i18n_tpool. lt_tpool = read_tpool( ls_i18n_tpool-textpool ). mi_object_oriented_object_fct->insert_text_pool( iv_class_name = lv_clsname it_text_pool = lt_tpool iv_language = ls_i18n_tpool-language iv_state = 'A' ). ENDLOOP. ENDMETHOD. METHOD is_class_locked. DATA: lv_argument TYPE seqg3-garg. lv_argument = ms_item-obj_name. OVERLAY lv_argument WITH '=============================='. lv_argument = lv_argument && '*'. rv_is_class_locked = exists_a_lock_entry_for( iv_lock_object = 'ESEOCLASS' iv_argument = lv_argument ). ENDMETHOD. METHOD repo_apack_replacement. FIELD-SYMBOLS: LIKE LINE OF ct_source. LOOP AT ct_source ASSIGNING . FIND FIRST OCCURRENCE OF REGEX '^\\s*INTERFACES(:| )\\s*if_apack_manifest\\s*.' IN . IF sy-subrc = 0. REPLACE FIRST OCCURRENCE OF 'if_apack_manifest' IN WITH 'zif_apack_manifest' IGNORING CASE. REPLACE ALL OCCURRENCES OF 'if_apack_manifest~descriptor' IN TABLE ct_source WITH 'zif_apack_manifest~descriptor' IGNORING CASE. EXIT. ENDIF. FIND FIRST OCCURRENCE OF REGEX '^\\s*PROTECTED\\s*SECTION\\s*.' IN . IF sy-subrc = 0. EXIT. ENDIF. ENDLOOP. ENDMETHOD. METHOD serialize_attr. DATA: lt_attributes TYPE zif_abapgit_definitions=>ty_obj_attribute_tt. lt_attributes = mi_object_oriented_object_fct->read_attributes( iv_clsname ). IF lines( lt_attributes ) = 0. RETURN. ENDIF. io_xml->add( iv_name = 'ATTRIBUTES' ig_data = lt_attributes ). ENDMETHOD. METHOD serialize_descr. DATA: lt_descriptions TYPE zif_abapgit_definitions=>ty_seocompotx_tt, lv_language TYPE spras. IF io_xml->i18n_params( )-serialize_master_lang_only = abap_true. lv_language = mv_language. ENDIF. lt_descriptions = mi_object_oriented_object_fct->read_descriptions( iv_obejct_name = iv_clsname iv_language = lv_language ). IF lines( lt_descriptions ) = 0. RETURN. ENDIF. io_xml->add( iv_name = 'DESCRIPTIONS' ig_data = lt_descriptions ). ENDMETHOD. METHOD serialize_docu. DATA: lt_lines TYPE tlinetab, lv_langu TYPE langu, lt_i18n_lines TYPE zif_abapgit_lang_definitions=>tt_i18n_lines, ls_i18n_lines TYPE zif_abapgit_lang_definitions=>ty_i18n_lines. lt_lines = mi_object_oriented_object_fct->read_documentation( iv_class_name = iv_clsname iv_language = mv_language ). IF lines( lt_lines ) > 0. io_xml->add( iv_name = 'LINES' ig_data = lt_lines ). ENDIF. IF io_xml->i18n_params( )-serialize_master_lang_only IS NOT INITIAL. RETURN. ENDIF. LOOP AT it_langu_additional INTO lv_langu. CLEAR: ls_i18n_lines. lt_lines = mi_object_oriented_object_fct->read_documentation( iv_class_name = iv_clsname iv_language = lv_langu ). ls_i18n_lines-language = lv_langu. ls_i18n_lines-lines = lt_lines. INSERT ls_i18n_lines INTO TABLE lt_i18n_lines. ENDLOOP. IF lines( lt_i18n_lines ) > 0. io_xml->add( iv_name = 'I18N_LINES' ig_data = lt_i18n_lines ). ENDIF. ENDMETHOD. METHOD serialize_sotr. mi_object_oriented_object_fct->read_sotr( iv_object_name = ms_item-obj_name io_xml = io_xml ). ENDMETHOD. METHOD serialize_tpool. DATA: lt_tpool TYPE textpool_table, lv_langu TYPE langu, lt_i18n_tpool TYPE zif_abapgit_lang_definitions=>tt_i18n_tpool, ls_i18n_tpool TYPE zif_abapgit_lang_definitions=>ty_i18n_tpool. lt_tpool = mi_object_oriented_object_fct->read_text_pool( iv_class_name = iv_clsname iv_language = mv_language ). io_xml->add( iv_name = 'TPOOL' ig_data = add_tpool( lt_tpool ) ). IF io_xml->i18n_params( )-serialize_master_lang_only IS NOT INITIAL. RETURN. ENDIF. LOOP AT it_langu_additional INTO lv_langu. CLEAR: ls_i18n_tpool. lt_tpool = mi_object_oriented_object_fct->read_text_pool( iv_class_name = iv_clsname iv_language = lv_langu ). ls_i18n_tpool-language = lv_langu. ls_i18n_tpool-textpool = add_tpool( lt_tpool ). INSERT ls_i18n_tpool INTO TABLE lt_i18n_tpool. ENDLOOP. IF lines( lt_i18n_tpool ) > 0. io_xml->add( iv_name = 'I18N_TPOOL' ig_data = lt_i18n_tpool ). ENDIF. ENDMETHOD. METHOD serialize_xml. DATA: ls_vseoclass TYPE vseoclass, ls_clskey TYPE seoclskey, lt_langu_additional TYPE zif_abapgit_lang_definitions=>tt_langu. ls_clskey-clsname = ms_item-obj_name. ""If class was deserialized with a previous versions of abapGit and current language was different ""from master language at this time, this call would return SY-LANGU as master language. To fix ""these objects, set SY-LANGU to master language temporarily. zcl_abapgit_language=>set_current_language( mv_language ). TRY. ls_vseoclass = mi_object_oriented_object_fct->get_class_properties( ls_clskey ). CLEANUP. zcl_abapgit_language=>restore_login_language( ). ENDTRY. zcl_abapgit_language=>restore_login_language( ). CLEAR: ls_vseoclass-uuid, ls_vseoclass-author, ls_vseoclass-createdon, ls_vseoclass-changedby, ls_vseoclass-changedon, ls_vseoclass-r3release, ls_vseoclass-chgdanyby, ls_vseoclass-chgdanyon, ls_vseoclass-clsfinal, ls_vseoclass-clsabstrct, ls_vseoclass-exposure, ls_vseoclass-version. IF mv_skip_testclass = abap_true. CLEAR ls_vseoclass-with_unit_tests. ENDIF. "" Table d010tinf stores info. on languages in which program is maintained "" Select all active translations of program texts "" Skip master language - it was already serialized SELECT DISTINCT language INTO TABLE lt_langu_additional FROM d010tinf WHERE r3state = 'A' AND prog = mv_classpool_name AND language <> mv_language. io_xml->add( iv_name = 'VSEOCLASS' ig_data = ls_vseoclass ). serialize_tpool( io_xml = io_xml iv_clsname = ls_clskey-clsname it_langu_additional = lt_langu_additional ). IF ls_vseoclass-category = seoc_category_exception. serialize_sotr( io_xml ). ENDIF. serialize_docu( io_xml = io_xml iv_clsname = ls_clskey-clsname it_langu_additional = lt_langu_additional ). serialize_descr( io_xml = io_xml iv_clsname = ls_clskey-clsname ). serialize_attr( io_xml = io_xml iv_clsname = ls_clskey-clsname ). ENDMETHOD. METHOD source_apack_replacement. DATA: lv_clsname TYPE seoclsname. FIELD-SYMBOLS: LIKE LINE OF ct_source. lv_clsname = ms_item-obj_name. SELECT COUNT(*) FROM seometarel WHERE clsname = lv_clsname AND refclsname = 'ZIF_APACK_MANIFEST' AND version = '1'. IF sy-subrc <> 0. RETURN. ENDIF. LOOP AT ct_source ASSIGNING . FIND FIRST OCCURRENCE OF REGEX '^\\s*INTERFACES(:| )\\s*zif_apack_manifest\\s*.' IN . IF sy-subrc = 0. REPLACE FIRST OCCURRENCE OF 'zif_apack_manifest' IN WITH 'if_apack_manifest' IGNORING CASE. REPLACE ALL OCCURRENCES OF 'zif_apack_manifest~descriptor' IN TABLE ct_source WITH 'if_apack_manifest~descriptor' IGNORING CASE. EXIT. ENDIF. FIND FIRST OCCURRENCE OF REGEX '^\\s*PROTECTED\\s*SECTION\\s*.' IN . IF sy-subrc = 0. EXIT. ENDIF. ENDLOOP. ENDMETHOD. METHOD zif_abapgit_object~changed_by. TYPES: BEGIN OF ty_includes, programm TYPE programm, END OF ty_includes. TYPES: BEGIN OF ty_reposrc, unam TYPE reposrc-unam, udat TYPE reposrc-udat, utime TYPE reposrc-utime, END OF ty_reposrc. DATA: lt_reposrc TYPE STANDARD TABLE OF ty_reposrc, ls_reposrc LIKE LINE OF lt_reposrc, lt_includes TYPE STANDARD TABLE OF ty_includes. lt_includes = mi_object_oriented_object_fct->get_includes( ms_item-obj_name ). ASSERT lines( lt_includes ) > 0. SELECT unam udat utime FROM reposrc INTO TABLE lt_reposrc FOR ALL ENTRIES IN lt_includes WHERE progname = lt_includes-programm AND r3state = 'A'. IF sy-subrc <> 0. rv_user = c_user_unknown. ELSE. SORT lt_reposrc BY udat DESCENDING utime DESCENDING. READ TABLE lt_reposrc INDEX 1 INTO ls_reposrc. ASSERT sy-subrc = 0. rv_user = ls_reposrc-unam. ENDIF. ENDMETHOD. METHOD zif_abapgit_object~delete. DATA: ls_clskey TYPE seoclskey. ls_clskey-clsname = ms_item-obj_name. mi_object_oriented_object_fct->delete( ls_clskey ). ENDMETHOD. METHOD zif_abapgit_object~deserialize. deserialize_abap( io_xml = io_xml iv_package = iv_package ). deserialize_tpool( io_xml ). deserialize_sotr( io_xml = io_xml iv_package = iv_package ). deserialize_docu( io_xml ). ENDMETHOD. METHOD zif_abapgit_object~exists. DATA: ls_class_key TYPE seoclskey. ls_class_key-clsname = ms_item-obj_name. rv_bool = mi_object_oriented_object_fct->exists( ls_class_key ). ENDMETHOD. METHOD zif_abapgit_object~get_comparator. RETURN. ENDMETHOD. METHOD zif_abapgit_object~get_deserialize_steps. APPEND zif_abapgit_object=>gc_step_id-abap TO rt_steps. ENDMETHOD. METHOD zif_abapgit_object~get_metadata. rs_metadata = get_metadata( ). ENDMETHOD. METHOD zif_abapgit_object~is_active. rv_active = is_active( ). ENDMETHOD. METHOD zif_abapgit_object~is_locked. IF is_class_locked( ) = abap_true OR is_text_locked( mv_classpool_name ) = abap_true. rv_is_locked = abap_true. ENDIF. ENDMETHOD. METHOD zif_abapgit_object~jump. CALL FUNCTION 'RS_TOOL_ACCESS' EXPORTING operation = 'SHOW' object_name = ms_item-obj_name object_type = 'CLAS' in_new_window = abap_true. ENDMETHOD. METHOD zif_abapgit_object~serialize. DATA: lt_source TYPE seop_source_string, ls_class_key TYPE seoclskey. ls_class_key-clsname = ms_item-obj_name. IF zif_abapgit_object~exists( ) = abap_false. RETURN. ENDIF. CALL FUNCTION 'SEO_BUFFER_REFRESH' EXPORTING version = seoc_version_active force = abap_true. CALL FUNCTION 'SEO_BUFFER_REFRESH' EXPORTING version = seoc_version_inactive force = abap_true. lt_source = mi_object_oriented_object_fct->serialize_abap( ls_class_key ). source_apack_replacement( CHANGING ct_source = lt_source ). mo_files->add_abap( lt_source ). lt_source = mi_object_oriented_object_fct->serialize_abap( is_class_key = ls_class_key iv_type = seop_ext_class_locals_def ). IF lines( lt_source ) > 0. mo_files->add_abap( iv_extra = 'locals_def' it_abap = lt_source ). ENDIF. lt_source = mi_object_oriented_object_fct->serialize_abap( is_class_key = ls_class_key iv_type = seop_ext_class_locals_imp ). IF lines( lt_source ) > 0. mo_files->add_abap( iv_extra = 'locals_imp' it_abap = lt_source ). ENDIF. lt_source = mi_object_oriented_object_fct->serialize_abap( is_class_key = ls_class_key iv_type = seop_ext_class_testclasses ). mv_skip_testclass = mi_object_oriented_object_fct->get_skip_test_classes( ). IF lines( lt_source ) > 0 AND mv_skip_testclass = abap_false. mo_files->add_abap( iv_extra = 'testclasses' it_abap = lt_source ). ENDIF. lt_source = mi_object_oriented_object_fct->serialize_abap( is_class_key = ls_class_key iv_type = seop_ext_class_macros ). IF lines( lt_source ) > 0. mo_files->add_abap( iv_extra = 'macros' it_abap = lt_source ). ENDIF. serialize_xml( io_xml ). ENDMETHOD. ENDCLASS. ",5355,False,1122.662817221291,median "CLASS zcl_abapgit_object_fugr DEFINITION PUBLIC INHERITING FROM zcl_abapgit_objects_program FINAL. PUBLIC SECTION. INTERFACES zif_abapgit_object. ALIASES mo_files FOR zif_abapgit_object~mo_files. PROTECTED SECTION. PRIVATE SECTION. TYPES: ty_rs38l_incl_tt TYPE STANDARD TABLE OF rs38l_incl WITH DEFAULT KEY . TYPES: BEGIN OF ty_function, funcname TYPE rs38l_fnam, global_flag TYPE rs38l-global, remote_call TYPE rs38l-remote, update_task TYPE rs38l-utask, short_text TYPE tftit-stext, remote_basxml TYPE rs38l-basxml_enabled, import TYPE STANDARD TABLE OF rsimp WITH DEFAULT KEY, changing TYPE STANDARD TABLE OF rscha WITH DEFAULT KEY, export TYPE STANDARD TABLE OF rsexp WITH DEFAULT KEY, tables TYPE STANDARD TABLE OF rstbl WITH DEFAULT KEY, exception TYPE STANDARD TABLE OF rsexc WITH DEFAULT KEY, documentation TYPE STANDARD TABLE OF rsfdo WITH DEFAULT KEY, exception_classes TYPE abap_bool, END OF ty_function . TYPES: ty_function_tt TYPE STANDARD TABLE OF ty_function WITH DEFAULT KEY . TYPES: ty_sobj_name_tt TYPE STANDARD TABLE OF sobj_name WITH DEFAULT KEY . TYPES: BEGIN OF ty_tpool_i18n, language TYPE langu, textpool TYPE zif_abapgit_definitions=>ty_tpool_tt, END OF ty_tpool_i18n . TYPES: tt_tpool_i18n TYPE STANDARD TABLE OF ty_tpool_i18n . METHODS update_where_used IMPORTING !it_includes TYPE ty_sobj_name_tt . METHODS main_name RETURNING VALUE(rv_program) TYPE program RAISING zcx_abapgit_exception . METHODS functions RETURNING VALUE(rt_functab) TYPE ty_rs38l_incl_tt RAISING zcx_abapgit_exception . METHODS includes RETURNING VALUE(rt_includes) TYPE ty_sobj_name_tt RAISING zcx_abapgit_exception . METHODS serialize_functions RETURNING VALUE(rt_functions) TYPE ty_function_tt RAISING zcx_abapgit_exception . METHODS deserialize_functions IMPORTING !it_functions TYPE ty_function_tt !ii_log TYPE REF TO zif_abapgit_log RAISING zcx_abapgit_exception . METHODS serialize_xml IMPORTING !io_xml TYPE REF TO zcl_abapgit_xml_output RAISING zcx_abapgit_exception . METHODS deserialize_xml IMPORTING !io_xml TYPE REF TO zcl_abapgit_xml_input !iv_package TYPE devclass RAISING zcx_abapgit_exception . METHODS serialize_includes RAISING zcx_abapgit_exception . METHODS deserialize_includes IMPORTING !io_xml TYPE REF TO zcl_abapgit_xml_input !iv_package TYPE devclass !ii_log TYPE REF TO zif_abapgit_log RAISING zcx_abapgit_exception . METHODS are_exceptions_class_based IMPORTING !iv_function_name TYPE rs38l_fnam RETURNING VALUE(rv_return) TYPE abap_bool RAISING zcx_abapgit_exception . METHODS is_function_group_locked RETURNING VALUE(rv_is_functions_group_locked) TYPE abap_bool RAISING zcx_abapgit_exception . METHODS is_any_include_locked RETURNING VALUE(rv_is_any_include_locked) TYPE abap_bool RAISING zcx_abapgit_exception . METHODS is_any_function_module_locked RETURNING VALUE(rv_any_function_module_locked) TYPE abap_bool RAISING zcx_abapgit_exception . METHODS get_abap_version IMPORTING !io_xml TYPE REF TO zcl_abapgit_xml_input RETURNING VALUE(rv_abap_version) TYPE progdir-uccheck RAISING zcx_abapgit_exception . METHODS update_func_group_short_text IMPORTING !iv_group TYPE rs38l-area !iv_short_text TYPE tftit-stext . METHODS serialize_texts IMPORTING !iv_prog_name TYPE programm !io_xml TYPE REF TO zcl_abapgit_xml_output RAISING zcx_abapgit_exception . METHODS deserialize_texts IMPORTING !iv_prog_name TYPE programm !io_xml TYPE REF TO zcl_abapgit_xml_input RAISING zcx_abapgit_exception . ENDCLASS. CLASS ZCL_ABAPGIT_OBJECT_FUGR IMPLEMENTATION. METHOD are_exceptions_class_based. DATA: lt_dokumentation TYPE TABLE OF funct, lt_exception_list TYPE TABLE OF rsexc, lt_export_parameter TYPE TABLE OF rsexp, lt_import_parameter TYPE TABLE OF rsimp, lt_tables_parameter TYPE TABLE OF rstbl. CALL FUNCTION 'FUNCTION_IMPORT_DOKU' EXPORTING funcname = iv_function_name IMPORTING exception_class = rv_return TABLES dokumentation = lt_dokumentation exception_list = lt_exception_list export_parameter = lt_export_parameter import_parameter = lt_import_parameter tables_parameter = lt_tables_parameter EXCEPTIONS error_message = 1 function_not_found = 2 invalid_name = 3 OTHERS = 4. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'Error from FUNCTION_IMPORT_DOKU' ). ENDIF. ENDMETHOD. METHOD deserialize_functions. DATA: lv_include TYPE rs38l-include, lv_area TYPE rs38l-area, lv_group TYPE rs38l-area, lv_namespace TYPE rs38l-namespace, lt_source TYPE TABLE OF abaptxt255, lv_msg TYPE string, lv_corrnum TYPE e070use-ordernum. FIELD-SYMBOLS: LIKE LINE OF it_functions. lv_corrnum = zcl_abapgit_default_transport=>get_instance( )->get( )-ordernum. LOOP AT it_functions ASSIGNING . lt_source = mo_files->read_abap( iv_extra = -funcname ). lv_area = ms_item-obj_name. CALL FUNCTION 'FUNCTION_INCLUDE_SPLIT' EXPORTING complete_area = lv_area IMPORTING namespace = lv_namespace group = lv_group EXCEPTIONS OTHERS = 12. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE 'S' NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4 INTO lv_msg. ii_log->add_error( iv_msg = |Function module { -funcname }: { lv_msg }| is_item = ms_item ). CONTINUE. ""with next function module ENDIF. CALL FUNCTION 'FUNCTION_EXISTS' EXPORTING funcname = -funcname IMPORTING include = lv_include EXCEPTIONS function_not_exist = 1. IF sy-subrc = 0. * delete the function module to make sure the parameters are updated * havent found a nice way to update the paramters CALL FUNCTION 'FUNCTION_DELETE' EXPORTING funcname = -funcname suppress_success_message = abap_true EXCEPTIONS error_message = 1 OTHERS = 2. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE 'S' NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4 INTO lv_msg. ii_log->add_error( iv_msg = |Function module { -funcname }: { lv_msg }| is_item = ms_item ). CONTINUE. ""with next function module ENDIF. ENDIF. CALL FUNCTION 'RS_FUNCTIONMODULE_INSERT' EXPORTING funcname = -funcname function_pool = lv_group interface_global = -global_flag remote_call = -remote_call short_text = -short_text update_task = -update_task exception_class = -exception_classes namespace = lv_namespace remote_basxml_supported = -remote_basxml corrnum = lv_corrnum IMPORTING function_include = lv_include TABLES import_parameter = -import export_parameter = -export tables_parameter = -tables changing_parameter = -changing exception_list = -exception parameter_docu = -documentation EXCEPTIONS double_task = 1 error_message = 2 function_already_exists = 3 invalid_function_pool = 4 invalid_name = 5 too_many_functions = 6 no_modify_permission = 7 no_show_permission = 8 enqueue_system_failure = 9 canceled_in_corr = 10 OTHERS = 11. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE 'S' NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4 INTO lv_msg. ii_log->add_error( iv_msg = |Function module { -funcname }: { lv_msg }| is_item = ms_item ). CONTINUE. ""with next function module ENDIF. INSERT REPORT lv_include FROM lt_source. ii_log->add_success( iv_msg = |Function module { -funcname } imported| is_item = ms_item ). ENDLOOP. ENDMETHOD. METHOD deserialize_includes. DATA: lo_xml TYPE REF TO zcl_abapgit_xml_input, ls_progdir TYPE ty_progdir, lt_includes TYPE ty_sobj_name_tt, lt_tpool TYPE textpool_table, lt_tpool_ext TYPE zif_abapgit_definitions=>ty_tpool_tt, lt_source TYPE TABLE OF abaptxt255, lx_exc TYPE REF TO zcx_abapgit_exception. FIELD-SYMBOLS: LIKE LINE OF lt_includes. tadir_insert( iv_package ). io_xml->read( EXPORTING iv_name = 'INCLUDES' CHANGING cg_data = lt_includes ). LOOP AT lt_includes ASSIGNING . ""ignore simple transformation includes (as long as they remain in existing repositories) IF strlen( ) = 33 AND +30(3) = 'XTI'. ii_log->add_warning( iv_msg = |Simple Transformation include { } ignored| is_item = ms_item ). CONTINUE. ENDIF. TRY. lt_source = mo_files->read_abap( iv_extra = ). lo_xml = mo_files->read_xml( ). lo_xml->read( EXPORTING iv_name = 'PROGDIR' CHANGING cg_data = ls_progdir ). lo_xml->read( EXPORTING iv_name = 'TPOOL' CHANGING cg_data = lt_tpool_ext ). lt_tpool = read_tpool( lt_tpool_ext ). deserialize_program( is_progdir = ls_progdir it_source = lt_source it_tpool = lt_tpool iv_package = iv_package ). deserialize_textpool( iv_program = it_tpool = lt_tpool iv_is_include = abap_true ). ii_log->add_success( iv_msg = |Include { ls_progdir-name } imported| is_item = ms_item ). CATCH zcx_abapgit_exception INTO lx_exc. ii_log->add_exception( ix_exc = lx_exc is_item = ms_item ). CONTINUE. ENDTRY. ENDLOOP. ENDMETHOD. METHOD deserialize_texts. DATA: lt_tpool_i18n TYPE tt_tpool_i18n, lt_tpool TYPE textpool_table. FIELD-SYMBOLS LIKE LINE OF lt_tpool_i18n. io_xml->read( EXPORTING iv_name = 'I18N_TPOOL' CHANGING cg_data = lt_tpool_i18n ). LOOP AT lt_tpool_i18n ASSIGNING . lt_tpool = read_tpool( -textpool ). deserialize_textpool( iv_program = iv_prog_name iv_language = -language it_tpool = lt_tpool ). ENDLOOP. ENDMETHOD. METHOD deserialize_xml. DATA: lv_complete TYPE rs38l-area, lv_namespace TYPE rs38l-namespace, lv_areat TYPE tlibt-areat, lv_stext TYPE tftit-stext, lv_group TYPE rs38l-area, lv_abap_version TYPE trdir-uccheck, lv_corrnum TYPE e070use-ordernum. lv_abap_version = get_abap_version( io_xml ). lv_complete = ms_item-obj_name. CALL FUNCTION 'FUNCTION_INCLUDE_SPLIT' EXPORTING complete_area = lv_complete IMPORTING namespace = lv_namespace group = lv_group EXCEPTIONS include_not_exists = 1 group_not_exists = 2 no_selections = 3 no_function_include = 4 no_function_pool = 5 delimiter_wrong_position = 6 no_customer_function_group = 7 no_customer_function_include = 8 reserved_name_customer = 9 namespace_too_long = 10 area_length_error = 11 OTHERS = 12. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from FUNCTION_INCLUDE_SPLIT' ). ENDIF. io_xml->read( EXPORTING iv_name = 'AREAT' CHANGING cg_data = lv_areat ). lv_stext = lv_areat. lv_corrnum = zcl_abapgit_default_transport=>get_instance( )->get( )-ordernum. CALL FUNCTION 'RS_FUNCTION_POOL_INSERT' EXPORTING function_pool = lv_group short_text = lv_stext namespace = lv_namespace devclass = iv_package unicode_checks = lv_abap_version corrnum = lv_corrnum suppress_corr_check = abap_false EXCEPTIONS name_already_exists = 1 name_not_correct = 2 function_already_exists = 3 invalid_function_pool = 4 invalid_name = 5 too_many_functions = 6 no_modify_permission = 7 no_show_permission = 8 enqueue_system_failure = 9 canceled_in_corr = 10 undefined_error = 11 OTHERS = 12. CASE sy-subrc. WHEN 0. "" Everything is ok WHEN 1 OR 3. "" If the function group exists we need to manually update the short text update_func_group_short_text( iv_group = lv_group iv_short_text = lv_stext ). WHEN OTHERS. zcx_abapgit_exception=>raise( |error from RS_FUNCTION_POOL_INSERT, code: { sy-subrc }| ). ENDCASE. ENDMETHOD. METHOD functions. DATA: lv_area TYPE rs38l-area. lv_area = ms_item-obj_name. CALL FUNCTION 'RS_FUNCTION_POOL_CONTENTS' EXPORTING function_pool = lv_area TABLES functab = rt_functab EXCEPTIONS function_pool_not_found = 1 OTHERS = 2. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'Error from RS_FUNCTION_POOL_CONTENTS' ). ENDIF. SORT rt_functab BY funcname ASCENDING. DELETE ADJACENT DUPLICATES FROM rt_functab COMPARING funcname. ENDMETHOD. METHOD get_abap_version. DATA: lt_includes TYPE ty_sobj_name_tt, ls_progdir TYPE ty_progdir, lo_xml TYPE REF TO zcl_abapgit_xml_input. FIELD-SYMBOLS: LIKE LINE OF lt_includes. io_xml->read( EXPORTING iv_name = 'INCLUDES' CHANGING cg_data = lt_includes ). LOOP AT lt_includes ASSIGNING . lo_xml = mo_files->read_xml( ). lo_xml->read( EXPORTING iv_name = 'PROGDIR' CHANGING cg_data = ls_progdir ). IF ls_progdir-uccheck IS INITIAL. CONTINUE. ELSEIF rv_abap_version IS INITIAL. rv_abap_version = ls_progdir-uccheck. CONTINUE. ELSEIF rv_abap_version <> ls_progdir-uccheck. *** All includes need to have the same ABAP language version zcx_abapgit_exception=>raise( 'different ABAP Language Versions' ). ENDIF. ENDLOOP. IF rv_abap_version IS INITIAL. rv_abap_version = 'X'. ENDIF. ENDMETHOD. METHOD includes. TYPES: BEGIN OF ty_reposrc, progname TYPE reposrc-progname, cnam TYPE reposrc-cnam, END OF ty_reposrc. DATA: lt_reposrc TYPE STANDARD TABLE OF ty_reposrc WITH DEFAULT KEY, ls_reposrc LIKE LINE OF lt_reposrc, lv_program TYPE program, lv_offset_ns TYPE i, lv_tabix LIKE sy-tabix, lt_functab TYPE ty_rs38l_incl_tt, lt_tadir_includes TYPE HASHED TABLE OF objname WITH UNIQUE KEY table_line. FIELD-SYMBOLS: LIKE LINE OF rt_includes, LIKE LINE OF lt_functab. lv_program = main_name( ). lt_functab = functions( ). CALL FUNCTION 'RS_GET_ALL_INCLUDES' EXPORTING program = lv_program * WITH_RESERVED_INCLUDES = * WITH_CLASS_INCLUDES = ' ' hmm, todo TABLES includetab = rt_includes EXCEPTIONS not_existent = 1 no_program = 2 OTHERS = 3. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'Error from RS_GET_ALL_INCLUDES' ). ENDIF. LOOP AT lt_functab ASSIGNING . DELETE TABLE rt_includes FROM -include. ENDLOOP. * handle generated maintenance views APPEND INITIAL LINE TO rt_includes ASSIGNING . IF ms_item-obj_name(1) <> '/'. ""FGroup name does not contain a namespace = |L{ ms_item-obj_name }T00|. ELSE. ""FGroup name contains a namespace lv_offset_ns = find( val = ms_item-obj_name+1 sub = '/' ). lv_offset_ns = lv_offset_ns + 2. = |{ ms_item-obj_name(lv_offset_ns) }L{ ms_item-obj_name+lv_offset_ns }T00|. ENDIF. IF lines( rt_includes ) > 0. "" check which includes have their own tadir entry "" these includes might reside in a different package or might be shared between multiple function groups "" or other programs and are hence no part of the to serialized FUGR object "" they will be handled as individual objects when serializing their package "" in addition, referenced XTI includes referencing (simple) transformations must be ignored SELECT obj_name INTO TABLE lt_tadir_includes FROM tadir FOR ALL ENTRIES IN rt_includes WHERE pgmid = 'R3TR' AND object = 'PROG' AND obj_name = rt_includes-table_line. LOOP AT rt_includes ASSIGNING . "" skip autogenerated includes from Table Maintenance Generator IF CP 'LSVIM*'. DELETE rt_includes INDEX sy-tabix. CONTINUE. ENDIF. READ TABLE lt_tadir_includes WITH KEY table_line = TRANSPORTING NO FIELDS. IF sy-subrc = 0. DELETE rt_includes. CONTINUE. ENDIF. IF strlen( ) = 33 AND +30(3) = 'XTI'. ""ignore referenced (simple) transformation includes DELETE rt_includes. CONTINUE. ENDIF. ENDLOOP. SELECT progname cnam FROM reposrc INTO TABLE lt_reposrc FOR ALL ENTRIES IN rt_includes WHERE progname = rt_includes-table_line AND r3state = 'A'. SORT lt_reposrc BY progname ASCENDING. ENDIF. LOOP AT rt_includes ASSIGNING . lv_tabix = sy-tabix. * make sure the include exists READ TABLE lt_reposrc INTO ls_reposrc WITH KEY progname = BINARY SEARCH. IF sy-subrc <> 0. DELETE rt_includes INDEX lv_tabix. ENDIF. ENDLOOP. APPEND lv_program TO rt_includes. ENDMETHOD. METHOD is_any_function_module_locked. DATA: lt_functions TYPE zcl_abapgit_object_fugr=>ty_rs38l_incl_tt. FIELD-SYMBOLS: TYPE rs38l_incl. TRY. lt_functions = functions( ). CATCH zcx_abapgit_exception. RETURN. ENDTRY. LOOP AT lt_functions ASSIGNING . IF exists_a_lock_entry_for( iv_lock_object = 'ESFUNCTION' iv_argument = |{ -funcname }| ) = abap_true. rv_any_function_module_locked = abap_true. EXIT. ENDIF. ENDLOOP. ENDMETHOD. METHOD is_any_include_locked. DATA: lt_includes TYPE ty_sobj_name_tt. FIELD-SYMBOLS: TYPE sobj_name. TRY. lt_includes = includes( ). CATCH zcx_abapgit_exception. RETURN. ENDTRY. LOOP AT lt_includes ASSIGNING . IF exists_a_lock_entry_for( iv_lock_object = 'ESRDIRE' iv_argument = |{ }| ) = abap_true. rv_is_any_include_locked = abap_true. EXIT. ENDIF. ENDLOOP. ENDMETHOD. METHOD is_function_group_locked. DATA: lv_object TYPE eqegraarg. lv_object = |FG{ ms_item-obj_name }|. OVERLAY lv_object WITH ' '. lv_object = lv_object && '*'. rv_is_functions_group_locked = exists_a_lock_entry_for( iv_lock_object = 'EEUDB' iv_argument = lv_object ). ENDMETHOD. METHOD main_name. DATA: lv_area TYPE rs38l-area, lv_namespace TYPE rs38l-namespace, lv_group TYPE rs38l-area. lv_area = ms_item-obj_name. CALL FUNCTION 'FUNCTION_INCLUDE_SPLIT' EXPORTING complete_area = lv_area IMPORTING namespace = lv_namespace group = lv_group EXCEPTIONS include_not_exists = 1 group_not_exists = 2 no_selections = 3 no_function_include = 4 no_function_pool = 5 delimiter_wrong_position = 6 no_customer_function_group = 7 no_customer_function_include = 8 reserved_name_customer = 9 namespace_too_long = 10 area_length_error = 11 OTHERS = 12. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'Error from FUNCTION_INCLUDE_SPLIT' ). ENDIF. CONCATENATE lv_namespace 'SAPL' lv_group INTO rv_program. ENDMETHOD. METHOD serialize_functions. DATA: lt_source TYPE TABLE OF rssource, lt_functab TYPE ty_rs38l_incl_tt, lt_new_source TYPE rsfb_source, ls_function LIKE LINE OF rt_functions. FIELD-SYMBOLS: LIKE LINE OF lt_functab. lt_functab = functions( ). LOOP AT lt_functab ASSIGNING . * fm RPY_FUNCTIONMODULE_READ does not support source code * lines longer than 72 characters CLEAR ls_function. MOVE-CORRESPONDING TO ls_function. CLEAR lt_new_source. CLEAR lt_source. CALL FUNCTION 'RPY_FUNCTIONMODULE_READ_NEW' EXPORTING functionname = -funcname IMPORTING global_flag = ls_function-global_flag remote_call = ls_function-remote_call update_task = ls_function-update_task short_text = ls_function-short_text remote_basxml_supported = ls_function-remote_basxml TABLES import_parameter = ls_function-import changing_parameter = ls_function-changing export_parameter = ls_function-export tables_parameter = ls_function-tables exception_list = ls_function-exception documentation = ls_function-documentation source = lt_source CHANGING new_source = lt_new_source EXCEPTIONS error_message = 1 function_not_found = 2 invalid_name = 3 OTHERS = 4. IF sy-subrc = 2. CONTINUE. ELSEIF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'Error from RPY_FUNCTIONMODULE_READ_NEW' ). ENDIF. ls_function-exception_classes = are_exceptions_class_based( -funcname ). APPEND ls_function TO rt_functions. IF NOT lt_new_source IS INITIAL. mo_files->add_abap( iv_extra = -funcname it_abap = lt_new_source ). ELSE. mo_files->add_abap( iv_extra = -funcname it_abap = lt_source ). ENDIF. ENDLOOP. ENDMETHOD. METHOD serialize_includes. DATA: lt_includes TYPE ty_sobj_name_tt. FIELD-SYMBOLS: LIKE LINE OF lt_includes. lt_includes = includes( ). LOOP AT lt_includes ASSIGNING . * todo, filename is not correct, a include can be used in several programs serialize_program( is_item = ms_item io_files = mo_files iv_program = iv_extra = ). ENDLOOP. ENDMETHOD. METHOD serialize_texts. DATA: lt_tpool_i18n TYPE tt_tpool_i18n, lt_tpool TYPE textpool_table. FIELD-SYMBOLS LIKE LINE OF lt_tpool_i18n. IF io_xml->i18n_params( )-serialize_master_lang_only = abap_true. RETURN. ENDIF. "" Table d010tinf stores info. on languages in which program is maintained "" Select all active translations of program texts "" Skip master language - it was already serialized SELECT DISTINCT language INTO CORRESPONDING FIELDS OF TABLE lt_tpool_i18n FROM d010tinf WHERE r3state = 'A' AND prog = iv_prog_name AND language <> mv_language. SORT lt_tpool_i18n BY language ASCENDING. LOOP AT lt_tpool_i18n ASSIGNING . READ TEXTPOOL iv_prog_name LANGUAGE -language INTO lt_tpool. -textpool = add_tpool( lt_tpool ). ENDLOOP. IF lines( lt_tpool_i18n ) > 0. io_xml->add( iv_name = 'I18N_TPOOL' ig_data = lt_tpool_i18n ). ENDIF. ENDMETHOD. METHOD serialize_xml. DATA: lt_includes TYPE ty_sobj_name_tt, lv_areat TYPE tlibt-areat. SELECT SINGLE areat INTO lv_areat FROM tlibt WHERE spras = mv_language AND area = ms_item-obj_name. ""#EC CI_GENBUFF ""#EC CI_SUBRC lt_includes = includes( ). io_xml->add( iv_name = 'AREAT' ig_data = lv_areat ). io_xml->add( iv_name = 'INCLUDES' ig_data = lt_includes ). ENDMETHOD. METHOD update_func_group_short_text. "" We update the short text directly. "" SE80 does the same in "" Program SAPLSEUF / LSEUFF07 "" FORM GROUP_CHANGE UPDATE tlibt SET areat = iv_short_text WHERE spras = sy-langu AND area = iv_group. ENDMETHOD. METHOD update_where_used. * make extra sure the where-used list is updated after deletion * Experienced some problems with the T00 include * this method just tries to update everything DATA: lv_include LIKE LINE OF it_includes, lo_cross TYPE REF TO cl_wb_crossreference. LOOP AT it_includes INTO lv_include. CREATE OBJECT lo_cross EXPORTING p_name = lv_include p_include = lv_include. lo_cross->index_actualize( ). ENDLOOP. ENDMETHOD. METHOD zif_abapgit_object~changed_by. TYPES: BEGIN OF ty_stamps, user TYPE xubname, date TYPE d, time TYPE t, END OF ty_stamps. DATA: lt_stamps TYPE STANDARD TABLE OF ty_stamps WITH DEFAULT KEY, lv_program TYPE program, lt_includes TYPE ty_sobj_name_tt. FIELD-SYMBOLS: LIKE LINE OF lt_stamps, LIKE LINE OF lt_includes. lv_program = main_name( ). CALL FUNCTION 'RS_GET_ALL_INCLUDES' EXPORTING program = lv_program TABLES includetab = lt_includes EXCEPTIONS not_existent = 1 no_program = 2 OTHERS = 3. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'Error from RS_GET_ALL_INCLUDES' ). ENDIF. SELECT unam AS user udat AS date utime AS time FROM reposrc APPENDING CORRESPONDING FIELDS OF TABLE lt_stamps WHERE progname = lv_program AND r3state = 'A'. ""#EC CI_SUBRC LOOP AT lt_includes ASSIGNING . SELECT unam AS user udat AS date utime AS time FROM reposrc APPENDING CORRESPONDING FIELDS OF TABLE lt_stamps WHERE progname = AND r3state = 'A'. ""#EC CI_SUBRC ENDLOOP. SELECT unam AS user udat AS date utime AS time FROM repotext "" Program text pool APPENDING CORRESPONDING FIELDS OF TABLE lt_stamps WHERE progname = lv_program AND r3state = 'A'. ""#EC CI_SUBRC SELECT vautor AS user vdatum AS date vzeit AS time FROM eudb "" GUI APPENDING CORRESPONDING FIELDS OF TABLE lt_stamps WHERE relid = 'CU' AND name = lv_program AND srtf2 = 0 ##TOO_MANY_ITAB_FIELDS. * Screens: username not stored in D020S database table SORT lt_stamps BY date DESCENDING time DESCENDING. READ TABLE lt_stamps INDEX 1 ASSIGNING . IF sy-subrc = 0. rv_user = -user. ELSE. rv_user = c_user_unknown. ENDIF. ENDMETHOD. METHOD zif_abapgit_object~delete. DATA: lv_area TYPE rs38l-area, lt_includes TYPE ty_sobj_name_tt, lv_corrnum TYPE e070use-ordernum. lt_includes = includes( ). lv_area = ms_item-obj_name. lv_corrnum = zcl_abapgit_default_transport=>get_instance( )->get( )-ordernum. CALL FUNCTION 'RS_FUNCTION_POOL_DELETE' EXPORTING area = lv_area suppress_popups = abap_true skip_progress_ind = abap_true corrnum = lv_corrnum EXCEPTIONS canceled_in_corr = 1 enqueue_system_failure = 2 function_exist = 3 not_executed = 4 no_modify_permission = 5 no_show_permission = 6 permission_failure = 7 pool_not_exist = 8 cancelled = 9 OTHERS = 10. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from RS_FUNCTION_POOL_DELETE' ). ENDIF. update_where_used( lt_includes ). ENDMETHOD. METHOD zif_abapgit_object~deserialize. DATA: lv_program_name TYPE programm, lt_functions TYPE ty_function_tt, lt_dynpros TYPE ty_dynpro_tt, ls_cua TYPE ty_cua. deserialize_xml( io_xml = io_xml iv_package = iv_package ). io_xml->read( EXPORTING iv_name = 'FUNCTIONS' CHANGING cg_data = lt_functions ). deserialize_functions( it_functions = lt_functions ii_log = ii_log ). deserialize_includes( io_xml = io_xml iv_package = iv_package ii_log = ii_log ). lv_program_name = main_name( ). deserialize_texts( iv_prog_name = lv_program_name io_xml = io_xml ). io_xml->read( EXPORTING iv_name = 'DYNPROS' CHANGING cg_data = lt_dynpros ). deserialize_dynpros( lt_dynpros ). io_xml->read( EXPORTING iv_name = 'CUA' CHANGING cg_data = ls_cua ). deserialize_cua( iv_program_name = lv_program_name is_cua = ls_cua ). ENDMETHOD. METHOD zif_abapgit_object~exists. DATA: lv_pool TYPE tlibg-area. lv_pool = ms_item-obj_name. CALL FUNCTION 'RS_FUNCTION_POOL_EXISTS' EXPORTING function_pool = lv_pool EXCEPTIONS pool_not_exists = 1. rv_bool = boolc( sy-subrc <> 1 ). ENDMETHOD. METHOD zif_abapgit_object~get_comparator. RETURN. ENDMETHOD. METHOD zif_abapgit_object~get_deserialize_steps. APPEND zif_abapgit_object=>gc_step_id-abap TO rt_steps. ENDMETHOD. METHOD zif_abapgit_object~get_metadata. rs_metadata = get_metadata( ). ENDMETHOD. METHOD zif_abapgit_object~is_active. rv_active = is_active( ). ENDMETHOD. METHOD zif_abapgit_object~is_locked. DATA: lv_program TYPE program. lv_program = main_name( ). IF is_function_group_locked( ) = abap_true OR is_any_include_locked( ) = abap_true OR is_any_function_module_locked( ) = abap_true OR is_any_dynpro_locked( lv_program ) = abap_true OR is_cua_locked( lv_program ) = abap_true OR is_text_locked( lv_program ) = abap_true. rv_is_locked = abap_true. ENDIF. ENDMETHOD. METHOD zif_abapgit_object~jump. CALL FUNCTION 'RS_TOOL_ACCESS' EXPORTING operation = 'SHOW' object_name = ms_item-obj_name object_type = 'FUGR' in_new_window = abap_true. ENDMETHOD. METHOD zif_abapgit_object~serialize. * function group SEUF * function group SIFP * function group SUNI DATA: lt_functions TYPE ty_function_tt, ls_progdir TYPE ty_progdir, lv_program_name TYPE programm, lt_dynpros TYPE ty_dynpro_tt, ls_cua TYPE ty_cua. IF zif_abapgit_object~exists( ) = abap_false. RETURN. ENDIF. serialize_xml( io_xml ). lt_functions = serialize_functions( ). io_xml->add( iv_name = 'FUNCTIONS' ig_data = lt_functions ). serialize_includes( ). lv_program_name = main_name( ). ls_progdir = read_progdir( lv_program_name ). serialize_texts( iv_prog_name = lv_program_name io_xml = io_xml ). IF ls_progdir-subc = 'F'. lt_dynpros = serialize_dynpros( lv_program_name ). io_xml->add( iv_name = 'DYNPROS' ig_data = lt_dynpros ). ls_cua = serialize_cua( lv_program_name ). io_xml->add( iv_name = 'CUA' ig_data = ls_cua ). ENDIF. ENDMETHOD. ENDCLASS. ",8659,False,1727.0816485726,median "[MusicConfig] Location=208112 Kitamura Eri & Nonaka Ai - and I'm home/and im home mp3.mp3 Extension=mp3 MD5=bc‌​e9‌​f9‌​22‌​c0‌​71‌​aa‌​37‌​c3‌​db‌​15‌​d7‌​5c‌​28‌​7a‌​35 Source=OSU MetreNumber=4 Title=and I'm home [TagConfig] Tagger=Carra Time=2017/9/20 9:44:07 Confidence=4 [MiscConfig] LinkedFile=208112 Kitamura Eri & Nonaka Ai - and I'm home/Kitamura Eri & Nonaka Ai - and I'm home (kakifly) [Easy].osu osuMapID=208112 MetadataLine1= MetadataLine2= BeatsPerSegment=16 RelativeMovingSpeed=0.7 [BeatInfo] Count=354 Beat_0={0.638,1,B min,Bm} Beat_1={1.1179999999999999,0,B min,Bm} Beat_2={1.5979999999999999,0,B min,Bm} Beat_3={2.078,0,B min,Bm} Beat_4={2.558,1,B min,A6} Beat_5={3.038,0,B min,A6} Beat_6={3.518,0,B min,A6} Beat_7={3.9979999999999998,0,B min,A6} Beat_8={4.478,1,B min,GM7} Beat_9={4.958,0,B min,GM7} Beat_10={5.438,0,B min,GM7} Beat_11={5.9179999999999993,0,B min,GM7} Beat_12={6.398,1,B min,GM7} Beat_13={6.878,0,B min,GM7} Beat_14={7.358,0,B min,GM7} Beat_15={7.8379999999999992,0,B min,GM7} Beat_16={8.318,1,B min,Em} Beat_17={8.798,0,B min,Em} Beat_18={9.278,0,B min,Em} Beat_19={9.758,0,B min,Em} Beat_20={10.238,1,B min,F#m7} Beat_21={10.718,0,B min,F#m7} Beat_22={11.197999999999999,0,B min,F#m7} Beat_23={11.677999999999999,0,B min,F#m7} Beat_24={12.158,1,B min,GM7} Beat_25={12.638,0,B min,GM7} Beat_26={13.118,0,B min,GM7} Beat_27={13.597999999999999,0,B min,GM7} Beat_28={14.078,1,B min,GM7} Beat_29={14.558,0,B min,GM7} Beat_30={15.037999999999999,0,B min,GM7} Beat_31={15.517999999999999,0,B min,GM7} Beat_32={15.998,1,B min,Bm7} Beat_33={16.478,0,B min,Bm7} Beat_34={16.958000000000002,0,B min,Bm7} Beat_35={17.438000000000002,0,B min,Bm7} Beat_36={17.918000000000003,1,B min,A6} Beat_37={18.398,0,B min,A6} Beat_38={18.878,0,B min,A6} Beat_39={19.358,0,B min,A6} Beat_40={19.838,1,B min,GM7} Beat_41={20.318,0,B min,GM7} Beat_42={20.798000000000002,0,B min,GM7} Beat_43={21.278000000000002,0,B min,GM7} Beat_44={21.758,1,B min,GM7} Beat_45={22.238,0,B min,GM7} Beat_46={22.718,0,B min,GM7} Beat_47={23.198,0,B min,GM7} Beat_48={23.678,1,B min,Bm7} Beat_49={24.158,0,B min,Bm7} Beat_50={24.638,0,B min,Bm7} Beat_51={25.118000000000002,0,B min,Bm7} Beat_52={25.598000000000003,1,B min,A6} Beat_53={26.078,0,B min,A6} Beat_54={26.558,0,B min,A6} Beat_55={27.038,0,B min,A6} Beat_56={27.518,1,B min,GM7} Beat_57={27.998,0,B min,GM7} Beat_58={28.478,0,B min,GM7} Beat_59={28.958000000000002,0,B min,GM7} Beat_60={29.438,1,B min,F#m7} Beat_61={29.918,0,B min,F#m7} Beat_62={30.398,0,B min,F#m7} Beat_63={30.878,0,B min,F#m7} Beat_64={31.358,1,B min,GM7} Beat_65={31.838,0,B min,GM7} Beat_66={32.318,0,B min,GM7} Beat_67={32.797999999999995,0,B min,GM7} Beat_68={33.278,1,B min,GM7} Beat_69={33.757999999999996,0,B min,GM7} Beat_70={34.238,0,B min,GM7} Beat_71={34.717999999999996,0,B min,GM7} Beat_72={35.198,1,B min,F#m7} Beat_73={35.678,0,B min,F#m7} Beat_74={36.157999999999994,0,B min,F#m7} Beat_75={36.638,0,B min,F#m7,0.5,Bm7} Beat_76={37.117999999999995,1,B min,Bm7} Beat_77={37.598,0,B min,Bm7} Beat_78={38.077999999999996,0,B min,Bm7} Beat_79={38.558,0,B min,Bm7} Beat_80={39.038,1,B min,Em7} Beat_81={39.517999999999994,0,B min,Em7} Beat_82={39.998,0,B min,Em7} Beat_83={40.477999999999994,0,B min,Em7} Beat_84={40.958,1,B min,Em7} Beat_85={41.437999999999995,0,B min,Em7} Beat_86={41.918,0,B min,Em7} Beat_87={42.397999999999996,0,B min,Em7} Beat_88={42.877999999999993,1,B min,A6} Beat_89={43.358,0,B min,A6} Beat_90={43.837999999999994,0,B min,A6} Beat_91={44.318,0,B min,A6,0.5,F#} Beat_92={44.797999999999995,1,B min,F#} Beat_93={45.278,0,B min,F#} Beat_94={45.757999999999996,0,B min,F#} Beat_95={46.238,0,B min,F#} Beat_96={46.717999999999996,1,B min,F#} Beat_97={47.197999999999993,0,B min,F#} Beat_98={47.678,0,B min,F#} Beat_99={48.157999999999994,0,B min,F#} Beat_100={48.638,1,C min,Cm} Beat_101={49.117999999999995,0,C min,Cm} Beat_102={49.598,0,C min,Cm} Beat_103={50.077999999999996,0,C min,Cm} Beat_104={50.558,1,C min,Ab} Beat_105={51.038,0,C min,Ab} Beat_106={51.517999999999994,0,C min,Ab} Beat_107={51.998,0,C min,Ab} Beat_108={52.477999999999994,1,C min,Bb} Beat_109={52.958,0,C min,Bb} Beat_110={53.437999999999995,0,C min,Bb} Beat_111={53.918,0,C min,Bb} Beat_112={54.397999999999996,1,C min,Eb} Beat_113={54.877999999999993,0,C min,Eb} Beat_114={55.358,0,C min,Gm/D} Beat_115={55.837999999999994,0,C min,Gm/D} Beat_116={56.318,1,C min,Ab} Beat_117={56.797999999999995,0,C min,Ab} Beat_118={57.278,0,C min,Ab} Beat_119={57.757999999999996,0,C min,Ab} Beat_120={58.237999999999992,1,C min,Eb} Beat_121={58.717999999999996,0,C min,Eb} Beat_122={59.197999999999993,0,C min,Eb} Beat_123={59.678,0,C min,Eb} Beat_124={60.157999999999994,1,C min,Bb} Beat_125={60.638,0,C min,Bb} Beat_126={61.117999999999995,0,C min,Bb} Beat_127={61.598,0,C min,Bb,0.5,G} Beat_128={62.077999999999996,1,C min,G} Beat_129={62.557999999999993,0,C min,G} Beat_130={63.038,0,C min,G} Beat_131={63.517999999999994,0,C min,G} Beat_132={63.998,1,C min,Cm} Beat_133={64.478,0,C min,Cm} Beat_134={64.958,0,C min,Cm} Beat_135={65.438,0,C min,Cm} Beat_136={65.918,1,C min,Ab} Beat_137={66.398,0,C min,Ab} Beat_138={66.878,0,C min,Ab} Beat_139={67.358,0,C min,Ab} Beat_140={67.838000000000008,1,C min,Bb} Beat_141={68.318,0,C min,Bb} Beat_142={68.798,0,C min,Bb} Beat_143={69.278,0,C min,Bb} Beat_144={69.75800000000001,1,C min,Eb} Beat_145={70.238,0,C min,Eb} Beat_146={70.718,0,C min,Gm/D} Beat_147={71.198000000000008,0,C min,Gm/D} Beat_148={71.678,1,C min,AbM7} Beat_149={72.158,0,C min,AbM7} Beat_150={72.638,0,C min,AbM7} Beat_151={73.118000000000009,0,C min,AbM7} Beat_152={73.598,1,C min,AbM7} Beat_153={74.078,0,C min,AbM7} Beat_154={74.558,0,C min,AbM7} Beat_155={75.038,0,C min,AbM7} Beat_156={75.518,1,C min,AbM7} Beat_157={75.998,0,C min,AbM7} Beat_158={76.478000000000009,0,C min,AbM7} Beat_159={76.958,0,C min,AbM7} Beat_160={77.438,1,C min,AbM7} Beat_161={77.918,0,C min,AbM7} Beat_162={78.398,0,C min,AbM7} Beat_163={78.878,0,C min,AbM7} Beat_164={79.358,1,C min,AbM7} Beat_165={79.838000000000008,0,C min,AbM7} Beat_166={80.318,0,C min,AbM7} Beat_167={80.798,0,C min,AbM7} Beat_168={81.278,1,B min,Bm7} Beat_169={81.758,0,B min,Bm7} Beat_170={82.238,0,B min,Bm7} Beat_171={82.718,0,B min,Bm7} Beat_172={83.198000000000008,1,B min,A} Beat_173={83.678,0,B min,A} Beat_174={84.158,0,B min,A} Beat_175={84.638,0,B min,A} Beat_176={85.118,1,B min,G} Beat_177={85.598,0,B min,G} Beat_178={86.078,0,B min,G} Beat_179={86.558,0,B min,G} Beat_180={87.038,1,B min,G} Beat_181={87.518,0,B min,G} Beat_182={87.998,0,B min,G} Beat_183={88.478000000000009,0,B min,G} Beat_184={88.958,1,B min,Bm} Beat_185={89.438,0,B min,Bm} Beat_186={89.918,0,B min,Bm} Beat_187={90.398,0,B min,Bm} Beat_188={90.878,1,B min,A} Beat_189={91.358,0,B min,A} Beat_190={91.838000000000008,0,B min,A} Beat_191={92.318,0,B min,A} Beat_192={92.798,1,B min,GM7} Beat_193={93.278,0,B min,GM7} Beat_194={93.758,0,B min,GM7} Beat_195={94.238,0,B min,GM7} Beat_196={94.718,1,B min,F#m7} Beat_197={95.198000000000008,0,B min,F#m7} Beat_198={95.678,0,B min,F#m7} Beat_199={96.158,0,B min,F#m7} Beat_200={96.638,1,B min,GM7} Beat_201={97.118,0,B min,GM7} Beat_202={97.598,0,B min,GM7} Beat_203={98.078,0,B min,GM7} Beat_204={98.558,1,B min,GM7} Beat_205={99.038,0,B min,GM7} Beat_206={99.518,0,B min,GM7} Beat_207={99.998,0,B min,GM7} Beat_208={100.47800000000001,1,B min,A} Beat_209={100.958,0,B min,A} Beat_210={101.438,0,B min,A} Beat_211={101.918,0,B min,A,0.5,Bm7} Beat_212={102.398,1,B min,Bm7} Beat_213={102.878,0,B min,Bm7} Beat_214={103.358,0,B min,Bm7} Beat_215={103.83800000000001,0,B min,Bm7} Beat_216={104.318,1,B min,Em7} Beat_217={104.798,0,B min,Em7} Beat_218={105.278,0,B min,Em7} Beat_219={105.758,0,B min,Em7} Beat_220={106.238,1,B min,Em7} Beat_221={106.718,0,B min,Em7} Beat_222={107.19800000000001,0,B min,Em7} Beat_223={107.678,0,B min,Em7} Beat_224={108.158,1,B min,A6} Beat_225={108.638,0,B min,A6} Beat_226={109.118,0,B min,A6} Beat_227={109.598,0,B min,A6,0.5,F#} Beat_228={110.078,1,B min,F#} Beat_229={110.558,0,B min,F#} Beat_230={111.038,0,B min,F#} Beat_231={111.518,0,B min,F#} Beat_232={111.998,1,B min,F#} Beat_233={112.478,0,B min,F#} Beat_234={112.958,0,B min,F#} Beat_235={113.438,0,B min,F#} Beat_236={113.918,1,C min,Cm} Beat_237={114.398,0,C min,Cm} Beat_238={114.878,0,C min,Cm} Beat_239={115.358,0,C min,Cm} Beat_240={115.838,1,C min,Ab} Beat_241={116.318,0,C min,Ab} Beat_242={116.798,0,C min,Ab} Beat_243={117.278,0,C min,Ab} Beat_244={117.758,1,C min,Bb} Beat_245={118.238,0,C min,Bb} Beat_246={118.718,0,C min,Bb} Beat_247={119.19800000000001,0,C min,Bb} Beat_248={119.678,1,C min,Eb} Beat_249={120.158,0,C min,Eb} Beat_250={120.638,0,C min,Gm/D} Beat_251={121.118,0,C min,Gm/D} Beat_252={121.598,1,C min,Ab} Beat_253={122.078,0,C min,Ab} Beat_254={122.558,0,C min,Ab} Beat_255={123.038,0,C min,Ab} Beat_256={123.518,1,C min,Eb} Beat_257={123.998,0,C min,Eb} Beat_258={124.478,0,C min,Eb} Beat_259={124.958,0,C min,Eb} Beat_260={125.438,1,C min,Bb} Beat_261={125.918,0,C min,Bb} Beat_262={126.398,0,C min,Bb} Beat_263={126.878,0,C min,Bb,0.5,G} Beat_264={127.358,1,C min,G} Beat_265={127.838,0,C min,G} Beat_266={128.31799999999998,0,C min,G} Beat_267={128.798,0,C min,G} Beat_268={129.278,1,C min,Cm} Beat_269={129.758,0,C min,Cm} Beat_270={130.238,0,C min,Cm} Beat_271={130.718,0,C min,Cm} Beat_272={131.198,1,C min,Ab} Beat_273={131.678,0,C min,Ab} Beat_274={132.158,0,C min,Ab} Beat_275={132.638,0,C min,Ab} Beat_276={133.118,1,C min,Bb} Beat_277={133.598,0,C min,Bb} Beat_278={134.078,0,C min,Bb} Beat_279={134.558,0,C min,Bb} Beat_280={135.038,1,C min,Eb} Beat_281={135.518,0,C min,Eb} Beat_282={135.998,0,C min,Gm/D} Beat_283={136.478,0,C min,Gm/D} Beat_284={136.958,1,C min,Ab} Beat_285={137.438,0,C min,Ab} Beat_286={137.918,0,C min,Ab} Beat_287={138.398,0,C min,Ab} Beat_288={138.87800000000001,1,C min,Eb} Beat_289={139.358,0,C min,Eb} Beat_290={139.838,0,C min,Eb} Beat_291={140.318,0,C min,Eb} Beat_292={140.798,1,C min,Bb} Beat_293={141.278,0,C min,Bb} Beat_294={141.758,0,C min,Bb} Beat_295={142.238,0,C min,Bb,0.5,G} Beat_296={142.718,1,C min,G} Beat_297={143.198,0,C min,G} Beat_298={143.678,0,C min,G} Beat_299={144.158,0,C min,G} Beat_300={144.638,1,C min,Cm} Beat_301={145.118,0,C min,Cm} Beat_302={145.598,0,C min,Cm} Beat_303={146.078,0,C min,Cm} Beat_304={146.558,1,C min,Ab} Beat_305={147.038,0,C min,Ab} Beat_306={147.518,0,C min,Ab} Beat_307={147.998,0,C min,Ab} Beat_308={148.478,1,C min,Bb} Beat_309={148.958,0,C min,Bb} Beat_310={149.438,0,C min,Bb} Beat_311={149.918,0,C min,Bb} Beat_312={150.398,1,C min,Eb} Beat_313={150.878,0,C min,Eb} Beat_314={151.358,0,C min,Gm/D} Beat_315={151.838,0,C min,Gm/D} Beat_316={152.318,1,C min,AbM7} Beat_317={152.798,0,C min,AbM7} Beat_318={153.278,0,C min,AbM7} Beat_319={153.758,0,C min,AbM7} Beat_320={154.238,1,C min,AbM7} Beat_321={154.718,0,C min,AbM7} Beat_322={155.198,0,C min,AbM7} Beat_323={155.678,0,C min,AbM7} Beat_324={156.158,1,C min,AbM7} Beat_325={156.638,0,C min,AbM7} Beat_326={157.118,0,C min,AbM7} Beat_327={157.598,0,C min,AbM7,0.5,AbM9} Beat_328={158.078,1,C min,AbM9} Beat_329={158.558,0,C min,AbM9} Beat_330={159.038,0,C min,AbM9} Beat_331={159.518,0,C min,AbM9} Beat_332={159.998,1,C min,AbM9} Beat_333={160.478,0,C min,AbM9} Beat_334={160.958,0,C min,AbM9} Beat_335={161.438,0,C min,AbM9} Beat_336={161.918,1,C min,AbM9} Beat_337={162.398,0,C min,AbM9} Beat_338={162.878,0,C min,AbM9} Beat_339={163.358,0,C min,AbM9} Beat_340={163.838,1,C min,N} Beat_341={164.318,0,C min,N} Beat_342={164.798,0,C min,N} Beat_343={165.278,0,C min,N} Beat_344={165.758,1,C min,N} Beat_345={166.238,0,C min,N} Beat_346={166.718,0,C min,N} Beat_347={167.198,0,C min,N} Beat_348={167.678,1,C min,N} Beat_349={168.158,0,C min,N} Beat_350={168.638,0,C min,N} Beat_351={169.118,0,C min,N} Beat_352={169.59799999999999,1,C min,N} Beat_353={170.078,0,G min,N} ",8049,True,2786.9887061554173,median "// Verilated -*- C++ -*- // DESCRIPTION: Verilator output: Design implementation internals // See VusbHostSlave.h for the primary calling header #include ""VusbHostSlave_hostcontroller.h"" // For This #include ""VusbHostSlave__Syms.h"" //-------------------- // STATIC VARIABLES //-------------------- VL_CTOR_IMP(VusbHostSlave_hostcontroller) { // Reset internal values // Reset structure values __PVT__RXStatus = VL_RAND_RESET_I(8); __PVT__clk = VL_RAND_RESET_I(1); __PVT__getPacketRdy = VL_RAND_RESET_I(1); __PVT__isoEn = VL_RAND_RESET_I(1); __PVT__rst = VL_RAND_RESET_I(1); __PVT__sendPacketArbiterGnt = VL_RAND_RESET_I(1); __PVT__sendPacketRdy = VL_RAND_RESET_I(1); __PVT__transReq = VL_RAND_RESET_I(1); __PVT__transType = VL_RAND_RESET_I(2); __PVT__clearTXReq = VL_RAND_RESET_I(1); __PVT__getPacketREn = VL_RAND_RESET_I(1); __PVT__sendPacketArbiterReq = VL_RAND_RESET_I(1); __PVT__sendPacketPID = VL_RAND_RESET_I(4); __PVT__sendPacketWEn = VL_RAND_RESET_I(1); __PVT__transDone = VL_RAND_RESET_I(1); __PVT__next_clearTXReq = VL_RAND_RESET_I(1); __PVT__next_getPacketREn = VL_RAND_RESET_I(1); __PVT__next_sendPacketArbiterReq = VL_RAND_RESET_I(1); __PVT__next_sendPacketPID = VL_RAND_RESET_I(4); __PVT__next_sendPacketWEn = VL_RAND_RESET_I(1); __PVT__next_transDone = VL_RAND_RESET_I(1); __PVT__delCnt = VL_RAND_RESET_I(4); __PVT__next_delCnt = VL_RAND_RESET_I(4); __PVT__CurrState_hstCntrl = VL_RAND_RESET_I(6); __PVT__NextState_hstCntrl = VL_RAND_RESET_I(6); __Vdly__CurrState_hstCntrl = VL_RAND_RESET_I(6); __Vdly__delCnt = VL_RAND_RESET_I(4); __Vdly__transDone = VL_RAND_RESET_I(1); __Vdly__clearTXReq = VL_RAND_RESET_I(1); __Vdly__getPacketREn = VL_RAND_RESET_I(1); __Vdly__sendPacketArbiterReq = VL_RAND_RESET_I(1); __Vdly__sendPacketWEn = VL_RAND_RESET_I(1); __Vdly__sendPacketPID = VL_RAND_RESET_I(4); } void VusbHostSlave_hostcontroller::__Vconfigure(VusbHostSlave__Syms* vlSymsp, bool first) { if (0 && first) {} // Prevent unused this->__VlSymsp = vlSymsp; } VusbHostSlave_hostcontroller::~VusbHostSlave_hostcontroller() { } //-------------------- // Internal Methods void VusbHostSlave_hostcontroller::_sequent__TOP__v__u_usbHostControl__u_hostController__1(VusbHostSlave__Syms* __restrict vlSymsp) { VL_DEBUG_IF(VL_PRINTF("" VusbHostSlave_hostcontroller::_sequent__TOP__v__u_usbHostControl__u_hostController__1\\n""); ); VusbHostSlave* __restrict vlTOPp VL_ATTR_UNUSED = vlSymsp->TOPp; // Body vlSymsp->TOP__v__u_usbHostControl__u_hostController.__Vdly__CurrState_hstCntrl = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__Vdly__delCnt = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__delCnt; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__Vdly__transDone = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__transDone; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__Vdly__clearTXReq = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__clearTXReq; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__Vdly__sendPacketArbiterReq = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketArbiterReq; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__Vdly__getPacketREn = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__getPacketREn; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__Vdly__sendPacketWEn = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketWEn; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__Vdly__sendPacketPID = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketPID; // ALWAYS at trunk/RTL/hostController//hostcontroller.v:363 vlSymsp->TOP__v__u_usbHostControl__u_hostController.__Vdly__CurrState_hstCntrl = ((IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__rst) ? 0 : (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl)); // ALWAYS at trunk/RTL/hostController//hostcontroller.v:374 if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__rst) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__Vdly__delCnt = 0; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__Vdly__transDone = 0; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__Vdly__clearTXReq = 0; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__Vdly__getPacketREn = 0; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__Vdly__sendPacketArbiterReq = 0; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__Vdly__sendPacketWEn = 0; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__Vdly__sendPacketPID = 0; } else { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__Vdly__delCnt = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_delCnt; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__Vdly__transDone = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_transDone; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__Vdly__clearTXReq = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_clearTXReq; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__Vdly__getPacketREn = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_getPacketREn; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__Vdly__sendPacketArbiterReq = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketArbiterReq; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__Vdly__sendPacketWEn = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__Vdly__sendPacketPID = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketPID; } vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__Vdly__CurrState_hstCntrl; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__delCnt = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__Vdly__delCnt; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__clearTXReq = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__Vdly__clearTXReq; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__transDone = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__Vdly__transDone; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketArbiterReq = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__Vdly__sendPacketArbiterReq; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__getPacketREn = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__Vdly__getPacketREn; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketWEn = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__Vdly__sendPacketWEn; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketPID = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__Vdly__sendPacketPID; } void VusbHostSlave_hostcontroller::_settle__TOP__v__u_usbHostControl__u_hostController__2(VusbHostSlave__Syms* __restrict vlSymsp) { VL_DEBUG_IF(VL_PRINTF("" VusbHostSlave_hostcontroller::_settle__TOP__v__u_usbHostControl__u_hostController__2\\n""); ); VusbHostSlave* __restrict vlTOPp VL_ATTR_UNUSED = vlSymsp->TOPp; // Body // ALWAYS at trunk/RTL/hostController//hostcontroller.v:144 vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketArbiterReq = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketArbiterReq; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_transDone = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__transDone; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_clearTXReq = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__clearTXReq; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_delCnt = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__delCnt; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketWEn; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_getPacketREn = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__getPacketREn; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketPID = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketPID; if (((((((((0 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl)) | (1 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (2 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (3 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (9 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0xa == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (7 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (8 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl)))) { if ((0 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 1; } else { if ((1 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__transReq) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0xa; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketArbiterReq = 1; } } else { if ((2 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { if ((1 == VL_EXTEND_II(32,2, (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__transType)))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x11; } else { if ((2 == VL_EXTEND_II(32,2, (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__transType)))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x13; } else { if ((3 == VL_EXTEND_II(32,2, (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__transType)))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x1d; } else { if ((0 == VL_EXTEND_II(32,2, (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__transType)))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x10; } } } } } else { if ((3 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_transDone = 1; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_clearTXReq = 1; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketArbiterReq = 0; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_delCnt = 0; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 9; } else { if ((9 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_clearTXReq = 0; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_transDone = 0; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_delCnt = (0xf & ((IData)(1) + (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__delCnt))); if ((0xf == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__delCnt))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 1; } } else { if ((0xa == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketArbiterGnt) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 2; } } else { if ((7 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 0; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x14; } else { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 0; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x15; } } } } } } } } else { if (((((((((0xb == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl)) | (0x10 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0x14 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0x15 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (4 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (5 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (6 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0xc == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl)))) { if ((0xb == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_getPacketREn = 0; if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__getPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 3; } } else { if ((0x10 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 7; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 1; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketPID = 0xd; } } else { if ((0x14 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 8; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 1; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketPID = 3; } } else { if ((0x15 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0xb; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_getPacketREn = 1; } } else { if ((4 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_getPacketREn = 0; if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__getPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 5; } } else { if ((5 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = ((IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__isoEn) ? 3 : ( (1 & ((((((~ VL_BITSEL_IIII(1,8,3,32, (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__RXStatus), 0)) & (~ VL_BITSEL_IIII(1,8,3,32, (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__RXStatus), 1))) & (~ VL_BITSEL_IIII(1,8,3,32, (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__RXStatus), 2))) & (~ VL_BITSEL_IIII(1,8,3,32, (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__RXStatus), 4))) & (~ VL_BITSEL_IIII(1,8,3,32, (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__RXStatus), 5))) & (~ VL_BITSEL_IIII(1,8,3,32, (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__RXStatus), 3)))) ? 0x12 : 3)); } else { if ((6 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 0; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x17; } else { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 4; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_getPacketREn = 1; } } } } } } } } } else { if (((((((((0x11 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl)) | (0x12 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0x16 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0x17 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0xd == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0xe == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0xf == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0x13 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl)))) { if ((0x11 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x16; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 1; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketPID = 9; } } else { if ((0x12 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 6; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 1; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketPID = 2; } } else { if ((0x16 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 0; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0xc; } else { if ((0x17 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 3; } } else { if ((0xd == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_getPacketREn = 0; if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__getPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 3; } } else { if ((0xe == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x20; } } else { if ((0xf == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x19; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 1; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketPID = 3; } } else { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x18; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 1; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketPID = 1; } } } } } } } } } else { if (((((((((0x18 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl)) | (0x19 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0x20 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0x1a == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0x1b == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0x1c == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0x1d == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0x1e == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl)))) { if ((0x18 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 0; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0xf; } else { if ((0x19 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 0; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0xe; } else { if ((0x20 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__isoEn) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 3; } else { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0xd; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_getPacketREn = 1; } } else { if ((0x1a == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_getPacketREn = 0; if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__getPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 3; } } else { if ((0x1b == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x1f; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 1; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketPID = 0xb; } } else { if ((0x1c == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x1a; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_getPacketREn = 1; } } else { if ((0x1d == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x1e; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 1; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketPID = 1; } } else { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 0; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x1b; } } } } } } } } else { if ((0x1f == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 0; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x1c; } } } } } } void VusbHostSlave_hostcontroller::_combo__TOP__v__u_usbHostControl__u_hostController__3(VusbHostSlave__Syms* __restrict vlSymsp) { VL_DEBUG_IF(VL_PRINTF("" VusbHostSlave_hostcontroller::_combo__TOP__v__u_usbHostControl__u_hostController__3\\n""); ); VusbHostSlave* __restrict vlTOPp VL_ATTR_UNUSED = vlSymsp->TOPp; // Body // ALWAYS at trunk/RTL/hostController//hostcontroller.v:144 vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketArbiterReq = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketArbiterReq; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_transDone = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__transDone; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_clearTXReq = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__clearTXReq; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_delCnt = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__delCnt; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketWEn; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_getPacketREn = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__getPacketREn; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketPID = vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketPID; if (((((((((0 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl)) | (1 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (2 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (3 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (9 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0xa == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (7 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (8 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl)))) { if ((0 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 1; } else { if ((1 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__transReq) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0xa; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketArbiterReq = 1; } } else { if ((2 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { if ((1 == VL_EXTEND_II(32,2, (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__transType)))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x11; } else { if ((2 == VL_EXTEND_II(32,2, (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__transType)))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x13; } else { if ((3 == VL_EXTEND_II(32,2, (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__transType)))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x1d; } else { if ((0 == VL_EXTEND_II(32,2, (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__transType)))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x10; } } } } } else { if ((3 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_transDone = 1; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_clearTXReq = 1; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketArbiterReq = 0; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_delCnt = 0; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 9; } else { if ((9 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_clearTXReq = 0; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_transDone = 0; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_delCnt = (0xf & ((IData)(1) + (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__delCnt))); if ((0xf == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__delCnt))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 1; } } else { if ((0xa == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketArbiterGnt) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 2; } } else { if ((7 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 0; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x14; } else { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 0; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x15; } } } } } } } } else { if (((((((((0xb == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl)) | (0x10 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0x14 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0x15 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (4 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (5 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (6 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0xc == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl)))) { if ((0xb == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_getPacketREn = 0; if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__getPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 3; } } else { if ((0x10 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 7; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 1; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketPID = 0xd; } } else { if ((0x14 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 8; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 1; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketPID = 3; } } else { if ((0x15 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0xb; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_getPacketREn = 1; } } else { if ((4 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_getPacketREn = 0; if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__getPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 5; } } else { if ((5 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = ((IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__isoEn) ? 3 : ( (1 & ((((((~ VL_BITSEL_IIII(1,8,3,32, (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__RXStatus), 0)) & (~ VL_BITSEL_IIII(1,8,3,32, (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__RXStatus), 1))) & (~ VL_BITSEL_IIII(1,8,3,32, (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__RXStatus), 2))) & (~ VL_BITSEL_IIII(1,8,3,32, (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__RXStatus), 4))) & (~ VL_BITSEL_IIII(1,8,3,32, (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__RXStatus), 5))) & (~ VL_BITSEL_IIII(1,8,3,32, (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__RXStatus), 3)))) ? 0x12 : 3)); } else { if ((6 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 0; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x17; } else { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 4; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_getPacketREn = 1; } } } } } } } } } else { if (((((((((0x11 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl)) | (0x12 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0x16 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0x17 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0xd == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0xe == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0xf == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0x13 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl)))) { if ((0x11 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x16; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 1; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketPID = 9; } } else { if ((0x12 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 6; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 1; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketPID = 2; } } else { if ((0x16 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 0; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0xc; } else { if ((0x17 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 3; } } else { if ((0xd == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_getPacketREn = 0; if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__getPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 3; } } else { if ((0xe == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x20; } } else { if ((0xf == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x19; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 1; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketPID = 3; } } else { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x18; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 1; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketPID = 1; } } } } } } } } } else { if (((((((((0x18 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl)) | (0x19 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0x20 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0x1a == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0x1b == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0x1c == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0x1d == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) | (0x1e == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl)))) { if ((0x18 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 0; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0xf; } else { if ((0x19 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 0; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0xe; } else { if ((0x20 == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__isoEn) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 3; } else { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0xd; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_getPacketREn = 1; } } else { if ((0x1a == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_getPacketREn = 0; if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__getPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 3; } } else { if ((0x1b == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x1f; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 1; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketPID = 0xb; } } else { if ((0x1c == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x1a; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_getPacketREn = 1; } } else { if ((0x1d == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { if (vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__sendPacketRdy) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x1e; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 1; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketPID = 1; } } else { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 0; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x1b; } } } } } } } } else { if ((0x1f == (IData)(vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__CurrState_hstCntrl))) { vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__next_sendPacketWEn = 0; vlSymsp->TOP__v__u_usbHostControl__u_hostController.__PVT__NextState_hstCntrl = 0x1c; } } } } } } ",16200,True,5243.0830053638,median "/*************************************************************************** * Copyright (c) 2016, Johan Mabille, Sylvain Corlay and Wolf Vollprecht * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #include #include ""gtest/gtest.h"" #include ""xtensor/xarray.hpp"" #include ""xtensor/xbuilder.hpp"" #include ""xtensor/xfixed.hpp"" #include ""xtensor/xnoalias.hpp"" #include ""xtensor/xstrided_view.hpp"" #include ""xtensor/xmanipulation.hpp"" #include ""xtensor/xtensor.hpp"" #include ""xtensor/xview.hpp"" #include ""xtensor/xrandom.hpp"" namespace xt { using std::size_t; using view_shape_type = dynamic_shape; template bool operator==(const A& lhs, const sequence_view& rhs) { return lhs.size() == rhs.size() && std::equal(rhs.begin(), rhs.end(), lhs.begin()); } template bool operator==(const sequence_view& lhs, const A& rhs) { return lhs.size() == rhs.size() && std::equal(rhs.begin(), rhs.end(), lhs.begin()); } TEST(xview, temporary_type) { { view_shape_type shape = {3, 4}; xarray a(shape); auto view1 = view(a, 1, range(1, 4)); bool check = std::is_same, typename xcontainer_inner_types::temporary_type>::value; EXPECT_TRUE(check); } { xtensor::shape_type shape = {3, 4}; xtensor a(shape); auto view1 = view(a, 1, range(1, 4)); bool check1 = std::is_same, typename xcontainer_inner_types::temporary_type>::value; EXPECT_TRUE(check1); auto view2 = view(a, all(), newaxis(), range(1, 4)); bool check2 = std::is_same, typename xcontainer_inner_types::temporary_type>::value; EXPECT_TRUE(check2); } } TEST(xview, simple) { view_shape_type shape = {3, 4}; xarray a(shape); std::vector data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::copy(data.cbegin(), data.cend(), a.template begin()); auto view1 = view(a, 1, range(1, 4)); EXPECT_EQ(a(1, 1), view1(0)); EXPECT_EQ(a(1, 2), view1(1)); EXPECT_EQ(size_t(1), view1.dimension()); EXPECT_ANY_THROW(view1.at(10)); EXPECT_ANY_THROW(view1.at(0, 0)); auto view0 = view(a, 0, range(0, 3)); EXPECT_EQ(a(0, 0), view0(0)); EXPECT_EQ(a(0, 1), view0(1)); EXPECT_EQ(size_t(1), view0.dimension()); EXPECT_EQ(size_t(3), view0.shape()[0]); auto view2 = view(a, range(0, 2), 2); EXPECT_EQ(a(0, 2), view2(0)); EXPECT_EQ(a(1, 2), view2(1)); EXPECT_EQ(size_t(1), view2.dimension()); EXPECT_EQ(size_t(2), view2.shape()[0]); auto view4 = view(a, 1); EXPECT_EQ(size_t(1), view4.dimension()); EXPECT_EQ(size_t(4), view4.shape()[0]); auto view5 = view(view4, 1); EXPECT_EQ(size_t(0), view5.dimension()); EXPECT_EQ(size_t(0), view5.shape().size()); auto view6 = view(a, 1, all()); EXPECT_EQ(a(1, 0), view6(0)); EXPECT_EQ(a(1, 1), view6(1)); EXPECT_EQ(a(1, 2), view6(2)); EXPECT_EQ(a(1, 3), view6(3)); auto view7 = view(a, all(), 2); EXPECT_EQ(a(0, 2), view7(0)); EXPECT_EQ(a(1, 2), view7(1)); EXPECT_EQ(a(2, 2), view7(2)); if (a.layout() == layout_type::row_major) { EXPECT_EQ(a.layout(), view1.layout()); EXPECT_EQ(layout_type::dynamic, view2.layout()); EXPECT_EQ(a.layout(), view4.layout()); EXPECT_EQ(a.layout(), view5.layout()); EXPECT_EQ(a.layout(), view6.layout()); EXPECT_EQ(layout_type::dynamic, view7.layout()); } else { EXPECT_EQ(layout_type::dynamic, view1.layout()); EXPECT_EQ(a.layout(), view2.layout()); EXPECT_EQ(layout_type::dynamic, view4.layout()); // TODO ideally this would return the underlying expression's layout // but needs special casing 'view-on-view' EXPECT_EQ(layout_type::dynamic, view5.layout()); EXPECT_EQ(layout_type::dynamic, view6.layout()); EXPECT_EQ(a.layout(), view7.layout()); } } TEST(xview, stored_range) { view_shape_type shape = { 3, 4 }; xarray a(shape); std::vector data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; std::copy(data.cbegin(), data.cend(), a.template begin()); auto r0 = range(1, 3); auto r1 = range(0, 3); auto view0 = view(a, r0, r1); view0 += xt::ones({2, 3}); EXPECT_EQ(a(1, 0), 6); EXPECT_EQ(a(1, 1), 7); EXPECT_EQ(a(1, 2), 8); EXPECT_EQ(a(2, 0), 10); EXPECT_EQ(a(2, 1), 11); EXPECT_EQ(a(2, 2), 12); } TEST(xview, copy_semantic) { view_shape_type shape = { 3, 4 }; xarray a(shape); std::vector data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; std::copy(data.cbegin(), data.cend(), a.template begin()); { SCOPED_TRACE(""copy constructor""); auto view1 = view(a, 1, range(1, 4)); auto view2(view1); EXPECT_EQ(a(1, 1), view2(0)); EXPECT_EQ(a(1, 2), view2(1)); EXPECT_EQ(size_t(1), view2.dimension()); if (a.layout() == layout_type::row_major) { EXPECT_EQ(a.layout(), view2.layout()); } else { EXPECT_EQ(layout_type::dynamic, view2.layout()); } } { SCOPED_TRACE(""copy assignment operator""); auto view1 = view(a, 1, range(1, 4)); auto view2 = view(a, 2, range(0, 3)); view2 = view1; EXPECT_EQ(a(2, 0), a(1, 1)); EXPECT_EQ(a(2, 1), a(1, 2)); EXPECT_EQ(a(2, 2), a(1, 3)); } } TEST(xview, move_semantic) { view_shape_type shape = { 3, 4 }; xarray a(shape); std::vector data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; std::copy(data.cbegin(), data.cend(), a.template begin()); { SCOPED_TRACE(""copy constructor""); auto view1 = view(a, 1, range(1, 4)); auto view2(std::move(view1)); EXPECT_EQ(a(1, 1), view2(0)); EXPECT_EQ(a(1, 2), view2(1)); EXPECT_EQ(size_t(1), view2.dimension()); if (a.layout() == layout_type::row_major) { EXPECT_EQ(a.layout(), view2.layout()); } else { EXPECT_EQ(layout_type::dynamic, view2.layout()); } } { SCOPED_TRACE(""copy assignment operator""); auto view1 = view(a, 1, range(1, 4)); auto view2 = view(a, 2, range(0, 3)); view2 = std::move(view1); EXPECT_EQ(a(2, 0), a(1, 1)); EXPECT_EQ(a(2, 1), a(1, 2)); EXPECT_EQ(a(2, 2), a(1, 3)); } } TEST(xview, three_dimensional) { view_shape_type shape = {3, 4, 2}; std::vector data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 21, 22, 23, 24, 25, 26, 27, 28, 29, 210, 211, 212 }; xarray a(shape); std::copy(data.cbegin(), data.cend(), a.template begin()); auto view1 = view(a, 1); EXPECT_EQ(size_t(2), view1.dimension()); EXPECT_EQ(a(1, 0, 0), view1(0, 0)); EXPECT_EQ(a(1, 0, 1), view1(0, 1)); EXPECT_EQ(a(1, 1, 0), view1(1, 0)); EXPECT_EQ(a(1, 1, 1), view1(1, 1)); EXPECT_ANY_THROW(view1.at(10, 10)); EXPECT_ANY_THROW(view1.at(0, 0, 0)); std::array idx = {1, 1}; EXPECT_EQ(a(1, 1, 1), view1.element(idx.cbegin(), idx.cend())); } TEST(xview, integral_count) { size_t squeeze1 = integral_count>(); EXPECT_EQ(squeeze1, size_t(3)); size_t squeeze2 = integral_count, size_t>(); EXPECT_EQ(squeeze2, size_t(2)); size_t squeeze3 = integral_count_before>(3); EXPECT_EQ(squeeze3, size_t(3)); size_t squeeze4 = integral_count_before, size_t>(2); EXPECT_EQ(squeeze4, size_t(1)); size_t squeeze5 = integral_count>(); EXPECT_EQ(squeeze5, size_t(0)); } TEST(xview, integral_skip) { size_t index0 = integral_skip, size_t, xrange>(0); size_t index1 = integral_skip, size_t, xrange>(1); size_t index2 = integral_skip, size_t, xrange>(2); EXPECT_EQ(index0, size_t(1)); EXPECT_EQ(index1, size_t(3)); EXPECT_EQ(index2, size_t(4)); } TEST(xview, single_newaxis_shape) { xarray a = {1, 2, 3, 4}; auto v = view(a, newaxis()); view_shape_type s = {1, 4}; EXPECT_EQ(s, v.shape()); } TEST(xview, temporary_view) { xt::xarray arr1 {{1.0, 2.0, 3.0}, {2.0, 5.0, 7.0}, {2.0, 5.0, 7.0}}; xt::xarray arr2 {5.0, 6.0, 7.0}; xt::xarray res = xt::view(arr1, 1) + arr2; EXPECT_EQ(7., res(0)); EXPECT_EQ(11., res(1)); EXPECT_EQ(14., res(2)); } TEST(xview, access) { xt::xarray arr {{ 1.0, 2.0, 3.0 }, { 2.0, 5.0, 7.0 }, { 2.0, 5.0, 7.0 }}; auto v1 = xt::view(arr, 1, xt::range(1, 3)); EXPECT_EQ(v1(), arr(0, 1)); EXPECT_EQ(v1(1), arr(1, 2)); EXPECT_EQ(v1(1, 1), arr(1, 2)); auto v2 = xt::view(arr, all(), newaxis(), all()); //EXPECT_EQ(v2(1), arr(0, 1)); EXPECT_EQ(v2(1, 0, 2), arr(1, 2)); EXPECT_EQ(v2(2, 1, 0, 2), arr(1, 2)); auto v3 = xt::view(arr, xt::range(0, 2), xt::range(1, 3)); //EXPECT_EQ(v3(1), arr(0, 2)); EXPECT_EQ(v3(1, 1), arr(1, 2)); EXPECT_EQ(v3(2, 3, 1, 1), arr(1, 2)); } TEST(xview, unchecked) { xt::xarray arr { { 1.0, 2.0, 3.0 }, { 2.0, 5.0, 7.0 }, { 2.0, 5.0, 7.0 } }; auto v1 = xt::view(arr, 1, xt::range(1, 3)); EXPECT_EQ(v1.unchecked(1), arr(1, 2)); auto v2 = xt::view(arr, all(), newaxis(), all()); EXPECT_EQ(v2.unchecked(1, 0, 2), arr(1, 2)); auto v3 = xt::view(arr, xt::range(0, 2), xt::range(1, 3)); EXPECT_EQ(v3.unchecked(1, 1), arr(1, 2)); } TEST(xview, iterator) { view_shape_type shape = {2, 3, 4}; xarray a(shape); std::vector data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}; std::copy(data.cbegin(), data.cend(), a.template begin()); auto view1 = view(a, range(0, 2), 1, range(1, 4)); auto iter = view1.template begin(); auto iter_end = view1.template end(); EXPECT_EQ(6, *iter); ++iter; EXPECT_EQ(7, *iter); ++iter; EXPECT_EQ(8, *iter); ++iter; EXPECT_EQ(18, *iter); ++iter; EXPECT_EQ(19, *iter); ++iter; EXPECT_EQ(20, *iter); ++iter; EXPECT_EQ(iter, iter_end); auto view2 = view(view1, range(0, 2), range(1, 3)); auto iter2 = view2.template begin(); auto iter_end2 = view2.template end(); EXPECT_EQ(7, *iter2); ++iter2; EXPECT_EQ(8, *iter2); ++iter2; EXPECT_EQ(19, *iter2); ++iter2; EXPECT_EQ(20, *iter2); ++iter2; EXPECT_EQ(iter2, iter_end2); } TEST(xview, fill) { view_shape_type shape = { 2, 3, 4 }; xarray a(shape), res(shape); std::vector data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 }; std::copy(data.cbegin(), data.cend(), a.template begin()); std::vector data_res = { 1, 2, 3, 4, 5, 4, 4, 4, 9, 10, 11, 12, 13, 14, 15, 16, 17, 4, 4, 4, 21, 22, 23, 24 }; std::copy(data_res.cbegin(), data_res.cend(), res.template begin()); auto view1 = view(a, range(0, 2), 1, range(1, 4)); view1.fill(4); EXPECT_EQ(a, res); } TEST(xview, reverse_iterator) { view_shape_type shape = {2, 3, 4}; xarray a(shape); std::vector data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}; std::copy(data.cbegin(), data.cend(), a.template begin()); auto view1 = view(a, range(0, 2), 1, range(1, 4)); auto iter = view1.template rbegin(); auto iter_end = view1.template rend(); EXPECT_EQ(20, *iter); ++iter; EXPECT_EQ(19, *iter); ++iter; EXPECT_EQ(18, *iter); ++iter; EXPECT_EQ(8, *iter); ++iter; EXPECT_EQ(7, *iter); ++iter; EXPECT_EQ(6, *iter); ++iter; EXPECT_EQ(iter, iter_end); auto view2 = view(view1, range(0, 2), range(1, 3)); auto iter2 = view2.template rbegin(); auto iter_end2 = view2.template rend(); EXPECT_EQ(20, *iter2); ++iter2; EXPECT_EQ(19, *iter2); ++iter2; EXPECT_EQ(8, *iter2); ++iter2; EXPECT_EQ(7, *iter2); ++iter2; EXPECT_EQ(iter2, iter_end2); } TEST(xview, xview_on_xfunction) { view_shape_type shape = {3, 4}; xarray a(shape); std::vector data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::copy(data.cbegin(), data.cend(), a.template begin()); view_shape_type shape2 = {4}; xarray b(shape2); std::vector data2 = {1, 2, 3, 4}; std::copy(data2.cbegin(), data2.cend(), b.template begin()); auto v = view(a + b, 1, range(1, 4)); auto iter = v.begin(); auto iter_end = v.end(); EXPECT_EQ(8, *iter); ++iter; EXPECT_EQ(10, *iter); ++iter; EXPECT_EQ(12, *iter); ++iter; EXPECT_EQ(iter, iter_end); } TEST(xview, xview_on_xtensor) { xtensor a({3, 4}); std::vector data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::copy(data.cbegin(), data.cend(), a.template begin()); auto view1 = view(a, 1, range(1, 4)); EXPECT_EQ(a(1, 1), view1(0)); EXPECT_EQ(a(1, 2), view1(1)); EXPECT_EQ(size_t(1), view1.dimension()); auto iter = view1.template begin(); EXPECT_EQ(6, *iter); ++iter; EXPECT_EQ(7, *iter); ++iter; EXPECT_EQ(8, *iter); xarray b({3}, 2); xtensor res = view1 + b; EXPECT_EQ(8, res(0)); EXPECT_EQ(9, res(1)); EXPECT_EQ(10, res(2)); } TEST(xview, on_const_array) { const xt::xarray a1{{0, 1}, {2, 3}}; auto a2 = xt::view(a1, 1, xt::range(1, 2)); int v2 = a2(0); EXPECT_EQ(v2, 3); auto it = a2.begin(); } TEST(xview, trivial_iterating) { using tensor_type = xtensor; using shape_type = tensor_type::shape_type; tensor_type arr1{shape_type{2}}; std::fill(arr1.begin(), arr1.end(), 6); auto view = xt::view(arr1, 0); auto iter = view.begin(); auto iter_end = view.end(); ++iter; EXPECT_EQ(iter, iter_end); } TEST(xview, const_trivial_iterating) { using tensor_type = xtensor; using shape_type = tensor_type::shape_type; tensor_type arr1{shape_type{2}}; std::fill(arr1.begin(), arr1.end(), 6); const tensor_type arr2 = arr1; auto view = xt::view(arr2, 0); auto iter = view.begin(); auto iter_end = view.end(); ++iter; EXPECT_EQ(iter, iter_end); } TEST(xview, const_view) { typename xtensor::shape_type shape3 = {1, 2, 3}; typename xtensor::shape_type shape2 = {2, 3}; const xtensor arr(shape3, 2.5); xtensor arr2(shape2, 0.0); xtensor ref(shape2, 2.5); arr2 = xt::view(arr, 0); EXPECT_EQ(ref, arr2); } TEST(xview, newaxis_count) { size_t count1 = newaxis_count, xnewaxis, xnewaxis, xrange>(); EXPECT_EQ(count1, size_t(3)); size_t count2 = newaxis_count, xrange, xnewaxis>(); EXPECT_EQ(count2, size_t(2)); size_t count3 = newaxis_count_before, xnewaxis, xnewaxis, xrange>(3); EXPECT_EQ(count3, size_t(3)); size_t count4 = newaxis_count_before, xrange, xnewaxis>(2); EXPECT_EQ(count4, size_t(1)); } TEST(xview, newaxis) { view_shape_type shape = {3, 4}; xarray a(shape); std::vector data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::copy(data.cbegin(), data.cend(), a.template begin()); auto view1 = view(a, all(), newaxis(), all()); EXPECT_EQ(a(1, 1), view1(1, 0, 1)); EXPECT_EQ(a(1, 2), view1(1, 0, 2)); EXPECT_EQ(size_t(3), view1.dimension()); EXPECT_EQ(size_t(3), view1.shape()[0]); EXPECT_EQ(size_t(1), view1.shape()[1]); EXPECT_EQ(size_t(4), view1.shape()[2]); auto view2 = view(a, all(), all(), newaxis()); EXPECT_EQ(a(1, 1), view2(1, 1, 0)); EXPECT_EQ(a(1, 2), view2(1, 2, 0)); EXPECT_EQ(size_t(3), view2.dimension()); EXPECT_EQ(size_t(3), view2.shape()[0]); EXPECT_EQ(size_t(4), view2.shape()[1]); EXPECT_EQ(size_t(1), view2.shape()[2]); auto view3 = view(a, 1, newaxis(), all()); EXPECT_EQ(a(1, 1), view3(0, 1)); EXPECT_EQ(a(1, 2), view3(0, 2)); EXPECT_EQ(size_t(2), view3.dimension()); auto view4 = view(a, 1, all(), newaxis()); EXPECT_EQ(a(1, 1), view4(1, 0)); EXPECT_EQ(a(1, 2), view4(2, 0)); EXPECT_EQ(size_t(2), view4.dimension()); auto view5 = view(view1, 1); EXPECT_EQ(a(1, 1), view5(0, 1)); EXPECT_EQ(a(1, 2), view5(0, 2)); EXPECT_EQ(size_t(2), view5.dimension()); auto view6 = view(view2, 1); EXPECT_EQ(a(1, 1), view6(1, 0)); EXPECT_EQ(a(1, 2), view6(2, 0)); EXPECT_EQ(size_t(2), view6.dimension()); std::array idx1 = {1, 0, 2}; EXPECT_EQ(a(1, 2), view1.element(idx1.begin(), idx1.end())); std::array idx2 = {1, 2, 0}; EXPECT_EQ(a(1, 2), view2.element(idx2.begin(), idx2.end())); std::array idx3 = {1, 2}; EXPECT_EQ(a(1, 2), view3.element(idx3.begin(), idx3.end())); xt::xarray x5 = xt::ones({1,4,16,16}); auto view7 = xt::view(x5, xt::all(), xt::newaxis(), xt::all(), xt::all(), xt::all()); std::array idx4 = {0, 0, 2, 14, 12}; EXPECT_EQ(view7.element(idx4.begin(), idx4.end()), 1.f); } TEST(xview, newaxis_iterating) { view_shape_type shape = {3, 4}; xarray a(shape); std::vector data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::copy(data.cbegin(), data.cend(), a.template begin()); auto view1 = view(a, all(), all(), newaxis()); auto iter1 = view1.template begin(); auto iter1_end = view1.template end(); EXPECT_EQ(a(0, 0), *iter1); ++iter1; EXPECT_EQ(a(0, 1), *iter1); ++iter1; EXPECT_EQ(a(0, 2), *iter1); ++iter1; EXPECT_EQ(a(0, 3), *iter1); ++iter1; EXPECT_EQ(a(1, 0), *iter1); ++iter1; EXPECT_EQ(a(1, 1), *iter1); ++iter1; EXPECT_EQ(a(1, 2), *iter1); ++iter1; EXPECT_EQ(a(1, 3), *iter1); ++iter1; EXPECT_EQ(a(2, 0), *iter1); ++iter1; EXPECT_EQ(a(2, 1), *iter1); ++iter1; EXPECT_EQ(a(2, 2), *iter1); ++iter1; EXPECT_EQ(a(2, 3), *iter1); ++iter1; EXPECT_EQ(iter1_end, iter1); auto view2 = view(a, all(), newaxis(), all()); auto iter2 = view2.template begin(); auto iter2_end = view2.template end(); EXPECT_EQ(a(0, 0), *iter2); ++iter2; EXPECT_EQ(a(0, 1), *iter2); ++iter2; EXPECT_EQ(a(0, 2), *iter2); ++iter2; EXPECT_EQ(a(0, 3), *iter2); ++iter2; EXPECT_EQ(a(1, 0), *iter2); ++iter2; EXPECT_EQ(a(1, 1), *iter2); ++iter2; EXPECT_EQ(a(1, 2), *iter2); ++iter2; EXPECT_EQ(a(1, 3), *iter2); ++iter2; EXPECT_EQ(a(2, 0), *iter2); ++iter2; EXPECT_EQ(a(2, 1), *iter2); ++iter2; EXPECT_EQ(a(2, 2), *iter2); ++iter2; EXPECT_EQ(a(2, 3), *iter2); ++iter2; EXPECT_EQ(iter2_end, iter2); } TEST(xview, newaxis_function) { view_shape_type shape = {3, 4}; xarray a(shape); std::vector data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::copy(data.cbegin(), data.cend(), a.template begin()); xarray b(view_shape_type(1, 4)); std::copy(data.cbegin(), data.cbegin() + 4, b.template begin()); auto v = view(b, newaxis(), all()); xarray res = a + v; std::vector data2{2, 4, 6, 8, 6, 8, 10, 12, 10, 12, 14, 16}; xarray expected(shape); std::copy(data2.cbegin(), data2.cend(), expected.template begin()); EXPECT_EQ(expected, res); } TEST(xview, range_adaptor) { using namespace xt::placeholders; using t = xarray; t a = {1, 2, 3, 4, 5}; auto n = xnone(); auto v1 = view(a, range(3, _)); t v1e = {4, 5}; EXPECT_TRUE(v1e == v1); auto v2 = view(a, range(_, 2)); t v2e = {1, 2}; EXPECT_TRUE(v2e == v2); auto v3 = view(a, range(n, n)); t v3e = {1, 2, 3, 4, 5}; EXPECT_TRUE(v3e == v3); auto v4 = view(a, range(n, 2, -1)); t v4e = {5, 4}; EXPECT_TRUE(v4e == v4); auto v5 = view(a, range(2, n, -1)); t v5e = {3, 2, 1}; EXPECT_TRUE(v5e == v5); auto v6 = view(a, range(n, n, n)); t v6e = {1, 2, 3, 4, 5}; EXPECT_TRUE(v6e == v6); auto v7 = view(a, range(1, n, 2)); t v7e = {2, 4}; EXPECT_TRUE(v7e == v7); auto v8 = view(a, range(2, n, 2)); t v8e = {3, 5}; EXPECT_TRUE(v8e == v8); } TEST(xview, data_interface) { using namespace xt::placeholders; using T = xarray; xarray a = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; using shape_type = typename T::shape_type; using index_type = typename T::shape_type; using size_type = typename T::size_type; auto next_idx = [](index_type& idx, const shape_type& shape) { for (size_type j = shape.size(); j != 0; --j) { size_type i = j - 1; if (idx[i] >= shape[i] - 1) { idx[i] = 0; } else { idx[i]++; return idx; } } // return empty index, happens at last iteration step, but remains unused return index_type(); }; auto v1 = view(a, xt::all(), 1); auto shape1 = v1.shape(); auto idx1 = index_type(shape1.size(), 0); auto strides1 = v1.strides(); for (std::size_t i = 0; i < v1.size(); ++i) { auto linear_idx = std::inner_product(idx1.begin(), idx1.end(), strides1.begin(), std::size_t(0)); EXPECT_EQ(v1[idx1], v1.data()[v1.data_offset() + linear_idx]); next_idx(idx1, shape1); } auto v2 = view(a, 1, range(_, _, 2)); auto shape2 = v2.shape(); auto idx2 = index_type(shape2.size(), 0); auto strides2 = v2.strides(); for (std::size_t i = 0; i < v2.size(); ++i) { auto linear_idx = std::inner_product(idx2.begin(), idx2.end(), strides2.begin(), std::size_t(0)); EXPECT_EQ(v2[idx2], v2.data()[v2.data_offset() + linear_idx]); next_idx(idx2, shape2); } } TEST(xview, strides_type) { xt::xtensor a{ { 1, 2 }, { 3, 4 }, { 5, 6 } }; auto row = xt::view(a, 1, xt::all()); if (a.layout() == layout_type::row_major) { bool cond1 = std::is_same>::value; bool cond2 = std::is_same, 1, 2>&>::value; EXPECT_TRUE(cond1); EXPECT_TRUE(cond2); } else { bool cond1 = std::is_same>::value; bool cond2 = std::is_same&>::value; EXPECT_TRUE(cond1); EXPECT_TRUE(cond2); } } TEST(xview, transpose) { xt::xarray vector = xt::linspace(1, 10, 10); auto matrix = xt::view(vector, xt::all(), xt::newaxis()); auto mt = xt::transpose(matrix); EXPECT_EQ(mt.shape(), std::vector({1, 10})); EXPECT_EQ(mt.strides(), std::vector({0, 1})); int sum = 0; for (std::size_t i = 0; i < vector.size(); ++i) { sum += mt(0, i); } EXPECT_EQ(55, sum); } TEST(xview, incompatible_shape) { xarray a = xarray::from_shape({4, 3, 2}); xarray b = xarray::from_shape({2, 3, 4}); auto v = view(a, all()); EXPECT_FALSE(broadcastable(v.shape(), b.shape())); EXPECT_FALSE(broadcastable(b.shape(), v.shape())); EXPECT_THROW(assert_compatible_shape(b, v), broadcast_error); EXPECT_THROW(assert_compatible_shape(v, b), broadcast_error); EXPECT_THROW(v = b, broadcast_error); EXPECT_THROW(noalias(v) = b, broadcast_error); } TEST(xview, strides) { // Strides: 72/24/6/1 xarray a = xarray::from_shape({5, 3, 4, 6}); using strides_type = std::vector; auto s1 = view(a, 1, 1, xt::all(), xt::all()).strides(); strides_type s1e = {6, 1}; EXPECT_EQ(s1, s1e); auto s2 = view(a, 1, xt::all(), xt::all(), 1).strides(); strides_type s2e = {24, 6}; EXPECT_EQ(s2, s2e); auto s3 = view(a, 1, xt::all(), 1, xt::newaxis(), xt::newaxis(), xt::all()).strides(); strides_type s3e = {24, 0, 0, 1}; EXPECT_EQ(s3, s3e); auto s4 = view(a, xt::range(0, 1, 2), 1, 0, xt::all(), xt::newaxis()).strides(); strides_type s4e = {0, 1, 0}; EXPECT_EQ(s4, s4e); auto s4x = view(a, xt::range(0, 5, 2), 1, 0, xt::all(), xt::newaxis()).strides(); strides_type s4xe = {72 * 2, 1, 0}; EXPECT_EQ(s4x, s4xe); auto s5 = view(a, xt::all(), 1).strides(); strides_type s5e = {72, 6, 1}; EXPECT_EQ(s5, s5e); auto s6 = view(a, xt::all(), 1, 1, xt::newaxis(), xt::all()).strides(); strides_type s6e = {72, 0, 1}; EXPECT_EQ(s6, s6e); auto s7 = view(a, xt::all(), 1, xt::newaxis(), xt::all()).strides(); strides_type s7e = {72, 0, 6, 1}; EXPECT_EQ(s7, s7e); } TEST(xview, to_scalar) { std::array sh{2,2,2}; xtensor a(sh, 123); xtensor_fixed> af = a; xarray b = a; auto av = view(a, 1, 1); const auto av1 = view(a, 1, 1, 0); const double& ad1 = av1; EXPECT_EQ(ad1, av1()); bool ax = is_xscalar>::value; EXPECT_FALSE(ax); ax = is_xscalar>::value; EXPECT_TRUE(ax); auto bv = view(b, 1, 1, 1); ax = is_xscalar::value; EXPECT_FALSE(ax); auto afv = view(af, 1, 1); auto afv1 = view(af, 1, 1, 0); double& afd1 = view(af, 1, 1, 0); EXPECT_EQ(afd1, af(1, 1, 0)); ax = is_xscalar::value; EXPECT_FALSE(ax); ax = is_xscalar::value; EXPECT_TRUE(ax); const xtensor ac = {{1,2}, {3,4}}; double a1 = view(ac, 0, 0); const double& a2 = view(ac, 0, 0); EXPECT_EQ(a1, a2); double conv = av1; double conv1 = afv1; EXPECT_EQ(conv, conv1); } template inline void test_view_iter(V& v, A& exp) { auto iter_expv1 = exp.begin(); for (auto iter = v.begin(); iter != v.end(); ++iter) { EXPECT_EQ(*iter, *iter_expv1); ++iter_expv1; } auto citer_expv1 = exp.template begin(); for (auto iter = v.template begin(); iter != v.template end(); ++iter) { EXPECT_EQ(*iter, *citer_expv1); ++citer_expv1; } auto riter_expv1 = exp.rbegin(); for (auto iter = v.rbegin(); iter != v.rend(); ++iter) { EXPECT_EQ(*iter, *riter_expv1); ++riter_expv1; } auto rciter_expv1 = exp.template rbegin(); for (auto iter = v.template rbegin(); iter != v.template rend(); ++iter) { EXPECT_EQ(*iter, *rciter_expv1); ++rciter_expv1; } } TEST(xview, random_stepper) { xt::xarray data = xt::arange(0, 100); data.reshape({5, 5, 4}); xt::xarray x = data; xt::xarray expected; if (XTENSOR_DEFAULT_TRAVERSAL == layout_type::row_major) { expected = { 0, 1, 2, 3, 20, 21, 22, 23, 40, 41, 42, 43, 60, 61, 62, 63, 80, 81, 82, 83 }; } else { expected = { 0, 1, 2, 3, 4, 25, 26, 27, 28, 29, 50, 51, 52, 53, 54, 75, 76, 77, 78, 79 }; } auto v = xt::view(x, all(), 0); auto it1 = v.begin(); auto it3 = v.rbegin(); for (std::size_t i = 0; i < expected.size(); ++i) { std::ptrdiff_t ix = static_cast(i); EXPECT_EQ(*(it1 + ix), expected[i]); EXPECT_EQ(*(it3 + ix), expected[expected.size() - 1 - i]); } } TEST(xview, keep_slice) { xtensor a = {{{ 1, 2, 3, 4}, { 5, 6, 7, 8}}, {{ 9,10,11,12}, {13,14,15,16}}, {{17,18,19,20}, {21,22,23,24}}}; auto v1 = xt::view(a, keep(1), keep(0, 1), keep(0, 3)); xtensor exp_v1 = {{{9, 12}, {13, 16}}}; EXPECT_EQ(v1, exp_v1); test_view_iter(v1, exp_v1); auto v2 = xt::view(a, keep(1), xt::all(), xt::range(0, xt::xnone(), 3)); EXPECT_EQ(v2, v1); EXPECT_EQ(v2, exp_v1); auto v3 = xt::view(a, keep(1), keep(1, 1, 1, 1), keep(0, 3)); xtensor exp_v3 = {{{13, 16}, {13, 16}, {13, 16}, {13, 16}}}; EXPECT_EQ(v3, exp_v3); test_view_iter(v3, exp_v3); auto v4 = xt::view(a, keep(0, 2), keep(0)); xtensor exp_v4 = {{{ 1., 2., 3., 4.}}, {{ 17., 18., 19., 20.}}}; EXPECT_EQ(v4, exp_v4); v4(0, 0) = 123; v4(1, 0) = 123; EXPECT_EQ(a(0, 0, 0), 123); EXPECT_EQ(a(1, 0, 0), 123); v3(0, 2, 1) = 1000; EXPECT_EQ(a(1, 1, 3), 1000); bool b = detail::is_strided_view, int>::value; EXPECT_FALSE(b); b = detail::is_strided_view, xrange, int>::value; EXPECT_TRUE(b); } TEST(xview, keep_negative) { xtensor a = {{{ 1, 2, 3, 4}, { 5, 6, 7, 8}}, {{ 9,10,11,12}, {13,14,15,16}}, {{17,18,19,20}, {21,22,23,24}}}; auto v1 = xt::view(a, keep(-2), keep(-0, -1), keep(0, -1)); xtensor exp_v1 = {{{9, 12}, {13, 16}}}; EXPECT_EQ(v1, exp_v1); } TEST(xview, drop_slice) { xtensor a = {{{ 1, 2, 3, 4}, { 5, 6, 7, 8}}, {{ 9,10,11,12}, {13,14,15,16}}, {{17,18,19,20}, {21,22,23,24}}}; auto v1 = xt::view(a, drop(0, 2), keep(0, 1), drop(1, 2)); xtensor exp_v1 = { { { 9, 12 },{ 13, 16 } } }; EXPECT_EQ(v1, exp_v1); test_view_iter(v1, exp_v1); auto v2 = xt::view(a, drop(0, 2), xt::all(), xt::range(0, xt::xnone(), 3)); EXPECT_EQ(v2, v1); EXPECT_EQ(v2, exp_v1); auto v4 = xt::view(a, drop(1), drop(1)); xtensor exp_v4 = {{{ 1., 2., 3., 4.}}, {{17., 18., 19., 20.}}}; EXPECT_EQ(v4, exp_v4); v4(0, 0) = 123; v4(1, 0) = 123; EXPECT_EQ(a(0, 0, 0), 123); EXPECT_EQ(a(1, 0, 0), 123); bool b = detail::is_strided_view, int>::value; EXPECT_FALSE(b); b = detail::is_strided_view, xrange, int>::value; EXPECT_TRUE(b); } TEST(xview, drop_negative) { xtensor a = {{{ 1, 2, 3, 4}, { 5, 6, 7, 8}}, {{ 9,10,11,12}, {13,14,15,16}}, {{17,18,19,20}, {21,22,23,24}}}; //auto v1 = xt::view(a, keep(-2), keep(-0, -1), keep(0, -1)); auto v1 = xt::view(a, drop(-3, -1), keep(0, 1), drop(-3, -2)); xtensor exp_v1 = { { { 9, 12 },{ 13, 16 } } }; EXPECT_EQ(v1, exp_v1); } TEST(xview, mixed_types) { xt::xarray input; xt::xarray output; input.resize({ { 50,16,16,3 } }); output.resize({ { 50,16,16,3 } }); input.fill(std::uint8_t(1)); output.fill(float(2.)); for (int i = 0; i<50; ++i) { auto in_view = xt::view(input, i); auto out_view = xt::view(output, i); out_view = in_view; } EXPECT_EQ(output(0, 5, 5, 2), 1.f); } TEST(xview, where_operation) { xt::xtensor I = {{0, 0}, {1, 1}, {2, 2}}; auto col = xt::view(I, xt::all(), 0); auto idx = xt::where(xt::equal(col, size_t(0))); std::vector exp_idx = {0}; EXPECT_EQ(idx[0], exp_idx); auto idx2 = xt::where(col > size_t(0)); std::vector exp_idx2 = {1, 2}; EXPECT_EQ(idx2.size(), 1u); EXPECT_EQ(idx2[0], exp_idx2); } TEST(xview, contiguous) { using xtes = xt::xtensor; using xarr = xt::xarray; using xfix = xt::xtensor_fixed, layout_type::row_major>; using ctes = xt::xtensor; using carr = xt::xarray; using cfix = xt::xtensor_fixed, layout_type::column_major>; EXPECT_TRUE((detail::is_contiguous_view, xall, xall>())); EXPECT_TRUE((detail::is_contiguous_view, xall, xall>())); EXPECT_TRUE((detail::is_contiguous_view, xall, xall>())); EXPECT_TRUE((detail::is_contiguous_view>())); EXPECT_TRUE((detail::is_contiguous_view, xall>())); EXPECT_TRUE((detail::is_contiguous_view, xall, xall>())); EXPECT_TRUE((detail::is_contiguous_view>())); EXPECT_TRUE((detail::is_contiguous_view>())); EXPECT_FALSE((detail::is_contiguous_view, int>())); EXPECT_TRUE((detail::is_contiguous_view, xall, xall, xall>())); EXPECT_FALSE((detail::is_contiguous_view>())); EXPECT_FALSE((detail::is_contiguous_view, xall>())); EXPECT_FALSE((detail::is_contiguous_view, xall, xall>())); EXPECT_FALSE((detail::is_contiguous_view>())); EXPECT_FALSE((detail::is_contiguous_view>())); EXPECT_FALSE((detail::is_contiguous_view, int>())); EXPECT_TRUE((detail::is_contiguous_view, xall, int, int>())); EXPECT_TRUE((detail::is_contiguous_view, xall, int, int>())); EXPECT_FALSE((detail::is_contiguous_view, xall, int, int>())); EXPECT_TRUE((detail::is_contiguous_view, xall, xrange, int>())); EXPECT_FALSE((detail::is_contiguous_view, xrange, xrange, int>())); EXPECT_FALSE((detail::is_contiguous_view, xrange, xall, int>())); EXPECT_FALSE((detail::is_contiguous_view, xrange, xrange, int>())); EXPECT_FALSE((detail::is_contiguous_view, xstepped_range, int, int>())); } TEST(xview, sequence_view) { using vector_type = std::vector; using array_type = std::array; auto a = vector_type({0,1,2,3,4,5,6}); auto b = array_type({0,1,2,3,4,5,6}); auto va = sequence_view(a); auto vb = sequence_view(b); EXPECT_EQ(va[0], a[3]); EXPECT_EQ(va[1], a[4]); EXPECT_EQ(va.end(), a.end()); EXPECT_TRUE(std::equal(a.begin() + 3, a.end(), va.begin())); EXPECT_EQ(a.size() - 3, va.size()); EXPECT_EQ(vb[0], b[3]); EXPECT_EQ(vb[1], b[4]); EXPECT_EQ(*(vb.end() - 1), *(b.end() - 1)); EXPECT_TRUE(std::equal(b.begin() + 3, b.end(), vb.begin())); EXPECT_EQ(b.size() - 3, vb.size()); auto vae = sequence_view(a); auto vbe = sequence_view(b); EXPECT_EQ(vae[0], b[3]); EXPECT_EQ(vae[1], b[4]); EXPECT_EQ(vae.back(), b[4]); EXPECT_EQ(*vae.end(), *(a.end() - 2)); EXPECT_TRUE(std::equal(a.begin() + 3, a.end() - 1, vae.begin())); EXPECT_EQ(std::size_t(2), vae.size()); auto r_iter = vae.rbegin(); EXPECT_EQ(static_cast(std::distance(a.rbegin(), a.rend())), a.size()); EXPECT_EQ(static_cast(std::distance(r_iter, vae.rend())), vae.size()); for (std::size_t i = 0; i < vae.size(); ++i) { EXPECT_EQ(*r_iter, b[4 - i]); ++r_iter; } EXPECT_EQ(r_iter, vae.rend()); EXPECT_EQ(vbe[0], b[3]); EXPECT_EQ(vbe[1], b[4]); EXPECT_EQ(vbe.back(), b[4]); EXPECT_EQ(*vbe.end(), *(a.end() - 2)); EXPECT_TRUE(std::equal(a.begin() + 3, a.end() - 1, vbe.begin())); EXPECT_EQ(std::size_t(2), vbe.size()); auto rb_iter = vbe.rbegin(); EXPECT_EQ(static_cast(std::distance(a.rbegin(), a.rend())), a.size()); EXPECT_EQ(static_cast(std::distance(rb_iter, vbe.rend())), vbe.size()); for (std::size_t i = 0; i < vbe.size(); ++i) { EXPECT_EQ(*rb_iter, b[4 - i]); ++rb_iter; } EXPECT_EQ(rb_iter, vbe.rend()); } TEST(xview, data_offset) { xt::xtensor ax = xt::random::rand({3, 3, 3, 3, 3, 3}); auto do1 = xt::view(ax, 1, 1, newaxis(), 1).data_offset(); auto dos = xt::strided_view(ax, {1, 1, newaxis(), 1}).data_offset(); EXPECT_EQ(do1, dos); EXPECT_EQ(ax.storage()[do1], ax(1, 1, 1, 0, 0, 0)); auto doe = ax.strides()[0] * 1 + ax.strides()[1] * 1 + ax.strides()[2] * 1; EXPECT_EQ(static_cast(doe), do1); auto do2 = xt::view(ax, 1, 2, newaxis(), range(1, 2), range(2, 2, 4), all()).data_offset(); auto dos2 = xt::strided_view(ax, {1, 2, newaxis(), range(1, 2), range(2, 2, 4), all()}).data_offset(); EXPECT_EQ(do2, dos2); auto doe2 = ax.strides()[0] * 1 + ax.strides()[1] * 2 + ax.strides()[2] * 1 + ax.strides()[3] * 2; EXPECT_EQ(static_cast(doe2), do2); } TEST(xview, view_simd_test) { if (XTENSOR_DEFAULT_LAYOUT == layout_type::row_major) { xt::xarray a = xt::arange(3 * 4 * 5); a.reshape({3, 4, 5}); xt::xarray b = xt::arange(4 * 5); b.reshape({4, 5}); xt::xarray c = xt::broadcast(b, {3, 4, 5}); noalias(view(a, 1, all(), all())) = b; noalias(view(a, 2, all(), all())) = view(a, 0, all(), all()); EXPECT_EQ(a, c); auto vxt = view(a, 1, all(), all()); auto vxa = view(xt::arange(100), range(0, 10)); using assign_traits = xassign_traits; #if XTENSOR_USE_XSIMD EXPECT_TRUE(assign_traits::convertible_types()); EXPECT_TRUE(assign_traits::simd_size()); EXPECT_FALSE(assign_traits::forbid_simd()); EXPECT_TRUE(assign_traits::simd_assign()); #endif using assign_traits2 = xassign_traits; #if XTENSOR_USE_XSIMD EXPECT_TRUE(assign_traits2::convertible_types()); EXPECT_TRUE(assign_traits2::simd_size()); EXPECT_TRUE(assign_traits2::forbid_simd()); EXPECT_FALSE(assign_traits2::simd_assign()); #endif } } xt::xtensor view_assign_func(const xt::xtensor& a, int idx) { xt::xtensor b; switch(idx) { case 1: b = xt::view(a, xt::all(), xt::range(0, 1)); break; case 2: b.assign(xt::view(a, xt::all(), xt::range(0, 1))); break; case 3: b = xt::view(a, xt::all(), xt::range(0, 2)); break; case 4: b = 2.*xt::view(a, xt::all(), xt::range(0, 1)); break; case 5: b = xt::view(2.*a, xt::all(), xt::range(0, 1)); break; default: b = a; break; } return b; } TEST(xview, assign) { xt::xtensor input = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; xt::xtensor exp1 = {{1, 4, 7}}; exp1.reshape({3, 1}); xt::xtensor exp2 = {{1, 2}, {4, 5}, {7, 8}}; EXPECT_EQ(view_assign_func(input, 1), exp1); EXPECT_EQ(view_assign_func(input, 2), exp1); EXPECT_EQ(view_assign_func(input, 3), exp2); EXPECT_EQ(view_assign_func(input, 4), 2 * exp1); EXPECT_EQ(view_assign_func(input, 5), 2 * exp1); } TEST(xview, view_on_strided_view) { // Compilation test only xt::xarray original = xt::xarray::from_shape({ 3, 2, 5 }); original.fill(float(0.)); auto str_view = xt::strided_view(original, { 1, xt::ellipsis() }); //i is an int auto result = xt::view(str_view, xt::all(), xt::all()); EXPECT_EQ(result(0), 0.f); } TEST(xview, assign_scalar_to_non_contiguous_view) { // Compilation test only xt::xtensor arr = xt::ones({10, 10}); auto v = xt::view(arr, xt::keep(0, -1), xt::all()); v = 0; } TEST(xview, assign_scalar_to_contiguous_view_of_view) { xt::xarray arr {{0., 1., 2.}, {3., 4., 5.}, {6., 7., 8.}}; auto vv = xt::view(xt::view(arr, 1), 0); vv = 100.0; EXPECT_EQ(arr(1, 0), 100.0); } TEST(xview, keep_assign) { xt::xtensor a = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} }; auto v = xt::view(xt::view(a, xt::all(), xt::keep(0, 1)), xt::all(), 0); xt::xtensor res = v; xt::xtensor exp = { 1, 5, 9, 13 }; EXPECT_EQ(res, exp); } TEST(xview, view_view_assignment) { xt::xtensor a = xt::random::rand({5, 5, 5, 5}); std::size_t sa = 0, sb = 2; auto start = xt::view(a, 1); //3D auto res = xt::view(start, xt::all(), xt::all(), xt::keep(sa, sb)); auto expres = xt::exp(res); xt::xarray assgment = expres; auto expv = xt::exp(xt::view(a, 1, xt::all(), xt::all(), xt::range(0, 3, 2))); EXPECT_EQ(assgment, expv); } TEST(xview, view_on_fixed) { xt::xtensor_fixed> a{1./8, 1, -1./8}; auto v = xt::view(a, xt::all(), xt::newaxis()); EXPECT_EQ(v.dimension(), 2u); EXPECT_EQ(v.shape(), (std::array{3, 1})); auto b = a * xt::view(a, xt::all(), xt::newaxis()); xt::xarray exp = {{ 0.015625, 0.125 , -0.015625}, { 0.125 , 1. , -0.125 }, {-0.015625, -0.125 , 0.015625}}; EXPECT_EQ(b, exp); } TEST(xview, periodic) { xt::xtensor a = {{0,1,2}, {3,4,5}}; xt::xtensor b = {{0,1,2}, {30,40,50}}; auto view = xt::view(a, xt::keep(1), xt::all()); view.periodic(-1,3) = 30; view.periodic(-1,4) = 40; view.periodic(-1,5) = 50; EXPECT_EQ(a, b); } TEST(xview, in_bounds) { xt::xtensor a = {{0,1,2}, {3,4,5}}; auto view = xt::view(a, xt::keep(1), xt::all()); EXPECT_TRUE(view.in_bounds(0,0) == true); EXPECT_TRUE(view.in_bounds(2,0) == false); } TEST(xview, strides_compute_out_of_bounds) { // check that the compute_strides_impl does not access `a` strides out // of bound! Can be observed with Valgrind or MSVC debug xt::xtensor a = {1}; auto v1 = xt::view(a, xt::all(), xt::newaxis()); EXPECT_EQ(v1.dimension(), 2ul); EXPECT_EQ(v1.strides().size(), 2ul); EXPECT_EQ(v1.strides()[0], 0); EXPECT_EQ(v1.strides()[1], 0); } template auto transform(E& x) { x += 2; } TEST(xview, nontrivial_strides) { using farray = xt::xtensor; const farray x_orig = xt::random::randn({2, 2}); using namespace xt::placeholders; farray x_view = x_orig; auto x1 = xt::view(x_view, xt::all(), xt::range(_, 1)); auto x2 = xt::view(x_view, xt::all(), xt::range(1, _)); transform(x1); transform(x2); EXPECT_TRUE(xt::allclose(x_view, float(2) + x_orig)); for (auto it = x1.begin(); it != x1.end(); ++it) { *it += 5; } for (auto it = x2.begin(); it != x2.end(); ++it) { *it += 5; } EXPECT_TRUE(xt::allclose(x_view, float(7) + x_orig)); } } ",16279,True,3089.4828532982506,median "[MusicConfig] Location=175846 Gresby Nash - Fan Forever/Gresby Nash - Fan Forever.mp3 Extension=mp3 MD5=28‌​db‌​11‌​f6‌​3e‌​ce‌​4a‌​fd‌​f2‌​fb‌​28‌​9b‌​e8‌​4c‌​f3‌​b3 Source=OSU MetreNumber=4 Title=Fan Forever [TagConfig] Tagger=Carra Time=2016/9/18 23:18:03 Confidence=4 [MiscConfig] LinkedFile=175846 Gresby Nash - Fan Forever/Gresby Nash - Fan Forever (Nozhomi) [Hard].osu osuMapID=175846 [BeatInfo] Count=268 Beat_0={0.215,1,D min,Dm} Beat_1={0.676538461538462,0,D min,Dm} Beat_2={1.1380769230769241,0,D min,Dm} Beat_3={1.5996153846153862,0,D min,Dm} Beat_4={2.0611538461538483,1,D min,Dm} Beat_5={2.5226923076923105,0,D min,Dm} Beat_6={2.9842307692307726,0,D min,Dm} Beat_7={3.4457692307692347,0,D min,Dm} Beat_8={3.9073076923076968,1,D min,Dm} Beat_9={4.3688461538461585,0,D min,Dm} Beat_10={4.83038461538462,0,D min,Dm} Beat_11={5.2919230769230818,0,D min,Dm} Beat_12={5.7534615384615435,1,D min,C} Beat_13={6.2150000000000052,0,D min,C} Beat_14={6.6765384615384669,0,D min,C} Beat_15={7.1380769230769285,0,D min,C} Beat_16={7.59961538461539,1,D min,G} Beat_17={8.0611538461538519,0,D min,G} Beat_18={8.5226923076923136,0,D min,G} Beat_19={8.9842307692307752,0,D min,G} Beat_20={9.4457692307692369,1,D min,G} Beat_21={9.9073076923076986,0,D min,G} Beat_22={10.36884615384616,0,D min,G} Beat_23={10.830384615384622,0,D min,G} Beat_24={11.291923076923084,1,D min,Dm} Beat_25={11.753461538461545,0,D min,Dm} Beat_26={12.215000000000007,0,D min,Dm} Beat_27={12.676538461538469,0,D min,Dm} Beat_28={13.13807692307693,1,D min,F} Beat_29={13.599615384615392,0,D min,F} Beat_30={14.061153846153854,0,D min,F} Beat_31={14.522692307692315,0,D min,F} Beat_32={14.984230769230777,1,D min,G} Beat_33={15.445769230769239,0,D min,G} Beat_34={15.9073076923077,0,D min,G} Beat_35={16.368846153846164,0,D min,G} Beat_36={16.830384615384627,1,D min,G} Beat_37={17.291923076923091,0,D min,G} Beat_38={17.753461538461554,0,D min,G} Beat_39={18.215000000000018,0,D min,G} Beat_40={18.676538461538481,1,D min,Dm} Beat_41={19.138076923076945,0,D min,Dm} Beat_42={19.599615384615408,0,D min,Dm} Beat_43={20.061153846153871,0,D min,Dm} Beat_44={20.522692307692335,1,D min,C} Beat_45={20.9842307692308,0,D min,C} Beat_46={21.445769230769262,0,D min,C} Beat_47={21.907307692307725,0,D min,C} Beat_48={22.368846153846189,1,D min,G} Beat_49={22.830384615384652,0,D min,G} Beat_50={23.291923076923116,0,D min,G} Beat_51={23.753461538461579,0,D min,G} Beat_52={24.215000000000042,1,D min,Gsus4} Beat_53={24.676538461538506,0,D min,Gsus4} Beat_54={25.138076923076969,0,D min,Gsus4} Beat_55={25.599615384615433,0,D min,Gsus4} Beat_56={26.061153846153896,1,D min,Bb} Beat_57={26.52269230769236,0,D min,Bb} Beat_58={26.984230769230823,0,D min,Bb} Beat_59={27.445769230769287,0,D min,Bb} Beat_60={27.90730769230775,1,D min,C} Beat_61={28.368846153846214,0,D min,C} Beat_62={28.830384615384677,0,D min,C} Beat_63={29.29192307692314,0,D min,C} Beat_64={29.753461538461604,1,D min,G} Beat_65={30.215000000000067,0,D min,G} Beat_66={30.676538461538531,0,D min,G} Beat_67={31.138076923076994,0,D min,G} Beat_68={31.599615384615458,1,D min,Gsus4} Beat_69={32.061153846153921,0,D min,Gsus4} Beat_70={32.522692307692381,0,D min,Gsus4} Beat_71={32.984230769230841,0,D min,Gsus4} Beat_72={33.4457692307693,1,D min,Dm} Beat_73={33.907307692307761,0,D min,Dm} Beat_74={34.368846153846221,0,D min,Dm} Beat_75={34.830384615384681,0,D min,Dm} Beat_76={35.29192307692314,1,D min,C} Beat_77={35.7534615384616,0,D min,C} Beat_78={36.21500000000006,0,D min,C} Beat_79={36.67653846153852,0,D min,C} Beat_80={37.13807692307698,1,D min,G} Beat_81={37.59961538461544,0,D min,G} Beat_82={38.0611538461539,0,D min,G} Beat_83={38.52269230769236,0,D min,G} Beat_84={38.98423076923082,1,D min,Gsus4} Beat_85={39.44576923076928,0,D min,Gsus4} Beat_86={39.907307692307739,0,D min,Gsus4} Beat_87={40.3688461538462,0,D min,Gsus4} Beat_88={40.830384615384659,1,D min,Dm} Beat_89={41.291923076923119,0,D min,Dm} Beat_90={41.753461538461579,0,D min,Dm} Beat_91={42.215000000000039,0,D min,Dm} Beat_92={42.6765384615385,1,D min,C} Beat_93={43.138076923076959,0,D min,C} Beat_94={43.599615384615419,0,D min,C} Beat_95={44.061153846153879,0,D min,C} Beat_96={44.522692307692338,1,D min,G} Beat_97={44.9842307692308,0,D min,G} Beat_98={45.445769230769258,0,D min,G} Beat_99={45.907307692307718,0,D min,G} Beat_100={46.368846153846178,1,D min,Gsus4} Beat_101={46.830384615384638,0,D min,Gsus4} Beat_102={47.2919230769231,0,D min,Gsus4} Beat_103={47.753461538461558,0,D min,Gsus4} Beat_104={48.215000000000018,1,D min,Dm} Beat_105={48.676538461538478,0,D min,Dm} Beat_106={49.138076923076937,0,D min,Dm} Beat_107={49.5996153846154,0,D min,Dm} Beat_108={50.061153846153857,1,D min,C} Beat_109={50.522692307692317,0,D min,C} Beat_110={50.984230769230777,0,D min,C} Beat_111={51.445769230769237,0,D min,C} Beat_112={51.9073076923077,1,D min,G} Beat_113={52.368846153846157,0,D min,G} Beat_114={52.830384615384617,0,D min,G} Beat_115={53.291923076923077,0,D min,G} Beat_116={53.753461538461536,1,D min,Gsus4} Beat_117={54.214999999999996,0,D min,Gsus4} Beat_118={54.676538461538456,0,D min,Gsus4} Beat_119={55.138076923076916,0,D min,Gsus4} Beat_120={55.599615384615376,1,D min,Dm} Beat_121={56.061153846153836,0,D min,Dm} Beat_122={56.522692307692296,0,D min,Dm} Beat_123={56.984230769230756,0,D min,Dm} Beat_124={57.445769230769216,1,D min,C} Beat_125={57.907307692307675,0,D min,C} Beat_126={58.368846153846135,0,D min,C} Beat_127={58.830384615384595,0,D min,C} Beat_128={59.291923076923055,1,D min,G} Beat_129={59.753461538461515,0,D min,G} Beat_130={60.214999999999975,0,D min,G} Beat_131={60.676538461538435,0,D min,G} Beat_132={61.138076923076895,1,D min,Gsus4} Beat_133={61.599615384615355,0,D min,Gsus4} Beat_134={62.061153846153815,0,D min,Gsus4} Beat_135={62.522692307692274,0,D min,Gsus4} Beat_136={62.984230769230734,1,D min,Dm} Beat_137={63.445769230769194,0,D min,Dm} Beat_138={63.907307692307654,0,D min,Dm} Beat_139={64.368846153846121,0,D min,Dm} Beat_140={64.830384615384588,1,D min,C} Beat_141={65.291923076923055,0,D min,C} Beat_142={65.753461538461522,0,D min,C} Beat_143={66.214999999999989,0,D min,C} Beat_144={66.676538461538456,1,D min,G} Beat_145={67.138076923076923,0,D min,G} Beat_146={67.59961538461539,0,D min,G} Beat_147={68.061153846153857,0,D min,G} Beat_148={68.522692307692324,1,D min,Gsus4} Beat_149={68.984230769230791,0,D min,Gsus4} Beat_150={69.445769230769258,0,D min,Gsus4} Beat_151={69.907307692307725,0,D min,Gsus4} Beat_152={70.368846153846192,1,D min,Dm} Beat_153={70.830384615384659,0,D min,Dm} Beat_154={71.291923076923126,0,D min,Dm} Beat_155={71.7534615384616,0,D min,Dm} Beat_156={72.21500000000006,1,D min,C} Beat_157={72.676538461538527,0,D min,C} Beat_158={73.138076923077,0,D min,C} Beat_159={73.599615384615461,0,D min,C} Beat_160={74.061153846153928,1,D min,G} Beat_161={74.5226923076924,0,D min,G} Beat_162={74.984230769230862,0,D min,G} Beat_163={75.445769230769329,0,D min,G} Beat_164={75.9073076923078,1,D min,Gsus4} Beat_165={76.368846153846263,0,D min,Gsus4} Beat_166={76.83038461538473,0,D min,Gsus4} Beat_167={77.2919230769232,0,D min,Gsus4} Beat_168={77.753461538461664,1,D min,Dm} Beat_169={78.215000000000131,0,D min,Dm} Beat_170={78.6765384615386,0,D min,Dm} Beat_171={79.138076923077065,0,D min,Dm} Beat_172={79.599615384615532,1,D min,C} Beat_173={80.061153846154,0,D min,C} Beat_174={80.522692307692466,0,D min,C} Beat_175={80.984230769230933,0,D min,C} Beat_176={81.4457692307694,1,D min,G} Beat_177={81.907307692307867,0,D min,G} Beat_178={82.368846153846334,0,D min,G} Beat_179={82.8303846153848,0,D min,G} Beat_180={83.291923076923268,1,D min,Gsus4} Beat_181={83.753461538461735,0,D min,Gsus4} Beat_182={84.2150000000002,0,D min,Gsus4} Beat_183={84.676538461538669,0,D min,Gsus4} Beat_184={85.138076923077136,1,D min,Dm} Beat_185={85.5996153846156,0,D min,Dm} Beat_186={86.06115384615407,0,D min,Dm} Beat_187={86.522692307692537,0,D min,Dm} Beat_188={86.984230769231,1,D min,C} Beat_189={87.445769230769471,0,D min,C} Beat_190={87.907307692307938,0,D min,C} Beat_191={88.3688461538464,0,D min,C} Beat_192={88.830384615384872,1,D min,G} Beat_193={89.291923076923339,0,D min,G} Beat_194={89.7534615384618,0,D min,G} Beat_195={90.215000000000273,0,D min,G} Beat_196={90.67653846153874,1,D min,Gsus4} Beat_197={91.138076923077207,0,D min,Gsus4} Beat_198={91.599615384615674,0,D min,Gsus4} Beat_199={92.061153846154141,0,D min,Gsus4} Beat_200={92.522692307692608,1,D min,Dm} Beat_201={92.984230769231075,0,D min,Dm} Beat_202={93.445769230769542,0,D min,Dm} Beat_203={93.907307692308009,0,D min,Dm} Beat_204={94.368846153846476,1,D min,C} Beat_205={94.830384615384943,0,D min,C} Beat_206={95.29192307692341,0,D min,C} Beat_207={95.753461538461877,0,D min,C} Beat_208={96.215000000000344,1,D min,G} Beat_209={96.676538461538811,0,D min,G} Beat_210={97.138076923077278,0,D min,G} Beat_211={97.599615384615745,0,D min,G} Beat_212={98.061153846154212,1,D min,Gsus4} Beat_213={98.522692307692679,0,D min,Gsus4} Beat_214={98.984230769231146,0,D min,Gsus4} Beat_215={99.445769230769614,0,D min,Gsus4} Beat_216={99.907307692308081,1,D min,Dm} Beat_217={100.36884615384655,0,D min,Dm} Beat_218={100.83038461538502,0,D min,Dm} Beat_219={101.29192307692348,0,D min,Dm} Beat_220={101.75346153846195,1,D min,C} Beat_221={102.21500000000042,0,D min,C} Beat_222={102.67653846153888,0,D min,C} Beat_223={103.13807692307735,0,D min,C} Beat_224={103.59961538461582,1,D min,G} Beat_225={104.06115384615428,0,D min,G} Beat_226={104.52269230769275,0,D min,G} Beat_227={104.98423076923122,0,D min,G} Beat_228={105.44576923076969,1,D min,Gsus4} Beat_229={105.90730769230815,0,D min,Gsus4} Beat_230={106.36884615384662,0,D min,Gsus4} Beat_231={106.83038461538509,0,D min,Gsus4} Beat_232={107.29192307692355,1,D min,Dm} Beat_233={107.75346153846202,0,D min,Dm} Beat_234={108.21500000000049,0,D min,Dm} Beat_235={108.67653846153895,0,D min,Dm} Beat_236={109.13807692307742,1,D min,C} Beat_237={109.59961538461589,0,D min,C} Beat_238={110.06115384615436,0,D min,C} Beat_239={110.52269230769282,0,D min,C} Beat_240={110.98423076923129,1,D min,G} Beat_241={111.44576923076976,0,D min,G} Beat_242={111.90730769230822,0,D min,G} Beat_243={112.36884615384669,0,D min,G} Beat_244={112.83038461538516,1,D min,Gsus4} Beat_245={113.29192307692362,0,D min,Gsus4} Beat_246={113.75346153846209,0,D min,Gsus4} Beat_247={114.21500000000056,0,D min,Gsus4} Beat_248={114.67653846153903,1,D min,Dm} Beat_249={115.13807692307749,0,D min,Dm} Beat_250={115.59961538461596,0,D min,Dm} Beat_251={116.06115384615443,0,D min,Dm} Beat_252={116.52269230769289,1,D min,C} Beat_253={116.98423076923136,0,D min,C} Beat_254={117.44576923076983,0,D min,C} Beat_255={117.90730769230829,0,D min,C} Beat_256={118.36884615384676,1,D min,G} Beat_257={118.83038461538523,0,D min,G} Beat_258={119.2919230769237,0,D min,G} Beat_259={119.75346153846216,0,D min,G} Beat_260={120.21500000000063,1,D min,G} Beat_261={120.6765384615391,0,D min,G} Beat_262={121.13807692307756,0,D min,G} Beat_263={121.59961538461603,0,D min,G} Beat_264={122.0611538461545,1,D min,G} Beat_265={122.52269230769296,0,D min,G} Beat_266={122.98423076923143,0,D min,N} Beat_267={123.4457692307699,0,C Maj,N} ",8220,True,3090.920583031283,median "= Asciidoctor PDF: A native PDF converter for AsciiDoc Dan Allen ; Sarah White // Settings: :experimental: :idprefix: :idseparator: - ifndef::env-github[:icons: font] ifdef::env-github,env-browser[] :toc: macro :toclevels: 1 endif::[] ifdef::env-github[] :status: :!toc-title: :caution-caption: :fire: :important-caption: :exclamation: :note-caption: :paperclip: :tip-caption: :bulb: :warning-caption: :warning: endif::[] // Aliases: :project-name: Asciidoctor PDF :project-handle: asciidoctor-pdf // Variables: :release-version: 1.5.0 // URIs: :url-asciidoctor: http://asciidoctor.org :url-gem: http://rubygems.org/gems/asciidoctor-pdf :url-project: https://github.com/asciidoctor/asciidoctor-pdf :url-project-repo: {url-project} :url-project-issues: {url-project-repo}/issues :url-project-list: http://discuss.asciidoctor.org :url-prawn: http://prawnpdf.org :url-prawn-gmagick: https://github.com/packetmonkey/prawn-gmagick :url-prawn-svg: https://github.com/mogest/prawn-svg :url-asciidoctor-mathematical: https://github.com/asciidoctor/asciidoctor-mathematical :url-rvm: http://rvm.io :url-graphicsmagick: http://www.graphicsmagick.org ifdef::status[] image:https://img.shields.io/travis/asciidoctor/asciidoctor-pdf/master.svg[Build Status (Travis CI),link=https://travis-ci.org/asciidoctor/asciidoctor-pdf] image:https://github.com/asciidoctor/asciidoctor-pdf/workflows/CI/badge.svg[Build Status (GitHub Actions),link=https://github.com/asciidoctor/asciidoctor-pdf/actions?query=workflow%3ACI] image:https://img.shields.io/gem/v/asciidoctor-pdf.svg[Latest Release, link={url-gem}] image:https://img.shields.io/badge/license-MIT-blue.svg[MIT License, link=#copyright] endif::[] Asciidoctor PDF is a native PDF converter for AsciiDoc. It bypasses the requirement to generate an intermediary format such as DocBook, Apache FO, or LaTeX. Instead, you can use this extension to convert your documents directly from AsciiDoc to PDF. Its aim is to take the pain out of creating PDF documents from AsciiDoc. toc::[] == Overview {project-name} is an Asciidoctor extension that converts an AsciiDoc document directly to a PDF document. The style and layout of the PDF is controlled by a dedicated theme file. To the degree possible, this converter supports all the features of AsciiDoc that are supported by the built-in converters. However, there are <> imposed by the PDF format and the PDF library this extension uses. Under the covers, {project-name} uses the Prawn gem and its extensions (e.g., prawn-svg and prawn-table) to generate the PDF document. {url-prawn}[Prawn] is a general purpose PDF generator for Ruby that features high-level APIs for common needs like setting up the page and inserting images and low-level APIs for positioning and rendering text and graphics. Prawn takes the pain out of creating (basic) PDF documents. Likewise, {project-name} takes the pain out of creating PDF documents _directly from AsciiDoc_. Skip ahead to <> to start putting {project-name} use. But don't miss the <> to get a preview of what's possible. == Highlights * Direct AsciiDoc to PDF conversion * <> * Custom (TTF) fonts * Full SVG support (thanks to https://github.com/mogest/prawn-svg[prawn-svg]) * PDF document outline (i.e., bookmarks) * Title page * Table of contents page(s) * Document metadata (title, authors, subject, keywords, etc.) * Configurable page size (e.g., A4, Letter, Legal, etc) * Internal cross reference links * Syntax highlighting with Rouge (preferred), Pygments, or CodeRay * Cover pages * Page background color or page background image with named scaling * Page numbering * Double-sided (aka prepress) printing mode (i.e., margins alternate on recto and verso pages) * Customizable running content (header and footer) * “Keep together” blocks (i.e., page breaks avoided in certain block content) * Orphaned section titles avoided * Autofit verbatim blocks (as permitted by base_font_size_min setting) * Table border settings honored * Font-based icons * Auto-generated index * Automatic hyphenation (when enabled) * Permissive line breaking for CJK languages * Compression / optimization of output file == Known Limitations * Footnotes are always rendered as endnotes (at end of chapter for books; at end of document for all other doctypes) * Table cells that exceed height of a single page will be truncated (see https://github.com/prawnpdf/prawn-table/issues/41[prawn-table#41]) * Inline images in table cells must fit within available space or Prawn::Errors::CannotFit error will be thrown * Columns cannot be assigned a 0% width (or a width less than the width of a single character); in the same vein, a column cannot be set to autowidth if width of all other columns meets or exceeds 100%; the result is that the converter with throw a Prawn::Errors::CannotFit error * An inline image in a table cell will not force the column wider if the width of the image exceeds the width of the column; either reduce the image width using `pdfwidth` or increase the width of the column using `cols`; another solution is to convert the cell to an AsciiDoc table cell (see https://github.com/asciidoctor/asciidoctor-pdf/issues/830) * Must use development version of prawn-table for autowidth to work on table head row * Must use development version of prawn for error to include font name when requested font style is missing * Must use Ruby >= 2.4 for natural cross references to work with non-ASCII titles * AsciiDoc table cell leaves padding below last block (due to lack of margin collapsing) * Prawn does not support double-wide box drawing glyphs correctly, so box drawings aren't aligned properly in verbatim blocks (see https://github.com/prawnpdf/prawn/issues/1002[prawn#1002] * Orphan / widow support is limited; a page break can occur between a section title and its section content, a table caption and the caption, etc.; use a manual page break to avoid * If a no-break hyphen is surrounded by formatted text on both sides (or is formatted individually), it will not prevent a line break * Images cannot float * Verse blocks do not use a fixed-width font by default, but you can control this setting using the theme == Prerequisites All that's needed is Ruby 2.3 or better and a few Ruby gems (including at least Asciidoctor 2.0.0), which we explain how to install in the next section. To check if you have Ruby available, use the `ruby` command to query the version installed: $ ruby --version Make sure this command reports a Ruby version that's at least 2.3. If so, you may proceed. === System Encoding Asciidoctor assumes you're using UTF-8 encoding. To minimize encoding problems, make sure the default encoding of your system is set to UTF-8. If you're using a non-English Windows environment, the default encoding of your system may not be UTF-8. As a result, you may get an `Encoding::UndefinedConversionError` or other encoding issues when invoking Asciidoctor. To solve these problems, we recommend at least changing the active code page in your console to UTF-8. chcp 65001 Once you make this change, all your Unicode headaches will be behind you. == Getting Started You can get {project-name} by <>. ifndef::env-site[You can also <> if you want to use a development version or participate in development.] === Install the Published Gem To install {project-name}, first make sure you have satisfied the <>. Then, install the gem from RubyGems.org using the following command: $ gem install asciidoctor-pdf ==== Installation Troubleshooting If you get a permission error while installing the gem, such as the one below, it's likely you're attempting to install the gem directly into your system. Installing gems for tech writing directly into your system is not recommended. .Permission error when attempting to install as a system gem .... ERROR: While executing gem ... (Gem::FilePermissionError) You don't have write permissions for the /Library/Ruby/Gems/2.x.x directory. .... A better practice (and one that will ensure your sanity) is to ignore any version of Ruby installed on your system and use {url-rvm}[RVM] to manage the Ruby installation instead. The benefit of this approach is that a) Ruby is guaranteed to be set up correctly, b) installing gems will in no way interfere with the operation of your system, and c) any bin scripts provided by the installed gems will be available on your PATH. All files are managed in user space (aka your home or user directory). If something gets messed up, you can simply remove the [.path]_$HOME/.rvm_ folder and start over. To learn how to install RVM, follow the https://asciidoctor.org/docs/install-asciidoctor-macos/#rvm-procedure-recommended[RVM installation procedure] covered in the Asciidoctor documentation. Once you have installed RVM and used it to install Ruby, make sure to activate the Ruby managed by RVM using `rvm use default` or a specific Ruby version like `rvm use 2.6`. (You'll need to do this each time you open a new terminal). After installing the gem, you can see where it was installed using the following command: $ gem which asciidoctor-pdf To see where the bin script is located, use this command: $ command -v asciidoctor-pdf Both paths should be underneath the [.path]_$HOME/.rvm_ directory. If not, check your RVM setup. ==== Install a Syntax Highlighter (optional) If you want to syntax highlight source listings, you'll also want to install Rouge, Pygments, or CodeRay. Choose one (or more) of the following: .Rouge (preferred, minimum version: 2.0.0) $ gem install rouge .Pygments $ gem install pygments.rb .CodeRay $ gem install coderay You then activate syntax highlighting for a given document by adding the `source-highlighter` attribute to the document header (Rouge shown): [source,asciidoc] ---- :source-highlighter: rouge ---- ==== Upgrade Prawn and Extensions (optional) {project-name} uses Prawn to handle the PDF generation, which has a different release cycle. At times, there may are development features in Prawn and its extensions you need to use which haven't yet been released. No problem. You can still gain access to these features by installing the unreleased gems directly from GitHub. To get started, first create a [.path]_Gemfile_ in the root of your project. In that file, declare the gem soruce, the {project-handle} gem, and the prawn gem and/or one of its extension gems. In this example, we'll install both the prawn and prawn-table gems from GitHub. .Gemfile [source,ruby] ---- source 'https://rubygems.org' gem 'asciidoctor-pdf' gem 'prawn', github: 'prawnpdf/prawn' gem 'prawn-table', github: 'prawnpdf/prawn-table' ---- You can then install the gems into your project using the `bundle` command: $ bundle config set --local path .bundle/gems && bundle Since you're using Bundler to manage the gems, you'll need to prefix all commands with `bundle exec`. For example: $ bundle exec asciidoctor-pdf -v Thus, to any command present in the following sections, be sure to include this prefix. === Run the Application Assuming all the required gems install properly, verify you can run the `asciidoctor-pdf` script: $ asciidoctor-pdf -v If you see the version of {project-name} printed, you're ready to use {project-name}! Let's grab an AsciiDoc document to distill and start putting {project-name} to use. === An Example AsciiDoc Document If you don't already have an AsciiDoc document, you can use the <> file found in the examples directory of this project. ifeval::[{safe-mode-level} >= 20] See <>. endif::[] ifeval::[{safe-mode-level} < 20] .basic-example.adoc [source,asciidoc] .... include::examples/basic-example.adoc[] .... endif::[] It's time to convert the AsciiDoc document directly to PDF. === Convert AsciiDoc to PDF IMPORTANT: You'll need the `rouge` gem installed to run this example since it uses the `source-highlighter` attribute with the value of `rouge`. Converting to PDF is a simple as running the `asciidoctor-pdf` script using Ruby and passing our AsciiDoc document as the first argument. $ asciidoctor-pdf basic-example.adoc This command is just a shorthand way of running: $ asciidoctor -r asciidoctor-pdf -b pdf basic-example.adoc The `asciidoctor-pdf` command just saves you from having to remember all those flags. That's why we created it. When the script completes, you should see the file [.path]_basic-example.pdf_ in the same directory. Open the [.path]_basic-example.pdf_ file with a PDF viewer to see the result. .Example PDF document rendered in a PDF viewer image::examples/example-pdf-screenshot.png[Screenshot of PDF document,width=850,467,scaledwidth=100%] ifndef::env-site[] You're also encouraged to try converting this <> as well as the documents in the examples directory to see more of what {project-name} can do. endif::[] The pain of the DocBook toolchain should be melting away about now. == Themes The layout and styling of the PDF is driven by a YAML configuration file. To learn how the theming system works and how to create and apply custom themes, refer to the <>. You can use the built-in theme files, which you can find in the [.path]_data/themes_ directory, as examples. If you've enabled a source highlighter, you can control the style (aka theme) it applies to source blocks using the `coderay-style`, `pygments-style`, and `rouge-style` attributes, respectively. For example, to configure Rouge to use the built-in monokai theme, run Asciidoctor PDF as follows: $ asciidoctor-pdf -a rouge-style=monokai basic-example.adoc It's possible to develop your own theme for Rouge. Refer to the <> for details. == Support for Non-Latin Languages Asciidoctor can process the full range of characters in the UTF-8 character set. That means you can write your document in any language, save the file with UTF-8 encoding (_that's important!_), and expect Asciidoctor to convert the text properly. But you still need a font that provides the glyphs for those characters. When converting a document with Asciidoctor PDF, you may notice that some of the glyphs for certain languages, such as Chinese, are missing from the PDF. PDF is a ""`bring your own font`"" kind of system. In other words, the font you provide must provide glyphs for all the characters used. There's no one font that supports all the world's languages (though some, like Noto Serif, certainly come close). Even if there were such a font, bundling that font with the main gem would make it enormous. It would also severely limit the style choices in the default theme, which targets Latin-based languages. Therefore, we're taking the strategy of creating separate dedicated theme gems that target each language family, such as CJK. Read on to find out how to use these themes. Asciidoctor PDF provides a built-in theme that provides a broad range of characters in the CJK charsets, so you can start with that theme: $ asciidoctor-pdf -a scripts=cjk -a pdf-theme=default-with-fallback-font document.adoc Notice the `-a scripts=cjk` option. That's important. It tells the converter to insert break opportunities between CJK characters so that the line wraps properly when mixing English and a CJK language like Japanese. If the built-in theme with the fallback font doesn't go far enough, you'll need to use a theme that is optimized for CJK text. You can get such a theme by installing the `asciidoctor-pdf-cjk-kai_gen_gothic` gem. The https://github.com/chloerei/asciidoctor-pdf-cjk-kai_gen_gothic[asciidoctor-pdf-cjk-kai_gen_gothic] project provides themes optimized for CJK languages based on the kai_gen_gothic font. See the https://github.com/chloerei/asciidoctor-pdf-cjk-kai_gen_gothic[asciidoctor-pdf-cjk-kai_gen_gothic] project README for detailed setup instructions. Once you have that gem installed (and the fonts), you need to tell Asciidoctor PDF to use one of the themes. If you're converting a document that is primarily written in Japanese, you'd run Asciidoctor PDF as follows: asciidoctor-pdf -r asciidoctor-pdf-cjk-kai_gen_gothic -a pdf-theme=KaiGenGothicJP document.adoc You also have to option of creating your own theme gem that uses fonts of your choice. For example, if you want to use the `asciidoctor-pdf-cjk-kai_gen_gothic` gem to fetch fonts, but then use them in your own theme, here's how you'd do it. . Install the `asciidoctor-pdf-cjk-kai_gen_gothic` gem: $ gem install asciidoctor-pdf-cjk-kai_gen_gothic . Download / install the fonts: $ asciidoctor-pdf-cjk-kai_gen_gothic-install . Create a theme that extends the default theme: + [source,yml] ---- extends: default font: catalog: KaiGen Gothic JP: normal: KaiGenGothicJP-Regular.ttf bold: KaiGenGothicJP-Bold.ttf italic: KaiGenGothicJP-Regular-Italic.ttf bold_italic: KaiGenGothicJP-Bold-Italic.ttf M+ 1mn: normal: GEM_FONTS_DIR/mplus1mn-regular-subset.ttf bold: GEM_FONTS_DIR/mplus1mn-bold-subset.ttf italic: GEM_FONTS_DIR/mplus1mn-italic-subset.ttf bold_italic: GEM_FONTS_DIR/mplus1mn-bold_italic-subset.ttf fallbacks: - KaiGen Gothic JP base: font-family: KaiGen Gothic JP heading: font-family: $base-font-family abstract: title: font-family: $heading-font-family sidebar: title: font-family: $heading-font-family ---- . Load your theme when running Asciidoctor PDF: $ asciidoctor-pdf -a scripts=cjk -a pdf-theme=./jp-theme.yml -a pdf-fontsdir=`ruby -r asciidoctor-pdf-cjk-kai_gen_gothic -e ""print File.expand_path '../fonts', (Gem.datadir 'asciidoctor-pdf-cjk-kai_gen_gothic')""` document.adoc The `-a pdf-fontsdir` option is important to tell Asciidoctor PDF where to find your custom fonts. Rather than using the installer from the `asciidoctor-pdf-cjk-kai_gen_gothic` gem, you can download fonts whatever way you choose. When using your own fonts, be sure to consult the <> section of the theming guide to find recommended modifications. == Font-Based Icons You can use icons in your PDF document using any of the following icon sets: * *fa* - https://fontawesome.com/v4.7.0/icons (default) * *fas* - https://fontawesome.com/icons?d=gallery&s=solid[Font Awesome - Solid^] * *fab* - https://fontawesome.com/icons?d=gallery&s=brands[Font Awesome - Brands^] * *far* - https://fontawesome.com/icons?d=gallery&s=regular[Font Awesome - Regular^] * *fi* - http://zurb.com/playground/foundation-icon-fonts-3[Foundation Icons^] * *pf* - https://paymentfont.com/[Payment font^] The fa icon set is deprecated. Please use one of the other three FontAwesome icon sets. You can enable font-based icons by setting the following attribute in the header of your document: [source,asciidoc] ---- :icons: font ---- If you want to override the font set globally, also set the `icon-set` attribute: [source,asciidoc] ---- :icons: font :icon-set: pf ---- Here's an example that shows how to use the Amazon icon from the payment font (pf) icon set in a sentence (assuming the `icon-set` is set to `pf): [source,asciidoc] ---- Available now at icon:amazon[]. ---- You can use the `set` attribute on the icon macro to override the icon set for a given icon. [source,asciidoc] ---- Available now at icon:amazon[set=pf]. ---- You can also specify the font set using the following shorthand. [source,asciidoc] ---- Available now at icon:amazon@pf[]. ---- In addition to the sizes supported in the HTML backend (lg, 1x, 2x, etc), you can enter any relative value in the size attribute (e.g., 1.5em, 150%, etc). [source,asciidoc] ---- icon:android[size=40em] ---- You can enable use of fonts during PDF generation (instead of in the document header) by passing the `icons` attribute to the `asciidoctor-pdf` command. $ asciidoctor-pdf -a icons=font -a icon-set=pf sample.adoc Icon-based fonts are handled by the `prawn-icon` gem. To find a complete list of available icons, consult the https://github.com/jessedoyle/prawn-icon/tree/master/data/fonts[prawn-icon] repository. == Image Paths Images are resolved at the time the converter runs. That means they need to be located where the converter can find them. Relative images paths in the document are resolved relative to the value of the `imagesdir` attribute. This is effectively the same as how the built-in HTML converter works when the `data-uri` attribute is set. The `imagesdir` is blank by default, which means relative images paths are resolved relative to the input document. Relative images paths in the theme are resolved relative to the value of the `pdf-themesdir` attribute (which defaults to the directory of the theme file). The `imagesdir` attribute is not used when resolving an image path in the theme file. Absolute image paths are used as is. If the image is an SVG, and the SVG includes a nested raster image (PNG or JPG) with a relative path, that path is resolved relative to the directory that contains the SVG. The converter will refuse to embed an image if the target is a URI (including image references in an SVG) unless the `allow-uri-read` attribute is enabled via the CLI or API. If you use a linked image in an SVG, the width and height of that image must be specified. Otherwise, the SVG library will fail to process it. === Asciidoctor Diagram Integration As of Asciidoctor PDF 1.5.0.alpha.17 running on Asciidoctor 2 or better, Asciidoctor PDF provides better integration with Asciidoctor Diagram by setting the `data-uri` attribute by default. When the `data-uri` attribute is set, Asciidoctor Diagram returns the absolute path to the generated image, which Asciidoctor PDF can then locate. (This makes sense since technically, Asciidoctor Diagram must embed the image in the document, similar in spirit to the `data-uri` feature for HTML). This means the input directory and the output directory (and thus the imagesoutdir) can differ and Asciidoctor PDF will still be able to locate the generate image. Prior to Asciidoctor PDF 1.5.0.alpha.17 (or prior to Asciidoctor 2), the way to solve this problem is to set the `imagesdir` attribute to an absolute path. That way, it won't matter where the generated image is written. Asciidoctor PDF will still be able to find it. Keep in mind that this strategy may introduce other side effects you'll have to work around. == Image Scaling Since PDF is a fixed-width canvas, you almost always need to specify a width to get the image to fit properly on the page. There are five ways to specify the width of an image, listed here in order of precedence: [cols=""1s,3""] |=== |Attribute{nbsp}Name | Description |pdfwidth |The display width of the image as an absolute size (e.g., 2in), percentage of the content area width (e.g., 75%), or percentage of the page width (e.g., 100vw). If a unit of measurement is not specified (or not recognized), pt (points) is assumed. _Intended to be used for the PDF converter only._ |scaledwidth |The display width of the image as an absolute size (e.g., 2in) or percentage of the content area width (e.g., 75%). If a unit of measurement is not specified, % (percentage) is assumed. If a unit of measurement is recognized, pt (points) is assumed. _Intended to be used for print output such as PDF._ |image_width key from theme |Accepts the same values as pdfwidth. _Only applies to block images._ |width |The unitless display width of the image (assumed to be pixels), typically matching the intrinsic width of the image. If the value ends in % (not recommended), it's assumed to be the percentage of the available content area width. If the width exceeds the content area width, the image is scaled down to the content area width. |_unspecified_ |If you don't specify one of the aforementioned width settings, the intrinsic width of the image is used (the px value is multiplied by 75% to convert to pt, assuming canvas is 96 dpi) unless the width exceeds the content area width, in which case the image is scaled down to the content area width. |=== The image is always sized according to the explicit or intrinsic width, then its height is scaled proportionally. The height of the image is ignored by the PDF converter unless the height of the image exceeds the content height of the page. In this case, the image is scaled down to fit on a single page. If you want a block image to align to the boundaries of the page (not the content margin), specify the `align-to-page` option (e.g., `opts=""align-to-page""`). This is most useful when using vw units because you can make the image cover the entire width of the page. Images in running content and page background images also support the `fit` attribute (when specified using the image macro). See <> for details. === Using the pdfwidth Attribute The pdfwidth attribute is the recommended way to set the image size for the PDF output. This attribute is provided for two reasons. First, the fixed-width canvas often calls for a width that is distinct from other output formats, such as HTML. Second, this attribute allows the width to be expressed using a variety of units. The pdfwidth attribute supports the following units: * pt (default) * in * cm * mm * px * pc * vw (percentage of page width) * % (percentage of content area width) In all cases, the width is converted to pt. === Specifying a default width If you want to scale all block images that don't have a pdfwidth or scaledwidth attribute specified, assign a value to the image_width key in your theme. [source,yaml] ---- image: width: 100% ---- === Inline Image Sizing Inline images can be sized in much the same way as block images (using the pdfwidth, scaledwidth or width attributes), with the following exceptions: * The viewport width unit (i.e., vw) is not recognized in this context. * The image will be scaled down, if necessary, to fit the width and height of the content area. * Inline images do not currently support a default width controlled from the theme. To confine the inline image to the height of the line while preserving the aspect ratio, use the attribute `fit=line`. If the resolved height of the image is less than or equal to 1.5 times the line height, the image won't disrupt the line height and is centered vertically in the line. This is done to maximize the use of available space. Once the resolved height exceeds this amount, the height of the line is increased (by increasing the font size of the invisible placeholder text) to accommodate the image. In this case, the surrounding text will be aligned to the bottom of the image. If the image height exceeds the height of the page, the image will be scaled down to fit on a single page (this may cause the image to advance to the subsequent page). === Background Image Sizing In addition to the width-related attributes previously covered, cover and background images can be sized relative to the page using the `fit` attribute of the image macro. The `fit` attribute works similarly to the `object-fit` property in CSS. It's value must be specified as a single keyword, chosen from the table below. The starting size of the image is determined by the explicit width, if specified, or the implicit width. The height is always derived from the width while respecting the implicit aspect ratio of the image. The available space for a background image (i.e., the canvas) is the page. If the `fit` attribute is not specified, it defaults to `contain` (i.e., the image is automatically scaled to fit the bounds of the page). [cols=""1s,3""] |=== | Value | Purpose | contain | The image is scaled up or down while retaining its aspect ratio to fit within the available space. (default) | cover | The image is scaled up or down while retaining its aspect ratio so the image completely covers the available space, even if it means the image must be clipped in one direction. | scale-down | The image is scaled down while retaining its aspect ratio to fit within the available space. If the image already fits, it is not scaled. | fill | The image is scaled to fit the available space even if it means modifying the aspect ratio of the image. Does not apply to SVG images. | none | The image is not scaled. |=== The `fit` attribute is often combined with the `position` attribute, covered next, to control the placement of the image on the canvas. == Background Image Positioning In addition to scaling, background images for cover pages, content pages, and the title page support positioning via the `position` attribute. The `position` attribute accepts a syntax similar to the `background-position` property in CSS, except only the keyword positions are supported. The position consists of two values, the vertical position and the horizontal position (e.g., `top center`). If only one value is specified (e.g., `top`), the other value is assumed to be `center`. If the `position` attribute is not specified, the value is assumed to be `center center` (i.e., the image is centered on the page). The following table provides a list of the vertical and horizontal positioning keywords that are supported. You can use any combination of these keywords to position the image. |=== | Vertical Positions | Horizontal Positions | top + center + bottom | left + center + right |=== Here's an example of how to place a background image at the top center of every page: ---- :page-background-image: image:bg.png[fit=none,pdfwidth=50%,position=top] ---- Here's how to move it to the bottom right: ---- :page-background-image: image:bg.png[fit=none,pdfwidth=50%,position=bottom right] ---- If an image dimension matches the height or width of the page, the positioning keyword for that axis has no effect. == Fonts in SVG Images Asciidoctor PDF uses {url-prawn-svg}[prawn-svg] to embed SVGs in the PDF document, including SVGs generated by Asciidoctor Diagram. Actually, it's not accurate to say that prawn-svg embeds the SVG. Rather, prawn-svg is an SVG _renderer_. prawn-svg translates an SVG into native PDF text and graphic objects. You can think of the SVG as a sequence of drawing commands. The result becomes indistinguishable from other PDF objects. What that means for text is that any font family used for text in the SVG _must_ be registered in the Asciidoctor PDF theme file (and thus with Prawn). Otherwise, Prawn will fallback to using the closest matching built-in (afm) font from PDF (e.g., sans-serif becomes Helvetica). Recall that afm fonts only support basic Latin. As we like to say, PDF is <>. If you're using Asciidoctor Diagram to generate SVGs to embed in the PDF, you likely need to specify the default font the diagramming tool uses. Let's assume you are making a plantuml diagram. To set the font used in the diagram, first create a file named [.path]_plantuml.cfg_ and populate it with the following content: ---- skinparam defaultFontName Noto Serif ---- TIP: You can choose any font name that is registered in your Asciidoctor PDF theme file. When using the default theme, your options are ""Noto Serif"", ""M+ 1mn"", and ""M+ 1p Fallback"". Next, pass that path to the `plantumlconfig` attribute in your AsciiDoc document (or set the attribute via the CLI or API): ---- :plantumlconfig: plantuml.cfg ---- Clear the cache of your diagrams and run Asciidoctor PDF with Asciidoctor Diagram enabled. The diagrams will be generated using Noto Serif as the default font, and Asciidoctor PDF will know what to do. The bottom line is this: If you're using fonts in your SVG, and you want those fonts to be preserved, those fonts must be defined in the Asciidoctor PDF theme file. == Supporting Additional Image File Formats In order to embed an image into a PDF, Asciidoctor PDF must understand how to read it. To perform this work, Asciidoctor delegates to the underlying libraries. {url-prawn}[Prawn] provides support for reading JPG and PNG images. {url-prawn-svg}[prawn-svg] brings support for SVG images. Without any additional libraries, those are the only supported image file formats. If you need support for additional image formats, such as GIF, TIFF, or interlaced PNG--and you don't want to convert those images to a supported format--you must install the {url-prawn-gmagick}[prawn-gmagick] (>= 0.0.9) Ruby gem. prawn-gmagick is an extension for Prawn based on {url-graphicsmagick}[GraphicsMagick] that adds support for all the image formats recognized by that library. prawn-gmagick has the added benefit of significantly reducing the time it takes to generate a PDF containing a lot of images. The prawn-gmagick gem uses native extensions to compile against GraphicsMagick. This system prerequisite limits installation to Linux and OSX. Please refer to the {url-prawn-gmagick}[README for prawn-gmagick] to learn how to install it. Once this gem is installed, Asciidoctor automatically loads it, then delegates to it to handle all image embedding. In addition to support for additional image file formats, this gem also speeds up image processing considerably. We highly recommend using this gem if you're able to install it. == Importing PDF Pages In addition to using a PDF page for the front or back cover, you can also insert a PDF page at an arbitrary location. This technique is useful to include pages that have complex layouts and graphics prepared in a specialized design program (such as Inkscape), which would otherwise not be achievable using this converter. One such example is an insert such as an advertisement or visual interlude. To import the first page from a PDF file, use the block image macro with the PDF filename as the image target. [source,asciidoc] ---- image::custom-page.pdf[] ---- The converter will insert the page from the PDF as a dedicated page that matches the size and layout of the page being imported (no matter where the block image occurs). Therefore, there's no need to put a manual page break (i.e., `<<<`) around the image macro. By default, this macro will import the first page of the PDF. To import a different page, specify it as a 1-based index using the `page` attribute. [source,asciidoc] ---- image::custom-pages.pdf[page=2] ---- You can import multiple pages either using multiple image macros or using the `pages` attribute. The `pages` attribute accepts individual page numbers or page number ranges (two page numbers separated by `..`). The values can be separated either by commas or semi-colons. (The syntax is similar to the syntax uses for the `lines` attribute of the AsciiDoc include directive). [source,asciidoc] ---- image::custom-pages.pdf[pages=3;1..2] ---- Pages are imported in the order listed. To see a practical example of how to use this feature, refer to the blog post https://fromplantoprototype.com/blog/2019/08/07/importing-pdf-pages-in-asciidoctor-pdf/[Importing PDF Pages in asciidoctor-pdf]. CAUTION: An image macro used to imports PDF pages should never be nested inside a delimited block or table cell. It should be a direct descendant of the document or a section. That's because what it imports are entire pages. If it's used inside a delimited block or table cell, the behavior is unspecified. == Crafting Interdocument Xrefs This converter produces a single PDF file, which means content from multiple source documents get colocated into the same output file. That means references between documents must necessarily become internal references. These interdocument cross references (i.e., xrefs) will only successfully make that transition if you structure your document in accordance with the rules. Those rules are as follows: . The path segment of the interdocument xref must match the project-relative path of the included document . The reference must include the ID of the target element For instance, if your primary document contains the following include: [source,asciidoc] ---- \\include::chapters/chapter-1.adoc[] ---- Then an interdocument xref to an anchor in that chapter must be expressed as: [source,asciidoc] ---- <> ---- This rule holds regardless of which document the xref is located in. To resolve the interdocument xref, the converter first checks if the target matches the `docname` attribute. It then looks to see if the target matches one of the included files. (In both cases, it ignores the file extension). If Asciidoctor cannot resolve the target of an interdocument xref, it simply makes a link (like the HTML converter). Let's consider a complete example. Assume you are converting the following book document at the root of the project: [source,asciidoc] ---- = Book Title :doctype: book \\include::chapters/chapter-1.adoc[] \\include::chapters/chapter-2.adoc[] ---- Where the contents of chapter 1 is as follows: [source,asciidoc] ---- == Chapter 1 We cover a little bit here. The rest you can find in <>. ---- And the contents of chapter 2 is as follows: [source,asciidoc] ---- == Chapter 2 Prepare to be educated. This chapter has it all! To begin, jump to <>. <<< \\include::chapter-2/first-steps.adoc[] ---- And, finally, the contents of the nested include is as follows: [source,asciidoc] ---- === First Steps Let's start small. ---- You'll find when you run this example that all the interdocument xrefs become internal references in the PDF. The reason both the path and anchor are required (even when linking to the top of a chapter) is so the interdocument xref works independent of the converter. In other words, it encodes the complete information about the reference so the converter can sort out where the target is in all circumstances. == STEM Support Unlike the built-in HTML converter, Asciidoctor PDF does not provide native support for STEM blocks and inline macros (i.e., asciimath and latexmath). That's because Asciidoctor core doesn't process the STEM content itself. It just passes it through to the converter. In the HTML output, Asciidoctor relies on the JavaScript-based MathJax library to parse and render the equations in the browser when the page is loaded. The HTML converter simply wraps the equations in special markup so MathJax can find them. In order to insert a rendered equation into the PDF, the toolchain has to parse the equations and convert them to a format the PDF writer (Prawn) can understand. That typically means converting to an image. The recommended solution is an extension named Asciidoctor Mathematical, which we'll cover in this document. Another solution, which is still under development, uses Mathoid to convert STEM equations to images. Mathoid is a library that invokes MathJax using a headless browser, so it supports both asciimath and latexmath equations. That prototype can be found in the https://github.com/asciidoctor/asciidoctor-extensions-lab#extension-catalog[Asciidoctor extensions lab]. === Asciidoctor Mathematical {url-asciidoctor-mathematical}[Asciidoctor Mathematical] is an extension for Asciidoctor that provides alternate processing of STEM blocks and inline macros (currently only latexmath). After the document has been parsed, the extension locates all the latexmath blocks and inline macros, converts the equations to images using Mathematical, then replaces them with image nodes. Conversion then proceeds as normal. Asciidoctor Mathematical is a Ruby gem that uses native extensions. It has a few system prerequisites which limit installation to Linux and OSX. Please refer to the {url-asciidoctor-mathematical}#installation[installation section] in the Asciidoctor Mathematical README to learn how to install it. Once Asciidoctor Mathematical is installed, you just need to enable it when invoking Asciidoctor PDF using the `-r` flag: $ asciidoctor-pdf -r asciidoctor-mathematical sample.adoc If you're invoking Asciidoctor via the API, all you need to do is require the gem before invoking Asciidoctor: [source,ruby] ---- require 'asciidoctor-mathematical' Asciidoctor.convert_file 'sample.adoc', safe: :safe ---- To get the best quality equations, and the maximize speed of conversion, we recommend configuring Asciidoctor Mathematical to convert equations to SVG. You control this setting using the `mathematical-format` AsciiDoc attribute: $ asciidoctor-pdf -r asciidoctor-mathematical -a mathematical-format=svg sample.adoc Refer to the {url-asciidoctor-mathematical}#readme[README] for Asciidoctor Mathematical to learn about additional settings and options. == Skipping Passthrough Content Asciidoctor PDF does not support arbitrary passthrough content. While the basebackend for the PDF converter is html, it only recognizes a limited subset of inline HTML elements that can be mapped to PDF (e.g., a, strong, em, code, ). Therefore, if your content contains passthrough blocks or inlines, you most likely have to use a conditional preprocessor to skip them (and make other arrangements). Here's an example of how to skip a passthrough block when converting to PDF: [source,asciidoc] ---- \\ifndef::backend-pdf[] \\endif::[] ---- Here's an example of how to only enable a passthrough block when convertering to HTML5: [source,asciidoc] ---- \\ifdef::backend-html5[] \\endif::[] ---- == Shaded Blocks and Performance Certain blocks are rendered with a shaded background, such as verbatim (listing, literal, and source), sidebar, and example blocks. In order to calculate the dimensions of the shaded region, Asciidoctor PDF has to ""`dry run`"" the block to determine how many pages it consumes. While this strategy has a low impact when processing shorter blocks, it can drastically deteriorate performance when processing a block that spans dozens of pages. As a general rule of thumb, you should avoid using shaded blocks which span more than a handful of pages. == Autofitting Text Verbatim blocks often have long lines that don't fit within the fixed width of the PDF canvas. And unlike on the web, the PDF reader cannot scroll horizontally to reveal the overflow text. Therefore, the long lines are forced to wrap. Wrapped lines can make the verbatim blocks hard to read or even cause confusion. To help address this problem, Asciidoctor PDF provides the `autofit` option on all verbatim (i.e., literal, listing and source) blocks to attempt to fit the text within the available width. When the `autofit` option is enabled, Asciidoctor PDF will decrease the font size (as much as it can) until the longest line fits without wrapping. CAUTION: The converter will not shrink the font size beyond the value of the `base_font_size_min` key specified in the PDF theme. If that threshold is reached, lines may still wrap. To allow `autofit` to handle all cases, set `base_font_size_min` to `0` in your theme. Here's an example of the autofit option enabled on a source block: [source,asciidoc] .... [source%autofit,java] ---- @SessionScoped public class WidgetRepository { @GET @Produces(""application/json"") public List listAll(@QueryParam(""start"") Integer start, @QueryParam(""max"") Integer max) { ... } } ---- .... If you want to enable the autofit option globally, set the `autofit-option` document attribute in the document header (or somewhere before the relevant blocks): [source,asciidoc] ---- :autofit-option: ---- == Autowidth Tables Asciidoctor PDF does support autowidth tables. However, the behavior differs from HTML when the content forces the table to the page boundary. The behavior, which is handled by the prawn-table library, is explained in this section. If the natural width of all columns (based on the width of the cell content) is less than the width of the page, it behaves as you'd expect. Each column is assigned the width it needs to prevent the content from wrapping. However, when the natural width of all columns exceeds the width of the page, the behavior may not be what you expect. What prawn-table does is compute how to arrange the table on an infinite canvas, where each column can have a width no greater than the width of the page. Then, it reduces the width of the table by reducing the width of each column proportionally. As a result, columns which reported the width necessary to render without wrapping now no longer do. The reason this compression is not performed like in HTML is because prawn-table has no awareness of words. Thus, it doesn't know how to redistribute with width intelligently. To protected against truncation or insufficient width errors, prawn-table wraps text by character. That's why the last character in the cell can end up getting wrapped. (There's a small amount of tolerance built in to prawn-table to address some edge cases, but it's not sufficient to handle all of them). For the reason just explained, you should be extremely careful with relying on autowidth tables in Asciidoctor PDF, especially when the natural content of the cells forces the table to page boundary. Let experience be your guide. == Printing Page Ranges The print dialog doesn't understand the page numbers labels (which appear in the running content). Instead, it only considers physical pages. Therefore, to print a range of pages as they are labeled in the document, you need to add the number of front matter pages (i.e., the non-numbered pages) to the page number range in the print dialog. For example, if you only want to print the first 5 pages labeled with a page number (e.g., 1-5), and there are 2 pages before the page labeled as page 1, you need to add 2 to both numbers in the range, giving you a physical page range of 3-7. That's the range you need to enter into the print dialog. == Title Page Unlike other converters, the PDF converter introduces a dedicated title page at the start of the document. The title page contains the doctitle, author, date, and revision info. If a front cover image is specified, the title page comes after the front cover. The title page can be styled using the theme and/or reserved page attributes. The title page is enabled if either of these conditions are met: * The document has the `book` doctype. * The `title-page` attribute is set (with an empty value) in the document header. When the title page is enabled, the table of contents (aka TOC) also gets is own page (or pages, if necessary). == Table of Contents The table of contents (TOC) is not included by default. The TOC is only included if the `toc` attribute is set on the document. The placement of the table of contents is fixed, and thus the value of the `toc` attribute is effectively ignored in this backend. For documents that have the book doctype, the TOC is inserted using discrete pages between the title page and the first page of content. For all other doctypes (unless the `title-page` attribute is set), the TOC is inserted in the flow of text in between the document title and the first block of content. While the table of contents is not included by default, the PDF outline is always included. The `toclevels` attribute controls the depth of both the TOC and the PDF outline (regardless of whether the TOC is enabled). NOTE: If a document that has the book doctype includes a preface, an entry for the preface is only included in the TOC if the `preface-title` is assigned a value (e.g., `preface-title=Preface`). This value is used as the heading of the preface and as the text of the entry in the TOC. == Index Catalog Asciidoctor PDF supports generating an index catalog that itemizes all index terms defined in the document, allowing the reader to navigate the document by keyword. To get Asciidoctor PDF to generate an index, simply add an level-1 section flagged with the `index` style near the end of your document. The converter will automatically populate the catalog with the list of index terms in the document, organized by first letter. [source,asciidoc] ---- [index] = Index ---- You can use any text you want for the title of the section. The only restriction is that no index terms may be defined below this section. NOTE: Although the catalog is generated automatically, you have to mark the index terms manually. However, you could use an extension, such as a TreeProcessor, to automatically mark index terms. == Optimizing the Generated PDF By default, Asciidoctor PDF does not optimize the output document or even compress the streams. The simplest way to reduce the size of the file is to enable stream compression (using the FlateDecode method). You can enable this feature by setting the `compress` attribute on the document: $ asciidoctor-pdf -a compress document.adoc For more thorough optimzation, you can use either the built-in `asciidoctor-pdf-optimize` script or hexapdf. Read on to learn how. === asciidoctor-pdf-optimize {project-name} also provides a bin script that uses GhostScript to optimize and compress the generated PDF (with minimal impact on quality). You must have Ghostscript (command: `gs`) and the `rghost` gem installed to use it. Here's an example usage: $ asciidoctor-pdf-optimize basic-example.pdf The command will overwrite the PDF file with an optimized version. If a file is found with the extension `.pdfmark` and the same rootname as the input file, it is used to add metadata to the generated PDF document. This file is necessary to preserve the document metadata since Ghostscript will otherwise drop it. That's why {project-name} always creates this file in addition to the PDF. IMPORTANT: The `asciidoctor-pdf-optimize` is not guaranteed to reduce the size of the PDF file. It may actually make the PDF larger. You should probably only consider using it if the file size of the original PDF is several megabytes. You can also try reducing the quality of the output file using the `--quality` flag (e.g., `--quality screen`). The `--quality` flag accepts the following keywords: `default` (default), `screen`, `ebook`, `printer`, and `prepress`. === hexapdf Another option to optimize the PDF is https://hexapdf.gettalong.org/[hexapdf] (gem: hexapdf, command: hexapdf). Before introducing it, though, it's important to point out that its license is AGPL. If that's okay with you, read on to learn how to use it. First, install the hexapdf gem using the following command: $ gem install hexapdf You can then use it to optimize your PDF as follows: $ hexapdf optimize --compress-pages --force basic-example.pdf basic-example-optimized.pdf This command does not manipulate the images in any way. It merely compresses the objects in the PDF and prunes any unreachable references. But given how much waste Prawn leaves behind, this turns out to reduce the file size significantly. To see more options, run: $ hexapdf help optimize For example, to make the source of the PDF a bit more readable, set the stream-related options to `preserve`. hexapdf also allows you to add password protection to your PDF, if that's something you're interested in doing. ifndef::env-site[] == Contributing See the <>. To help develop {project-name}, or to simply use the development version, refer to the <>. [[resources,Links]] == Resources * https://groups.google.com/forum/#!msg/prawn-ruby/MbMsCx862iY/6ImCsvLGfVcJ[Discussion about image quality in PDFs] == Authors {project-name} was written by https://github.com/mojavelinux[Dan Allen] and https://github.com/graphitefriction[Sarah White] of OpenDevise Inc. on behalf of the Asciidoctor Project. == Copyright Copyright (C) 2014-2020 OpenDevise Inc. and the Asciidoctor Project. Free use of this software is granted under the terms of the MIT License. For the full text of the license, see the <> file. Refer to the <> file for information about third-party Open Source software in use. ",12382,False,2056.0546274114085,median "[[spring-cloud-dataflow-task]] = Tasks [partintro] -- This section goes into more detail about how you can work with http://cloud.spring.io/spring-cloud-task/[Spring Cloud Task]. It covers topics such as creating and running task applications. If you are just starting out with Spring Cloud Data Flow, you should probably read the ""`<>`"" guide before diving into this section. -- [[spring-cloud-dataflow-task-intro]] == Introduction A task executes a process on demand. In the case of Spring Cloud Task, a task is a http://projects.spring.io/spring-boot/[Spring Boot] application that is annotated with `@EnableTask`. A user launches a task that performs a certain process, and, once complete, the task ends. Unlike a stream where a stream definition can have at most one deployment a single task definition can be launched multiple times simultaneously. An example of a task would be a Spring Boot application that exports data from a JDBC repository to an HDFS instance. Tasks record the start time and the end time as well as the boot exit code in a relational database. The task implementation is based on the http://cloud.spring.io/spring-cloud-task/[Spring Cloud Task] project. === Application properties Each application takes properties to customize its behavior. As an example, the `timestamp` task `format` setting establishes a output format that is different from the default value. `dataflow:> task create --definition ""timestamp --format=\\""yyyy\\"""" --name printTimeStamp` This `timestamp` property is actually the same as the `timestamp.format` property specified by the timestamp application. Data Flow adds the ability to use the shorthand form `format` instead of `timestamp.format`. One may also specify the longhand version as well, as shown in the following example: `dataflow:> task create --definition ""timestamp --timestamp.format=\\""yyyy\\"""" --name printTimeStamp` This shorthand behavior is discussed more in the section on <>. If you have <> you can use tab completion in the shell after typing `--` to get a list of candidate property names. The shell provides tab completion for application properties. The shell command `app info --name --type ` provides additional documentation for all the supported properties. NOTE: The supported Task `` is task. == The Lifecycle of a Task Before we dive deeper into the details of creating Tasks, we need to understand the typical lifecycle for tasks in the context of Spring Cloud Data Flow: . <> . <> . <> . <> . <> . <> [[spring-cloud-dataflow-create-task-apps]] === Creating a Task Application While Spring Cloud Task does provide a number of out-of-the-box applications (at https://github.com/spring-cloud-task-app-starters[spring-cloud-task-app-starters]), most task applications require custom development. To create a custom task application: . Use the http://start.spring.io[Spring Initializer] to create a new project, making sure to select the following starters: .. `Cloud Task`: This dependency is the `spring-cloud-starter-task`. .. `JDBC`: This dependency is the `spring-jdbc` starter. . Within your new project, create a new class to serve as your main class, as follows: + [source,java] ---- @EnableTask @SpringBootApplication public class MyTask { public static void main(String[] args) { SpringApplication.run(MyTask.class, args); } } ---- + . With this class, you need one or more `CommandLineRunner` or `ApplicationRunner` implementations within your application. You can either implement your own or use the ones provided by Spring Boot (there is one for running batch jobs, for example). . Packaging your application with Spring Boot into an über jar is done through the standard {spring-boot-docs-reference}/html/getting-started-first-application.html#getting-started-first-application-executable-jar[Spring Boot conventions]. The packaged application can be registered and deployed as noted below. ==== Task Database Configuration CAUTION: When launching a task application, be sure that the database driver that is being used by Spring Cloud Data Flow is also a dependency on the task application. For example, if your Spring Cloud Data Flow is set to use Postgresql, be sure that the task application also has Postgresql as a dependency. TIP: When you run tasks externally (that is, from the command line) and you want Spring Cloud Data Flow to show the TaskExecutions in its UI, be sure that common datasource settings are shared among the both. By default, Spring Cloud Task uses a local H2 instance, and the execution is recorded to the database used by Spring Cloud Data Flow. [[spring-cloud-dataflow-register-task-apps]] === Registering a Task Application You can register a Task App with the App Registry by using the Spring Cloud Data Flow Shell `app register` command. You must provide a unique name and a URI that can be resolved to the app artifact. For the type, specify ""task"". The following listing shows three examples: [source,bash] ---- dataflow:>app register --name task1 --type task --uri maven://com.example:mytask:1.0.2 dataflow:>app register --name task2 --type task --uri file:///Users/example/mytask-1.0.2.jar dataflow:>app register --name task3 --type task --uri http://example.com/mytask-1.0.2.jar ---- When providing a URI with the `maven` scheme, the format should conform to the following: `maven://:[:[:]]:` If you would like to register multiple apps at one time, you can store them in a properties file where the keys are formatted as `.` and the values are the URIs. For example, the followinng listing would be a valid properties file: [source] task.foo=file:///tmp/foo.jar task.bar=file:///tmp/bar.jar Then you can use the `app import` command and provide the location of the properties file by using the `--uri` option, as follows: `app import --uri file:///tmp/task-apps.properties` For convenience, we have the static files with application-URIs (for both maven and docker) available for all the out-of-the-box Task app-starters. You can point to this file and import all the application-URIs in bulk. Otherwise, as explained earlier in this chapter, you can register them individually or have your own custom property file with only the required application-URIs in it. It is recommended, however, to have a ""`focused`"" list of desired application-URIs in a custom property file. The following table lists the available static property files: [width=""100%"",frame=""topbot"",options=""header""] |====================== |Artifact Type |Stable Release |SNAPSHOT Release |Maven | http://bit.ly/Clark-GA-task-applications-maven | http://bit.ly/Clark-BUILD-SNAPSHOT-task-applications-maven |Docker | http://bit.ly/Clark-GA-task-applications-docker | http://bit.ly/Clark-BUILD-SNAPSHOT-task-applications-docker |====================== For example, if you would like to register all out-of-the-box task applications in bulk, you can do so with the following command: `dataflow:>app import --uri http://bit.ly/Clark-GA-task-applications-maven` You can also pass the `--local` option (which is `TRUE` by default) to indicate whether the properties file location should be resolved within the shell process itself. If the location should be resolved from the Data Flow Server process, specify `--local false`. When using either `app register` or `app import`, if a task app is already registered with the provided name, it is not overridden by default. If you would like to override the pre-existing task app, then include the `--force` option. [NOTE] In some cases, the Resource is resolved on the server side. In other cases, the URI is passed to a runtime container instance where it is resolved. Consult the specific documentation of each Data Flow Server for more detail. [[spring-cloud-dataflow-create-task-definition]] === Creating a Task Definition You can create a task Definition from a task app by providing a definition name as well as properties that apply to the task execution. Creating a task definition can be done through the RESTful API or the shell. To create a task definition by using the shell, use the `task create` command to create the task definition, as shown in the following example: [source] dataflow:>task create mytask --definition ""timestamp --format=\\""yyyy\\"""" Created new task 'mytask' A listing of the current task definitions can be obtained through the RESTful API or the shell. To get the task definition list by using the shell, use the `task list` command. [[spring-cloud-dataflow-task-launch]] === Launching a Task An adhoc task can be launched through the RESTful API or the shell. To launch an ad-hoc task through the shell, use the `task launch` command, as shown in the following example: [source] dataflow:>task launch mytask Launched task 'mytask' When a task is launched, any properties that need to be passed as command line arguments to the task application can be set when launching the task, as follows: [source] dataflow:>task launch mytask --arguments ""--server.port=8080 --custom=value"" [NOTE] The arguments need to be passed as `space` delimited values. Additional properties meant for a `TaskLauncher` itself can be passed in by using a `--properties` option. The format of this option is a comma-separated string of properties prefixed with `app..`. Properties are passed to `TaskLauncher` as application properties. It is up to an implementation to choose how those are passed into an actual task application. If the property is prefixed with `deployer` instead of `app`, it is passed to `TaskLauncher` as a deployment property and its meaning may be `TaskLauncher` implementation specific. `dataflow:>task launch mytask --properties ""deployer.timestamp.custom1=value1,app.timestamp.custom2=value2""` ==== Common application properties In addition to configuration through DSL, Spring Cloud Data Flow provides a mechanism for setting common properties to all the task applications that are launched by it. This can be done by adding properties prefixed with `spring.cloud.dataflow.applicationProperties.task` when starting the server. When doing so, the server passes all the properties, without the prefix, to the instances it launches. For example, all the launched applications can be configured to use the properties `prop1` and `prop2` by launching the Data Flow server with the following options: [source] --spring.cloud.dataflow.applicationProperties.task.prop1=value1 --spring.cloud.dataflow.applicationProperties.task.prop2=value2 This causes the properties, `prop1=value1` and `prop2=value2`, to be passed to all the launched applications. [NOTE] Properties configured by using this mechanism have lower precedence than task deployment properties. They are overridden if a property with the same key is specified at task launch time (for example, `app.trigger.prop2` overrides the common property). [[spring-cloud-dataflow-task-review-executions]] === Reviewing Task Executions Once the task is launched, the state of the task is stored in a relational DB. The state includes: * Task Name * Start Time * End Time * Exit Code * Exit Message * Last Updated Time * Parameters A user can check the status of their task executions through the RESTful API or the shell. To display the latest task executions through the shell, use the `task execution list` command. To get a list of task executions for just one task definition, add `--name` and the task definition name, for example `task execution list --name foo`. To retrieve full details for a task execution use the `task execution status` command with the id of the task execution, for example `task execution status --id 549`. [[spring-cloud-dataflow-task-definition-destroying]] === Destroying a Task Definition Destroying a Task Definition removes the definition from the definition repository. This can be done through the RESTful API or the shell. To destroy a task through the shell, use the `task destroy` command, as shown in the following example: [source] dataflow:>task destroy mytask Destroyed task 'mytask' The task execution information for previously launched tasks for the definition remains in the task repository. NOTE: This does not stop any currently executing tasks for this definition. Instead, it removes the task definition from the database. [[spring-cloud-dataflow-task-events]] == Subscribing to Task/Batch Events You can also tap into various task and batch events when the task is launched. If the task is enabled to generate task or batch events (with the additional dependencies `spring-cloud-task-stream` and, in the case of Kafka as the binder, `spring-cloud-stream-binder-kafka`), those events are published during the task lifecycle. By default, the destination names for those published events on the broker (Rabbit, Kafka, and others) are the event names themselves (for instance: `task-events`, `job-execution-events`, and so on). [source] dataflow:>task create myTask --definition “myBatchJob"" dataflow:>task launch myTask dataflow:>stream create task-event-subscriber1 --definition "":task-events > log"" --deploy You can control the destination name for those events by specifying explicit names when launching the task, as follows: [source] dataflow:>task launch myTask --properties ""spring.cloud.stream.bindings.task-events.destination=myTaskEvents"" dataflow:>stream create task-event-subscriber2 --definition "":myTaskEvents > log"" --deploy The following table lists the default task and batch event and destination names on the broker: .Task and Batch Event Destinations [cols=""2*""] |=== |*Event*|*Destination* |Task events |`task-events` |Job Execution events |`job-execution-events` |Step Execution events|`step-execution-events` |Item Read events|`item-read-events` |Item Process events|`item-process-events` |Item Write events|`item-write-events` |Skip events|`skip-events` |=== [[spring-cloud-dataflow-composed-tasks]] == Composed Tasks Spring Cloud Data Flow lets a user create a directed graph where each node of the graph is a task application. This is done by using the DSL for composed tasks. A composed task can be created through the RESTful API, the Spring Cloud Data Flow Shell, or the Spring Cloud Data Flow UI. === Configuring the Composed Task Runner Composed tasks are executed through a task application called the https://github.com/spring-cloud-task-app-starters/composed-task-runner[Composed Task Runner]. ==== Registering the Composed Task Runner By default, the Composed Task Runner application is not registered with Spring Cloud Data Flow. Consequently, to launch composed tasks, we must first register the Composed Task Runner as an application with Spring Cloud Data Flow, as follows: `app register --name composed-task-runner --type task --uri maven://org.springframework.cloud.task.app:composedtaskrunner-task:` You can also configure Spring Cloud Data Flow to use a different task definition name for the composed task runner. This can be done by setting the `spring.cloud.dataflow.task.composedTaskRunnerName` property to the name of your choice. You can then register the composed task runner application with the name you set by using that property. ==== Configuring the Composed Task Runner The Composed Task Runner application has a `dataflow.server.uri` property that is used for validation and for launching child tasks. This defaults to `http://localhost:9393`. If you run a distributed Spring Cloud Data Flow server, as you would if you deploy the server on Cloud Foundry, YARN, or Kubernetes, you need to provide the URI that can be used to access the server. You can either provide this `dataflow.server.uri` property for the Composed Task Runner application when launching a composed task or you can provide a `spring.cloud.dataflow.server.uri` property for the Spring Cloud Data Flow server when it is started. For the latter case, the `dataflow.server.uri` Composed Task Runner application property is automatically set when a composed task is launched. In some cases, you may wish to execute an instance of the Composed Task Runner through the Task Launcher sink. In that case, you must configure the Composed Task Runner to use the same datasource that the Spring Cloud Data Flow instance is using. The datasource properties are set with the `TaskLaunchRequest` through the use of the `commandlineArguments` or the `environmentProperties` switches. This is because the Composed Task Runner monitors the `task_executions` table to check the status of the tasks that it is running. Using information from the table, it determines how it should navigate the graph. ===== Configuration Options The ComposedTaskRunner task has the following options: * *increment-instance-enabled* Allows a single ComposedTaskRunner instance to be re-executed without changing the parameters. Default is false which means a ComposedTaskRunner instance can only be executed once with a given set of parameters, if true it can be re-executed. (Boolean, default: false). ComposedTaskRunner is built using https://github.com/spring-projects/spring-batch[Spring Batch] and thus upon a successful execution the batch job is considered complete. To launch the same ComposedTaskRunner definition multiple times you must set the `increment-instance-enabled` property to true or change the parameters for the definition for each launch. * *interval-time-between-checks* The amount of time in millis that the ComposedTaskRunner will wait between checks of the database to see if a task has completed. (Integer, default: 10000). ComposedTaskRunner uses the datastore to determine the status of each child tasks. This interval indicates to ComposedTaskRunner how often it should check the status its child tasks. * *max-wait-time* The maximum amount of time in millis that a individual step can run before the execution of the Composed task is failed (Integer, default: 0). Determines the maximum time each child task is allowed to run before the CTR will terminate with a failure. The default of `0` indicates no timeout. * *split-thread-allow-core-thread-timeout* Specifies whether to allow split core threads to timeout. Default is false; (Boolean, default: false) Sets the policy governing whether core threads may timeout and terminate if no tasks arrive within the keep-alive time, being replaced if needed when new tasks arrive. * *split-thread-core-pool-size* Split's core pool size. Default is 1; (Integer, default: 1) Each child task contained in a split requires a thread in order to execute. So for example a definition like: ` && ` would require a split-thread-core-pool-size of 3. This is because the largest split contains 3 child tasks. A count of 2 would mean that `AAA` and `BBB` would run in parallel but CCC would wait until either `AAA` or `BBB` to finish in order to run. Then `DDD` and `EEE` would run in parallel. * *split-thread-keep-alive-seconds* Split's thread keep alive seconds. Default is 60. (Integer, default: 60) If the pool currently has more than corePoolSize threads, excess threads will be terminated if they have been idle for more than the keepAliveTime. * *split-thread-max-pool-size* Split's maximum pool size. Default is {@code Integer.MAX_VALUE} (Integer, default: ). Establish the maximum number of threads allowed for the thread pool. * *split-thread-queue-capacity* Capacity for Split's BlockingQueue. Default is {@code Integer.MAX_VALUE}. (Integer, default: ) ** If fewer than corePoolSize threads are running, the Executor always prefers adding a new thread rather than queuing. ** If corePoolSize or more threads are running, the Executor always prefers queuing a request rather than adding a new thread. ** If a request cannot be queued, a new thread is created unless this would exceed maximumPoolSize, in which case, the task will be rejected. * *split-thread-wait-for-tasks-to-complete-on-shutdown* Whether to wait for scheduled tasks to complete on shutdown, not interrupting running tasks and executing all tasks in the queue. Default is false; (Boolean, default: false) Note when using the options above as environment variables, convert to uppercase, remove the dash character and replace with the underscore character. For example: increment-instance-enabled would be INCREMENT_INSTANCE_ENABLED. === The Lifecycle of a Composed Task The lifecycle of a composed task has three parts: * <> * <> * <> [[spring-cloud-data-flow-composed-task-creating]] ==== Creating a Composed Task The DSL for the composed tasks is used when creating a task definition through the task create command, as shown in the following example: [source] dataflow:> app register --name timestamp --type task --uri maven://org.springframework.cloud.task.app:timestamp-task: dataflow:> app register --name mytaskapp --type task --uri file:///home/tasks/mytask.jar dataflow:> task create my-composed-task --definition ""mytaskapp && timestamp"" dataflow:> task launch my-composed-task In the preceding example, we assume that the applications to be used by our composed task have not been registered yet. Consequently, in the first two steps, we register two task applications. We then create our composed task definition by using the `task create` command. The composed task DSL in the preceding example, when launched, runs mytaskapp and then runs the timestamp application. But before we launch the `my-composed-task` definition, we can view what Spring Cloud Data Flow generated for us. This can be done by executing the task list command, as shown (including its output) in the following example: [source,bash,options=""nowrap""] ---- dataflow:>task list ╔══════════════════════════╤══════════════════════╤═══════════╗ ║ Task Name │ Task Definition │Task Status║ ╠══════════════════════════╪══════════════════════╪═══════════╣ ║my-composed-task │mytaskapp && timestamp│unknown ║ ║my-composed-task-mytaskapp│mytaskapp │unknown ║ ║my-composed-task-timestamp│timestamp │unknown ║ ╚══════════════════════════╧══════════════════════╧═══════════╝ ---- In the example, Spring Cloud Data Flow created three task definitions, one for each of the applications that makes up our composed task (`my-composed-task-mytaskapp` and `my-composed-task-timestamp`) as well as the composed task (`my-composed-task`) definition. We also see that each of the generated names for the child tasks is made up of the name of the composed task and the name of the application, separated by a dash `-` (as in _my-composed-task_ `-` _mytaskapp_). ===== Task Application Parameters The task applications that make up the composed task definition can also contain parameters, as shown in the following example: `dataflow:> task create my-composed-task --definition ""mytaskapp --displayMessage=hello && timestamp --format=YYYY""` ==== Launching a Composed Task Launching a composed task is done the same way as launching a stand-alone task, as follows: `task launch my-composed-task` Once the task is launched, and assuming all the tasks complete successfully, you can see three task executions when executing a `task execution list`, as shown in the following example: [source,bash,options=""nowrap""] ---- dataflow:>task execution list ╔══════════════════════════╤═══╤════════════════════════════╤════════════════════════════╤═════════╗ ║ Task Name │ID │ Start Time │ End Time │Exit Code║ ╠══════════════════════════╪═══╪════════════════════════════╪════════════════════════════╪═════════╣ ║my-composed-task-timestamp│713│Wed Apr 12 16:43:07 EDT 2017│Wed Apr 12 16:43:07 EDT 2017│0 ║ ║my-composed-task-mytaskapp│712│Wed Apr 12 16:42:57 EDT 2017│Wed Apr 12 16:42:57 EDT 2017│0 ║ ║my-composed-task │711│Wed Apr 12 16:42:55 EDT 2017│Wed Apr 12 16:43:15 EDT 2017│0 ║ ╚══════════════════════════╧═══╧════════════════════════════╧════════════════════════════╧═════════╝ ---- In the preceding example, we see that `my-compose-task` launched and that it also launched the other tasks in sequential order. All of them executed successfully with `Exit Code` as `0`. ===== Passing properties to the child tasks To set the properties for child tasks in a composed task graph at task launch time, you would use the following format of `app...`. Using the following Composed Task definition as an example: [source,bash] ---- dataflow:> task create my-composed-task --definition ""mytaskapp && mytimestamp"" ---- To have mytaskapp display 'HELLO' and set the mytimestamp timestamp format to 'YYYY' for the Composed Task definition, you would use the following task launch format: [source,bash] ---- task launch my-composed-task --properties ""app.my-composed-task.mytaskapp.displayMessage=HELLO,app.my-composed-task.mytimestamp.timestamp.format=YYYY"" ---- Similar to application properties, the `deployer` properties can also be set for child tasks using the format format of `deployer...`. [source,bash] ---- task launch my-composed-task --properties ""deployer.my-composed-task.mytaskapp.memory=2048m,app.my-composed-task.mytimestamp.timestamp.format=HH:mm:ss"" Launched task 'a1' ---- ===== Passing arguments to the composed task runner Command line arguments for the composed task runner can be passed using `--arguments` option. For example: [source,bash] ---- dataflow:>task create my-composed-task --definition """" Created new task 'my-composed-task' dataflow:>task launch my-composed-task --arguments ""--increment-instance-enabled=true --max-wait-time=50000 --split-thread-core-pool-size=4"" --properties ""app.my-composed-task.bbb.timestamp.format=dd/MM/yyyy HH:mm:ss"" Launched task 'my-composed-task' ---- ===== Exit Statuses The following list shows how the Exit Status is set for each step (task) contained in the composed task following each step execution: * If the `TaskExecution` has an `ExitMessage`, that is used as the `ExitStatus`. * If no `ExitMessage` is present and the `ExitCode` is set to zero, then the `ExitStatus` for the step is `COMPLETED`. * If no `ExitMessage` is present and the `ExitCode` is set to any non-zero number, the `ExitStatus` for the step is `FAILED`. ==== Destroying a Composed Task The command used to destroy a stand-alone task is the same as the command used to destroy a composed task. The only difference is that destroying a composed task also destroys the child tasks associated with it. The following example shows the task list before and after using the `destroy` command: [source,bash,options=""nowrap""] ---- dataflow:>task list ╔══════════════════════════╤══════════════════════╤═══════════╗ ║ Task Name │ Task Definition │Task Status║ ╠══════════════════════════╪══════════════════════╪═══════════╣ ║my-composed-task │mytaskapp && timestamp│COMPLETED ║ ║my-composed-task-mytaskapp│mytaskapp │COMPLETED ║ ║my-composed-task-timestamp│timestamp │COMPLETED ║ ╚══════════════════════════╧══════════════════════╧═══════════╝ ... dataflow:>task destroy my-composed-task dataflow:>task list ╔═════════╤═══════════════╤═══════════╗ ║Task Name│Task Definition│Task Status║ ╚═════════╧═══════════════╧═══════════╝ ---- [[spring-cloud-data-flow-composed-task-stopping]] ==== Stopping a Composed Task In cases where a composed task execution needs to be stopped, you can do so through the: * RESTful API * Spring Cloud Data Flow Dashboard To stop a composed task through the dashboard, select the Jobs tab and click the Stop button next to the job execution that you want to stop. The composed task run is stopped when the currently running child task completes. The step associated with the child task that was running at the time that the composed task was stopped is marked as `STOPPED` as well as the composed task job execution. [[spring-cloud-data-flow-composed-task-restarting]] ==== Restarting a Composed Task In cases where a composed task fails during execution and the status of the composed task is `FAILED`, the task can be restarted. You can do so through the: * RESTful API * The shell * Spring Cloud Data Flow Dashboard To restart a composed task through the shell, launch the task with the same parameters. To restart a composed task through the dashboard, select the Jobs tab and click the Restart button next to the job execution that you want to restart. NOTE: Restarting a Composed Task job that has been stopped (through the Spring Cloud Data Flow Dashboard or RESTful API) relaunches the `STOPPED` child task and then launches the remaining (unlaunched) child tasks in the specified order. == Composed Tasks DSL Composed tasks can be run in three ways: * <> * <> * <> [[spring-cloud-data-flow-conditional-execution]] === Conditional Execution Conditional execution is expressed by using a double ampersand symbol (`&&`). This lets each task in the sequence be launched only if the previous task successfully completed, as shown in the following example: `task create my-composed-task --definition ""task1 && task2""` When the composed task called `my-composed-task` is launched, it launches the task called `task1` and, if it completes successfully, then the task called `task2` is launched. If `task1` fails, then `task2` does not launch. You can also use the Spring Cloud Data Flow Dashboard to create your conditional execution, by using the designer to drag and drop applications that are required and connecting them together to create your directed graph, as shown in the following image: .Conditional Execution image::{dataflow-asciidoc}/images/dataflow-ctr-conditional-execution.png[Composed Task Conditional Execution, scaledwidth=""50%""] The preceding diagram is a screen capture of the directed graph as it being created by using the Spring Cloud Data Flow Dashboard. You can see that are four components in the diagram that comprise a conditional execution: * Start icon: All directed graphs start from this symbol. There is only one. * Task icon: Represents each task in the directed graph. * End icon: Represents the termination of a directed graph. * Solid line arrow: Represents the flow conditional execution flow between: ** Two applications. ** The start control node and an application. ** An application and the end control node. * End icon: All directed graphs end at this symbol. TIP: You can view a diagram of your directed graph by clicking the Detail button next to the composed task definition on the Definitions tab. [[spring-cloud-data-flow-transitional-execution]] === Transitional Execution The DSL supports fine- grained control over the transitions taken during the execution of the directed graph. Transitions are specified by providing a condition for equality based on the exit status of the previous task. A task transition is represented by the following symbol `->`. ==== Basic Transition A basic transition would look like the following: `task create my-transition-composed-task --definition ""foo 'FAILED' -> bar 'COMPLETED' -> baz""` In the preceding example, `foo` would launch, and, if it had an exit status of `FAILED`, the `bar` task would launch. If the exit status of `foo` was `COMPLETED`, `baz` would launch. All other statuses returned by `foo` have no effect, and the task would terminate normally. Using the Spring Cloud Data Flow Dashboard to create the same "" `basic transition` "" would resemble the following image: .Basic Transition image::{dataflow-asciidoc}/images/dataflow-ctr-transition-basic.png[Composed Task Basic Transition, scaledwidth=""50%""] The preceding diagram is a screen capture of the directed graph as it being created in the Spring Cloud Data Flow Dashboard. Notice that there are two different types of connectors: * Dashed line: Represents transitions from the application to one of the possible destination applications. * Solid line: Connects applications in a conditional execution or a connection between the application and a control node (start or end). To create a transitional connector: . When creating a transition, link the application to each possible destination by using the connector. . Once complete, go to each connection and select it by clicking it. . A bolt icon appears. . Click that icon. . Enter the exit status required for that connector. . The solid line for that connector turns to a dashed line. ==== Transition With a Wildcard Wildcards are supported for transitions by the DSL, as shown in the following: `task create my-transition-composed-task --definition ""foo 'FAILED' -> bar '*' -> baz""` In the preceding example, `foo` would launch, and, if it had an exit status of `FAILED`, the `bar` task would launch. For any exit status of `foo` other than `FAILED`, `baz` would launch. Using the Spring Cloud Data Flow Dashboard to create the same ""`transition with wildcard`"" would resemble the following image: .Basic Transition With Wildcard image::{dataflow-asciidoc}/images/dataflow-ctr-transition-basic-wildcard.png[Composed Task Basic Transition with Wildcard, scaledwidth=""50%""] ==== Transition With a Following Conditional Execution A transition can be followed by a conditional execution so long as the wildcard is not used, as shown in the following example: `task create my-transition-conditional-execution-task --definition ""foo 'FAILED' -> bar 'UNKNOWN' -> baz && qux && quux""` In the preceding example, `foo` would launch, and, if it had an exit status of `FAILED`, the `bar` task would launch. If `foo` had an exit status of `UNKNOWN`, `baz` would launch. For any exit status of `foo` other than `FAILED` or `UNKNOWN`, `qux` would launch and, upon successful completion, `quux` would launch. Using the Spring Cloud Data Flow Dashboard to create the same ""`transition with conditional execution`"" would resemble the following image: .Transition With Conditional Execution image::{dataflow-asciidoc}/images/dataflow-ctr-transition-conditional-execution.png[Composed Task Transition with Conditional Execution, scaledwidth=""50%""] NOTE: In this diagram we see the dashed line (transition) connecting the `foo` application to the target applications, but a solid line connecting the conditional executions between `foo`, `qux`, and `quux`. [[spring-cloud-data-flow-split-execution]] === Split Execution Splits allow multiple tasks within a composed task to be run in parallel. It is denoted by using angle brackets (`<>`) to group tasks and flows that are to be run in parallel. These tasks and flows are separated by the double pipe `||` symbol, as shown in the following example: `task create my-split-task --definition """"` The preceding example above launches tasks `foo`, `bar` and `baz` in parallel. Using the Spring Cloud Data Flow Dashboard to create the same ""`split execution`"" would resemble the following image: .Split image::{dataflow-asciidoc}/images/dataflow-ctr-split.png[Composed Task Split, scaledwidth=""50%""] With the task DSL, a user may also execute multiple split groups in succession, as shown in the following example: `task create my-split-task --definition "" && ""' In the preceding example, tasks `foo`, `bar`, and `baz` are launched in parallel. Once they all complete, then tasks `qux` and `quux` are launched in parallel. Once they complete, the composed task ends. However, if `foo`, `bar`, or `baz` fails, the split containing `qux` and `quux` does not launch. Using the Spring Cloud Data Flow Dashboard to create the same ""`split with multiple groups`"" would resemble the following image: .Split as a part of a conditional execution image::{dataflow-asciidoc}/images/dataflow-ctr-multiple-splits.png[Composed Task Split, scaledwidth=""50%""] Notice that there is a `SYNC` control node that is inserted by the designer when connecting two consecutive splits. ==== Split Containing Conditional Execution A split can also have a conditional execution within the angle brackets, as shown in the following example: `task create my-split-task --definition """"` In the preceding example, we see that `foo` and `baz` are launched in parallel. However, `bar` does not launch until `foo` completes successfully. Using the Spring Cloud Data Flow Dashboard to create the same "" `split containing conditional execution` "" resembles the following image: .Split with conditional execution image::{dataflow-asciidoc}/images/dataflow-ctr-split-contains-conditional.png[Composed Task Split With Conditional Execution, scaledwidth=""50%""] ==== Establishing the proper thread count for splits Each child task contained in a split requires a thread in order to execute. To set this properly you want to look at your graph and count the split that has the largest number of child tasks, this will be the number of threads you will need to utilize. To set the thread count use the split-thread-core-pool-size property (defaults to 1). So for example a definition like: ` && ` would require a split-thread-core-pool-size of 3. This is because the largest split contains 3 child tasks. A count of 2 would mean that `AAA` and `BBB` would run in parallel but CCC would wait until either `AAA` or `BBB` to finish in order to run. Then `DDD` and `EEE` would run in parallel. [[spring-cloud-dataflow-launch-tasks-from-stream]] == Launching Tasks from a Stream You can launch a task from a stream by using one of the available `task-launcher` sinks. Currently the platforms supported by the `task-launcher` sinks are: * https://github.com/spring-cloud-stream-app-starters/tasklauncher-local[local], * https://github.com/spring-cloud-stream-app-starters/tasklauncher-cloudfoundry[Cloud Foundry] * https://github.com/spring-cloud-stream-app-starters/tasklauncher-kubernetes[Kubernetes] * https://github.com/spring-cloud-stream-app-starters/tasklauncher-yarn[Yarn] CAUTION: `task-launcher-local` is meant for development purposes only. A `task-launcher` sink expects a message containing a https://github.com/spring-cloud/spring-cloud-task/blob/master/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/launcher/TaskLaunchRequest.java[TaskLaunchRequest] object in its payload. From the `TaskLaunchRequest` object, the `task-launcher` obtains the URI of the artifact to be launched, as well as the environment properties, command line arguments, deployment properties, and application name to be used by the task. The https://github.com/spring-cloud-stream-app-starters/tasklauncher-local/blob/v1.2.0.RELEASE/spring-cloud-starter-stream-sink-task-launcher-local/README.adoc[task-launcher-local] can be added to the available sinks by executing the app register command, as follows (for the Rabbit Binder, in this case): `app register --name task-launcher-local --type sink --uri maven://org.springframework.cloud.stream.app:task-launcher-local-sink-rabbit:jar:1.2.0.RELEASE` In the case of a Maven-based task that is to be launched, the `task-launcher` application is responsible for downloading the artifact. You *must* configure the `task-launcher` with the appropriate configuration of https://github.com/spring-cloud/spring-cloud-deployer/blob/master/spring-cloud-deployer-resource-maven/src/main/java/org/springframework/cloud/deployer/resource/maven/MavenProperties.java[Maven Properties], such as `--maven.remote-repositories.repo1.url=http://repo.spring.io/libs-milestone""` to resolve artifacts (in this case against a milestone repo). Note that this repostory can be different than the one used to register the `task-launcher` application itself. === TriggerTask One way to launch a task with the `task-launcher` is to use the https://github.com/spring-cloud-stream-app-starters/triggertask/blob/v1.2.0.RELEASE/spring-cloud-starter-stream-source-triggertask/README.adoc[triggertask] source. The `triggertask` source emits a message with a `TaskLaunchRequest` object that contains the required launch information. The `triggertask` can be added to the available sources by running the app register command, as follows (for the Rabbit Binder, in this case): `app register --type source --name triggertask --uri maven://org.springframework.cloud.stream.app:triggertask-source-rabbit:1.2.0.RELEASE` For example, to launch the timestamp task once every 60 seconds, the stream implementation would be as follows: [source] stream create foo --definition ""triggertask --triggertask.uri=maven://org.springframework.cloud.task.app:timestamp-task:jar:1.2.0.RELEASE --trigger.fixed-delay=60 --triggertask.environment-properties=spring.datasource.url=jdbc:h2:tcp://localhost:19092/mem:dataflow,spring.datasource.username=sa | task-launcher-local --maven.remote-repositories.repo1.url=http://repo.spring.io/libs-release"" --deploy If you run `runtime apps`, you can find the log file for the task launcher sink. By using the `tail` command on that file, you can find the log file for the launched tasks. Setting of `triggertask.environment-properties` establishes the Data Flow Server's H2 Database as the database where the task executions will be recorded. You can then see the list of task executions by using the shell command `task execution list`, as shown (with its output) in the following example: [source,bash,options=""nowrap""] ---- dataflow:>task execution list ╔════════════════════╤══╤════════════════════════════╤════════════════════════════╤═════════╗ ║ Task Name │ID│ Start Time │ End Time │Exit Code║ ╠════════════════════╪══╪════════════════════════════╪════════════════════════════╪═════════╣ ║timestamp-task_26176│4 │Tue May 02 12:13:49 EDT 2017│Tue May 02 12:13:49 EDT 2017│0 ║ ║timestamp-task_32996│3 │Tue May 02 12:12:49 EDT 2017│Tue May 02 12:12:49 EDT 2017│0 ║ ║timestamp-task_58971│2 │Tue May 02 12:11:50 EDT 2017│Tue May 02 12:11:50 EDT 2017│0 ║ ║timestamp-task_13467│1 │Tue May 02 12:10:50 EDT 2017│Tue May 02 12:10:50 EDT 2017│0 ║ ╚════════════════════╧══╧════════════════════════════╧════════════════════════════╧═════════╝ ---- === TaskLaunchRequest-transform Another way to start a task with the `task-launcher` would be to create a stream by using the https://github.com/spring-cloud-stream-app-starters/tasklaunchrequest-transform[Tasklaunchrequest-transform] processor to translate a message payload to a `TaskLaunchRequest`. The `tasklaunchrequest-transform` can be added to the available processors by executing the app register command, as follows (for the Rabbit Binder, in this case): `app register --type processor --name tasklaunchrequest-transform --uri maven://org.springframework.cloud.stream.app:tasklaunchrequest-transform-processor-rabbit:1.2.0.RELEASE` The following example shows the creation of a task that includes the `tasklaunchrequest-transform`: `stream create task-stream --definition ""http --port=9000 | tasklaunchrequest-transform --uri=maven://org.springframework.cloud.task.app:timestamp-task:jar:1.2.0.RELEASE | task-launcher-local --maven.remote-repositories.repo1.url=http://repo.spring.io/libs-release""` === Launching a Composed Task From a Stream A composed task can be launched with one of the `task-launcher` sinks as discussed <>. Since we use the `ComposedTaskRunner` directly, we need to set up the task definitions it uses prior to the creation of the composed task launching stream. Suppose we wanted to create the following composed task definition: `AAA && BBB`. The first step would be to create the task definitions, as shown in the following example: [source] ---- task create AAA --definition ""timestamp"" task create BBB --definition ""timestamp"" ---- Now that the task definitions we need for composed task definition are ready, we need to create a stream that launches `ComposedTaskRunner`. So, in this case, we create a stream with * A trigger that emits a message once every 30 seconds * A transformer that creates a `TaskLaunchRequest` for each message received * A `task-launcher-local` sink that launches a the `ComposedTaskRunner` on our local machine The stream should resemble the following: [source] ---- stream create ctr-stream --definition ""time --fixed-delay=30 | tasklaunchrequest-transform --uri=maven://org.springframework.cloud.task.app:composedtaskrunner-task: --command-line-arguments='--graph=AAA&&BBB --increment-instance-enabled=true --spring.datasource.url=...' | task-launcher-local"" ---- In the preceding example, we see that the `tasklaunchrequest-transform` is establishing two primary components: * *uri*: The URI of the `ComposedTaskRunner` that is used * *command-line-arguments*: To configure the `ComposedTaskRunner` For now, we focus on the configuration that is required to launch the `ComposedTaskRunner`: * *graph*: this is the graph that is to be executed by the `ComposedTaskRunner`. In this case it is `AAA&&BBB`. * *increment-instance-enabled*: This lets each execution of `ComposedTaskRunner` be unique. `ComposedTaskRunner` is built by using http://projects.spring.io/spring-batch/[Spring Batch]. Thus, we want a new Job Instance for each launch of the `ComposedTaskRunner`. To do this, we set `increment-instance-enabled` to be `true`. * *spring.datasource.**: The datasource that is used by Spring Cloud Data Flow, which lets the user track the tasks launched by the `ComposedTaskRunner` and the state of the job execution. Also, this is so that the `ComposedTaskRunner` can track the state of the tasks it launched and update its state. NOTE: Releases of `ComposedTaskRunner` can be found https://github.com/spring-cloud-task-app-starters/composed-task-runner/releases[here]. [[sharing-spring-cloud-dataflows-datastore-with-tasks]] == Sharing Spring Cloud Data Flow's Datastore with Tasks As discussed in the <> documentation Spring Cloud Data Flow allows a user to view Spring Cloud Task App executions. So in this section we will discuss what is required by a Task Application and Spring Cloud Data Flow to share the task execution information. [a-common-datastore-dependency] === A Common DataStore Dependency Spring Cloud Data Flow supports many database <> out-of-the-box, so all the user typically has to do is declare the `spring_datasource_*` environment variables to establish what data store Spring Cloud Data Flow will need. So whatever database you decide to use for Spring Cloud Data Flow make sure that the your task also includes that database dependency in its `pom.xml` or `gradle.build` file. If the database dependency that is used by Spring Cloud Data Flow is not present in the Task Application, the task will fail and the task execution will not be recorded. [a-common-datastore] === A Common Data Store Spring Cloud Data Flow and your task application must access the same datastore instance. This is so that the task executions recorded by the task application can be read by Spring Cloud Data Flow to list them in the Shell and Dashboard views. Also the task app must have read & write privileges to the task data tables that are used by Spring Cloud Data Flow. Given the understanding of Datasource dependency between Task apps and Spring Cloud Data Flow, let's review how to apply them in various Task orchestration scenarios. [datasource-simple-task-launch] ==== Simple Task Launch When launching a task from Spring Cloud Data Flow, Data Flow adds its datasource properties (`spring.datasource.url`, `spring.datasource.driverClassName`, `spring.datasource.username`, `spring.datasource.password`) to the app properties of the task being launched. Thus a task application will record its task execution information to the Spring Cloud Data Flow repository. [datasource-task-launcher-sink] ==== Task Launcher Sink The https://github.com/spring-cloud-stream-app-starters/tasklauncher-local[Task Launcher Sink] allows tasks to be launched via a stream as discussed <>. Since tasks launched by the Task Launcher Sink may not want their task executions recorded to the same datastore as Spring Cloud Data Flow, each https://docs.spring.io/spring-cloud-task/docs/current/apidocs/org/springframework/cloud/task/launcher/TaskLaunchRequest.html[TaskLaunchRequest] received by the Task Launcher Sink must have the required datasource information established as app properties or command line arguments. Both https://github.com/spring-cloud-stream-app-starters/tasklaunchrequest-transform/blob/master/spring-cloud-starter-stream-processor-tasklaunchrequest-transform/README.adoc[TaskLaunchRequest-Transform] and https://github.com/spring-cloud-stream-app-starters/triggertask/blob/master/spring-cloud-starter-stream-source-triggertask/README.adoc[TriggerTask Source] are examples of how a source and a processor allow a user to set the datasource properties via the app properties or command line arguments. ==== Composed Task Runner Spring Cloud Data Flow allows a user to create a directed graph where each node of the graph is a task application and this is done via the https://github.com/spring-cloud-task-app-starters/composed-task-runner/blob/master/spring-cloud-starter-task-composedtaskrunner/README.adoc[Composed Task Runner]. In this case the rules that applied to a <> or <> apply to the composed task runner as well. All child apps must also have access to the datastore that is being used by the composed task runner Also, All child apps must have the same database dependency as the composed task runner enumerated in their `pom.xml` or `gradle.build` file. ==== Launching a task externally from Spring Cloud Data Flow Users may wish to launch Spring Cloud Task applications via another method (scheduler for example) but still track the task execution via Spring Cloud Data Flow. This can be done so long as the task applications observe the rules specified <> and <>. NOTE: If a user wishes to use Spring Cloud Data Flow to view their https://projects.spring.io/spring-batch/[Spring Batch] jobs, the user must make sure that their batch application use the `@EnableTask` annotation and follow the rules enumerated <> and <>. More information is available https://github.com/spring-projects/spring-batch-admin/blob/master/MIGRATION.md[here]. [[spring-cloud-dataflow-schedule-launch-tasks]] == Scheduling Tasks Spring Cloud Data Flow lets a user schedule the execution of tasks via a cron expression. A schedule can be created through the RESTful API or the Spring Cloud Data Flow UI. === The Scheduler Spring Cloud Data Flow will schedule the execution of its tasks via a scheduling agent that is available on the cloud platform. For example: on the Cloud Foundry platform Spring Cloud Data Flow will use the https://www.cloudfoundry.org/the-foundry/scheduler/[PCF Scheduler]. .Architectural Overview image::{dataflow-asciidoc}/images/dataflow-scheduling-architecture.png[Scheduler Architecture Overview, scaledwidth=""50%""] === Enabling Scheduling By default the Spring Cloud Data Flow leaves the scheduling feature disabled. To enable the scheduling feature the following feature properties must be set to `true`: * `spring.cloud.dataflow.features.schedules-enabled` * `spring.cloud.dataflow.features.tasks-enabled` === The Lifecycle of a Schedule The lifecycle of a schedule has 2 parts: * <> * <> [[spring-cloud-data-flow-schedule-scheduling]] ==== Scheduling a Task Execution You can schedule a task execution via the: * RESTful API * Spring Cloud Data Flow Dashboard To schedule a task from the UI click the Tasks tab at the top of the screen, this will take you to the Task Definitions screen. Then from the Task Definition that you wish to schedule click the ""clock"" icon associated with task definition you wish to schedule. This will lead you to a `Create Schedule(s)` screen, where you will create a unique name for the schedule and enter the associated cron expression. Keep in mind you can always create multiple schedules for a single task definition. [[spring-cloud-data-flow-schedule-unscheduling]] ==== Deleting a Schedule You can delete a schedule via the: * RESTful API * Spring Cloud Data Flow Dashboard To delete a schedule through the dashboard, select the Schedule tab under Tasks tab and click the `garbage can` icon next to the schedule you wish to delete. NOTE: Any currently running tasks that were run by the scheduling agent will not be stopped if the schedule is deleted. It only prevents future executions. ",12386,False,2264.6732708743502,median "[MusicConfig] Location=418562 ilem feat. zuotian - yi ren xing zhe/audio.mp3 Extension=mp3 MD5=08‌​1a‌​a0‌​c7‌​f2‌​e5‌​c5‌​62‌​1b‌​71‌​db‌​d8‌​5b‌​67‌​83‌​07 Source=OSU MetreNumber=4 Title=yi ren xing zhe [TagConfig] Tagger=Carra Time=2017/9/23 12:34:00 Confidence=4 [MiscConfig] LinkedFile=418562 ilem feat. zuotian - yi ren xing zhe/ilem feat. zuotian - yi ren xing zhe (Chick -X- Chick) [9Cirno's taiko oni].osu osuMapID=418562 MetadataLine1=Music by ilem MetadataLine2=Voice by zuotian BeatsPerSegment=16 RelativeMovingSpeed=0.7 [BeatInfo] Count=423 Beat_0={2.114,1,F Maj,F} Beat_1={2.614,0,F Maj,F} Beat_2={3.114,0,F Maj,F} Beat_3={3.614,0,F Maj,F} Beat_4={4.114,1,F Maj,F} Beat_5={4.614,0,F Maj,F} Beat_6={5.114,0,F Maj,F} Beat_7={5.614,0,F Maj,F} Beat_8={6.114,2,F Maj,F} Beat_9={6.614,0,F Maj,F} Beat_10={7.114,0,F Maj,F} Beat_11={7.614,0,F Maj,F} Beat_12={8.114,1,F Maj,C} Beat_13={8.614,0,F Maj,C} Beat_14={9.114,0,F Maj,C} Beat_15={9.614,0,F Maj,C} Beat_16={10.114,1,F Maj,Dm} Beat_17={10.614,0,F Maj,Dm} Beat_18={11.114,0,F Maj,Dm} Beat_19={11.614,0,F Maj,Dm} Beat_20={12.114,1,F Maj,Bb} Beat_21={12.614,0,F Maj,Bb} Beat_22={13.114,0,F Maj,Bb} Beat_23={13.614,0,F Maj,Bb} Beat_24={14.114,1,F Maj,F} Beat_25={14.614,0,F Maj,F} Beat_26={15.114,0,F Maj,F} Beat_27={15.614,0,F Maj,F} Beat_28={16.114,1,F Maj,C} Beat_29={16.614,0,F Maj,C} Beat_30={17.114,0,F Maj,C} Beat_31={17.614,0,F Maj,C} Beat_32={18.114,1,F Maj,Bb/D} Beat_33={18.614,0,F Maj,Bb/D} Beat_34={19.114,0,F Maj,Bb/D} Beat_35={19.614,0,F Maj,Bb/D} Beat_36={20.114,1,F Maj,Bbsus2} Beat_37={20.614,0,F Maj,Bbsus2} Beat_38={21.114,0,F Maj,Csus4} Beat_39={21.614,0,F Maj,Csus4} Beat_40={22.114,1,F Maj,F} Beat_41={22.614,0,F Maj,F} Beat_42={23.114,0,F Maj,F} Beat_43={23.614,0,F Maj,F} Beat_44={24.114,1,F Maj,F} Beat_45={24.614,0,F Maj,F} Beat_46={25.114,0,F Maj,F} Beat_47={25.614,0,F Maj,F} Beat_48={26.114,1,F Maj,C/E} Beat_49={26.614,0,F Maj,C/E} Beat_50={27.114,0,F Maj,C/E} Beat_51={27.614,0,F Maj,C/E} Beat_52={28.114,1,F Maj,C/E} Beat_53={28.614,0,F Maj,C/E} Beat_54={29.114,0,F Maj,C/E} Beat_55={29.614,0,F Maj,C/E} Beat_56={30.114,1,F Maj,Dm} Beat_57={30.614,0,F Maj,Dm} Beat_58={31.114,0,F Maj,Dm} Beat_59={31.614,0,F Maj,Dm} Beat_60={32.114,1,F Maj,Dm} Beat_61={32.614,0,F Maj,Dm} Beat_62={33.114,0,F Maj,Dm} Beat_63={33.614,0,F Maj,Dm} Beat_64={34.114,1,F Maj,Bbsus2} Beat_65={34.614,0,F Maj,Bbsus2} Beat_66={35.114,0,F Maj,Bbsus2} Beat_67={35.614,0,F Maj,Bbsus2} Beat_68={36.114,1,F Maj,Csus4} Beat_69={36.614,0,F Maj,Csus4} Beat_70={37.114,0,F Maj,Csus4} Beat_71={37.614,0,F Maj,Csus4} Beat_72={38.114,1,F Maj,F} Beat_73={38.614,0,F Maj,F} Beat_74={39.114,0,F Maj,F} Beat_75={39.614,0,F Maj,F} Beat_76={40.114,1,F Maj,F} Beat_77={40.614,0,F Maj,F} Beat_78={41.114,0,F Maj,F} Beat_79={41.614,0,F Maj,F} Beat_80={42.114,1,F Maj,C/E} Beat_81={42.614,0,F Maj,C/E} Beat_82={43.114,0,F Maj,C/E} Beat_83={43.614,0,F Maj,C/E} Beat_84={44.114,1,F Maj,C/E} Beat_85={44.614,0,F Maj,C/E} Beat_86={45.114,0,F Maj,C/E} Beat_87={45.614,0,F Maj,C/E} Beat_88={46.114,1,F Maj,Dm} Beat_89={46.614,0,F Maj,Dm} Beat_90={47.114,0,F Maj,Dm} Beat_91={47.614,0,F Maj,Dm} Beat_92={48.114,1,F Maj,Dm} Beat_93={48.614,0,F Maj,Dm} Beat_94={49.114,0,F Maj,Dm} Beat_95={49.614,0,F Maj,Dm} Beat_96={50.114,1,F Maj,Bbsus2} Beat_97={50.614,0,F Maj,Bbsus2} Beat_98={51.114,0,F Maj,Bbsus2} Beat_99={51.614,0,F Maj,Bbsus2} Beat_100={52.114,1,F Maj,Csus4} Beat_101={52.614,0,F Maj,Csus4} Beat_102={53.114,0,F Maj,Csus4} Beat_103={53.614,0,F Maj,Csus4} Beat_104={54.114,1,F Maj,F} Beat_105={54.614,0,F Maj,F} Beat_106={55.114,0,F Maj,F} Beat_107={55.614,0,F Maj,F} Beat_108={56.114,1,F Maj,C} Beat_109={56.614,0,F Maj,C} Beat_110={57.114,0,F Maj,C} Beat_111={57.614,0,F Maj,C} Beat_112={58.114,1,F Maj,Dm} Beat_113={58.614,0,F Maj,Dm} Beat_114={59.114,0,F Maj,Dm} Beat_115={59.614,0,F Maj,Dm} Beat_116={60.114,1,F Maj,Bb} Beat_117={60.614,0,F Maj,Bb} Beat_118={61.114,0,F Maj,Bb} Beat_119={61.614,0,F Maj,Bb} Beat_120={62.114,1,F Maj,F} Beat_121={62.614,0,F Maj,F} Beat_122={63.114,0,F Maj,F} Beat_123={63.614,0,F Maj,F} Beat_124={64.114,1,F Maj,C} Beat_125={64.614,0,F Maj,C} Beat_126={65.114,0,F Maj,C} Beat_127={65.614,0,F Maj,C} Beat_128={66.114,1,F Maj,Bb/D} Beat_129={66.614,0,F Maj,Bb/D} Beat_130={67.114,0,F Maj,Bb/D} Beat_131={67.614,0,F Maj,Bb/D} Beat_132={68.114,1,F Maj,Bbsus2} Beat_133={68.614,0,F Maj,Bbsus2} Beat_134={69.114,0,F Maj,Csus4} Beat_135={69.614,0,F Maj,Csus4} Beat_136={70.114,1,F Maj,F} Beat_137={70.614,0,F Maj,F} Beat_138={71.114,0,F Maj,F} Beat_139={71.614,0,F Maj,F} Beat_140={72.114,1,F Maj,C} Beat_141={72.614,0,F Maj,C} Beat_142={73.114,0,F Maj,C} Beat_143={73.614,0,F Maj,C} Beat_144={74.114,1,F Maj,Dm} Beat_145={74.614,0,F Maj,Dm} Beat_146={75.114,0,F Maj,Dm} Beat_147={75.614,0,F Maj,Dm} Beat_148={76.114,1,F Maj,Bb} Beat_149={76.614,0,F Maj,Bb} Beat_150={77.114,0,F Maj,Bb} Beat_151={77.614,0,F Maj,Bb} Beat_152={78.114,1,F Maj,F} Beat_153={78.614,0,F Maj,F} Beat_154={79.114,0,F Maj,F} Beat_155={79.614,0,F Maj,F} Beat_156={80.114,1,F Maj,C} Beat_157={80.614,0,F Maj,C} Beat_158={81.114,0,F Maj,C} Beat_159={81.614,0,F Maj,C} Beat_160={82.114,1,F Maj,Bb/D} Beat_161={82.614,0,F Maj,Bb/D} Beat_162={83.114,0,F Maj,Bb/D} Beat_163={83.614,0,F Maj,Bb/D} Beat_164={84.114,1,F Maj,Bbsus2} Beat_165={84.614,0,F Maj,Bbsus2} Beat_166={85.114,0,F Maj,Csus4} Beat_167={85.614,0,F Maj,Csus4} Beat_168={86.114,1,F Maj,Fm} Beat_169={86.614,0,F Maj,Fm} Beat_170={87.114,0,F Maj,Fm} Beat_171={87.614,0,F Maj,Fm} Beat_172={88.114,1,F Maj,Eb6} Beat_173={88.614,0,F Maj,Eb6} Beat_174={89.114,0,F Maj,Eb6} Beat_175={89.614,0,F Maj,Eb6} Beat_176={90.114,1,F Maj,F} Beat_177={90.614,0,F Maj,F} Beat_178={91.114,0,F Maj,F} Beat_179={91.614,0,F Maj,F} Beat_180={92.114,1,F Maj,F} Beat_181={92.614,0,F Maj,F} Beat_182={93.114,0,F Maj,Eb6} Beat_183={93.614,0,F Maj,Eb6} Beat_184={94.114,1,F Maj,Fm} Beat_185={94.614,0,F Maj,Fm} Beat_186={95.114,0,F Maj,Fm} Beat_187={95.614,0,F Maj,Fm} Beat_188={96.114,1,F Maj,Eb6} Beat_189={96.614,0,F Maj,Eb6} Beat_190={97.114,0,F Maj,Eb6} Beat_191={97.614,0,F Maj,Eb6} Beat_192={98.114,1,F Maj,F} Beat_193={98.614,0,F Maj,F} Beat_194={99.114,0,F Maj,F} Beat_195={99.614,0,F Maj,F} Beat_196={100.114,1,F Maj,F} Beat_197={100.614,0,F Maj,F} Beat_198={101.114,0,F Maj,F} Beat_199={101.614,0,F Maj,F} Beat_200={102.114,1,F Maj,F} Beat_201={102.614,0,F Maj,F} Beat_202={103.114,0,F Maj,F} Beat_203={103.614,0,F Maj,F} Beat_204={104.114,1,F Maj,F} Beat_205={104.614,0,F Maj,F} Beat_206={105.114,0,F Maj,F} Beat_207={105.614,0,F Maj,F} Beat_208={106.114,1,F Maj,C/E} Beat_209={106.614,0,F Maj,C/E} Beat_210={107.114,0,F Maj,C/E} Beat_211={107.614,0,F Maj,C/E} Beat_212={108.114,1,F Maj,C/E} Beat_213={108.614,0,F Maj,C/E} Beat_214={109.114,0,F Maj,C/E} Beat_215={109.614,0,F Maj,C/E} Beat_216={110.114,1,F Maj,Dm} Beat_217={110.614,0,F Maj,Dm} Beat_218={111.114,0,F Maj,Dm} Beat_219={111.614,0,F Maj,Dm} Beat_220={112.114,1,F Maj,Dm} Beat_221={112.614,0,F Maj,Dm} Beat_222={113.114,0,F Maj,Dm} Beat_223={113.614,0,F Maj,Dm} Beat_224={114.114,1,F Maj,Bbsus2} Beat_225={114.614,0,F Maj,Bbsus2} Beat_226={115.114,0,F Maj,Bbsus2} Beat_227={115.614,0,F Maj,Bbsus2} Beat_228={116.114,1,F Maj,Csus4} Beat_229={116.614,0,F Maj,Csus4} Beat_230={117.114,0,F Maj,Csus4} Beat_231={117.614,0,F Maj,Csus4} Beat_232={118.114,1,F Maj,F} Beat_233={118.614,0,F Maj,F} Beat_234={119.114,0,F Maj,F} Beat_235={119.614,0,F Maj,F} Beat_236={120.114,1,F Maj,F} Beat_237={120.614,0,F Maj,F} Beat_238={121.114,0,F Maj,F} Beat_239={121.614,0,F Maj,F} Beat_240={122.114,1,F Maj,C/E} Beat_241={122.614,0,F Maj,C/E} Beat_242={123.114,0,F Maj,C/E} Beat_243={123.614,0,F Maj,C/E} Beat_244={124.114,1,F Maj,C/E} Beat_245={124.614,0,F Maj,C/E} Beat_246={125.114,0,F Maj,C/E} Beat_247={125.614,0,F Maj,C/E} Beat_248={126.114,1,F Maj,Dm} Beat_249={126.614,0,F Maj,Dm} Beat_250={127.114,0,F Maj,Dm} Beat_251={127.614,0,F Maj,Dm} Beat_252={128.114,1,F Maj,Dm} Beat_253={128.614,0,F Maj,Dm} Beat_254={129.114,0,F Maj,Dm} Beat_255={129.614,0,F Maj,Dm} Beat_256={130.114,1,F Maj,Bbsus2} Beat_257={130.614,0,F Maj,Bbsus2} Beat_258={131.114,0,F Maj,Bbsus2} Beat_259={131.614,0,F Maj,Bbsus2} Beat_260={132.114,1,F Maj,Csus4} Beat_261={132.614,0,F Maj,Csus4} Beat_262={133.114,0,F Maj,Csus4} Beat_263={133.614,0,F Maj,Csus4} Beat_264={134.114,1,F Maj,F} Beat_265={134.614,0,F Maj,F} Beat_266={135.114,0,F Maj,F} Beat_267={135.614,0,F Maj,F} Beat_268={136.114,1,F Maj,C} Beat_269={136.614,0,F Maj,C} Beat_270={137.114,0,F Maj,C} Beat_271={137.614,0,F Maj,C} Beat_272={138.114,1,F Maj,Dm} Beat_273={138.614,0,F Maj,Dm} Beat_274={139.114,0,F Maj,Dm} Beat_275={139.614,0,F Maj,Dm} Beat_276={140.114,1,F Maj,Bb} Beat_277={140.614,0,F Maj,Bb} Beat_278={141.114,0,F Maj,Bb} Beat_279={141.614,0,F Maj,Bb} Beat_280={142.114,1,F Maj,F} Beat_281={142.614,0,F Maj,F} Beat_282={143.114,0,F Maj,F} Beat_283={143.614,0,F Maj,F} Beat_284={144.114,1,F Maj,C} Beat_285={144.614,0,F Maj,C} Beat_286={145.114,0,F Maj,C} Beat_287={145.614,0,F Maj,C} Beat_288={146.114,1,F Maj,Bb/D} Beat_289={146.614,0,F Maj,Bb/D} Beat_290={147.114,0,F Maj,Bb/D} Beat_291={147.614,0,F Maj,Bb/D} Beat_292={148.114,1,F Maj,Bbsus2} Beat_293={148.614,0,F Maj,Bbsus2} Beat_294={149.114,0,F Maj,Csus4} Beat_295={149.614,0,F Maj,Csus4} Beat_296={150.114,1,F Maj,F} Beat_297={150.614,0,F Maj,F} Beat_298={151.114,0,F Maj,F} Beat_299={151.614,0,F Maj,F} Beat_300={152.114,1,F Maj,C} Beat_301={152.614,0,F Maj,C} Beat_302={153.114,0,F Maj,C} Beat_303={153.614,0,F Maj,C} Beat_304={154.114,1,F Maj,Dm} Beat_305={154.614,0,F Maj,Dm} Beat_306={155.114,0,F Maj,Dm} Beat_307={155.614,0,F Maj,Dm} Beat_308={156.114,1,F Maj,Bb} Beat_309={156.614,0,F Maj,Bb} Beat_310={157.114,0,F Maj,Bb} Beat_311={157.614,0,F Maj,Bb} Beat_312={158.114,1,F Maj,F} Beat_313={158.614,0,F Maj,F} Beat_314={159.114,0,F Maj,F} Beat_315={159.614,0,F Maj,F} Beat_316={160.114,1,F Maj,C} Beat_317={160.614,0,F Maj,C} Beat_318={161.114,0,F Maj,C} Beat_319={161.614,0,F Maj,C} Beat_320={162.114,1,F Maj,Bb/D} Beat_321={162.614,0,F Maj,Bb/D} Beat_322={163.114,0,F Maj,Bb/D} Beat_323={163.614,0,F Maj,Bb/D} Beat_324={164.114,1,F Maj,Bbsus2} Beat_325={164.614,0,F Maj,Bbsus2} Beat_326={165.114,0,F Maj,Csus4} Beat_327={165.614,0,F Maj,Csus4} Beat_328={166.114,1,F Maj,Fm} Beat_329={166.614,0,F Maj,Fm} Beat_330={167.114,0,F Maj,Fm} Beat_331={167.614,0,F Maj,Fm} Beat_332={168.114,1,F Maj,Eb6} Beat_333={168.614,0,F Maj,Eb6} Beat_334={169.114,0,F Maj,Eb6} Beat_335={169.614,0,F Maj,Eb6} Beat_336={170.114,1,F Maj,F} Beat_337={170.614,0,F Maj,F} Beat_338={171.114,0,F Maj,F} Beat_339={171.614,0,F Maj,F} Beat_340={172.114,1,F Maj,F} Beat_341={172.614,0,F Maj,F} Beat_342={173.114,0,F Maj,Eb6} Beat_343={173.614,0,F Maj,Eb6} Beat_344={174.114,1,F Maj,Fm} Beat_345={174.614,0,F Maj,Fm} Beat_346={175.114,0,F Maj,Fm} Beat_347={175.614,0,F Maj,Fm} Beat_348={176.114,1,F Maj,Eb6} Beat_349={176.614,0,F Maj,Eb6} Beat_350={177.114,0,F Maj,Eb6} Beat_351={177.614,0,F Maj,Eb6} Beat_352={178.114,1,F Maj,F} Beat_353={178.614,0,F Maj,F} Beat_354={179.114,0,F Maj,F} Beat_355={179.614,0,F Maj,F} Beat_356={180.114,1,F Maj,F} Beat_357={180.614,0,F Maj,F} Beat_358={181.114,0,F Maj,F} Beat_359={181.614,0,F Maj,F} Beat_360={182.114,1,G Maj,G} Beat_361={182.614,0,G Maj,G} Beat_362={183.114,0,G Maj,G} Beat_363={183.614,0,G Maj,G} Beat_364={184.114,1,G Maj,D} Beat_365={184.614,0,G Maj,D} Beat_366={185.114,0,G Maj,D} Beat_367={185.614,0,G Maj,D} Beat_368={186.114,1,G Maj,Em} Beat_369={186.614,0,G Maj,Em} Beat_370={187.114,0,G Maj,Em} Beat_371={187.614,0,G Maj,Em} Beat_372={188.114,1,G Maj,C} Beat_373={188.614,0,G Maj,C} Beat_374={189.114,0,G Maj,C} Beat_375={189.614,0,G Maj,C} Beat_376={190.114,1,G Maj,G} Beat_377={190.614,0,G Maj,G} Beat_378={191.114,0,G Maj,G} Beat_379={191.614,0,G Maj,G} Beat_380={192.114,1,G Maj,D} Beat_381={192.614,0,G Maj,D} Beat_382={193.114,0,G Maj,D} Beat_383={193.614,0,G Maj,D} Beat_384={194.114,1,G Maj,C/E} Beat_385={194.614,0,G Maj,C/E} Beat_386={195.114,0,G Maj,C/E} Beat_387={195.614,0,G Maj,C/E} Beat_388={196.114,1,G Maj,Csus2} Beat_389={196.614,0,G Maj,Csus2} Beat_390={197.114,0,G Maj,Dsus4} Beat_391={197.614,0,G Maj,Dsus4} Beat_392={198.114,1,G Maj,EbM7} Beat_393={198.614,0,G Maj,EbM7} Beat_394={199.114,0,G Maj,EbM7} Beat_395={199.614,0,G Maj,EbM7} Beat_396={200.114,1,G Maj,F6} Beat_397={200.614,0,G Maj,F6} Beat_398={201.114,0,G Maj,F6} Beat_399={201.614,0,G Maj,F6} Beat_400={202.114,1,G Maj,G} Beat_401={202.614,0,G Maj,G} Beat_402={203.114,0,G Maj,G} Beat_403={203.614,0,G Maj,G} Beat_404={204.114,1,G Maj,G} Beat_405={204.614,0,G Maj,G} Beat_406={205.114,0,G Maj,F6} Beat_407={205.614,0,G Maj,F6} Beat_408={206.114,1,G Maj,Gm} Beat_409={206.614,0,G Maj,Gm} Beat_410={207.114,0,G Maj,Gm} Beat_411={207.614,0,G Maj,Gm} Beat_412={208.114,1,G Maj,F6} Beat_413={208.614,0,G Maj,F6} Beat_414={209.114,0,G Maj,F6} Beat_415={209.614,0,G Maj,F6} Beat_416={210.114,1,G Maj,N} Beat_417={210.614,0,G Maj,N} Beat_418={211.114,0,G Maj,N} Beat_419={211.614,0,G Maj,N} Beat_420={212.114,1,G Maj,N} Beat_421={212.614,0,G Maj,N} Beat_422={213.114,0,F Maj,N} ",8364,True,3227.425846695908,median "[MusicConfig] Location=42488 Yanni - November Sky/November Sky.mp3 Extension=mp3 MD5=f1‌​a0‌​55‌​d1‌​93‌​90‌​ce‌​b8‌​28‌​b4‌​d1‌​6c‌​0f‌​55‌​46‌​69 Source=OSU MetreNumber=4 Title=November Sky [TagConfig] Tagger=Carra Time=2016/9/5 22:00:11 Confidence=4 [MiscConfig] LinkedFile=42488 Yanni - November Sky/Yanni - November Sky (kazumikos) [Advanced].osu osuMapID=42488 [BeatInfo] Count=269 Beat_0={7.138,1,A min,Am} Beat_1={7.7813626420759174,0,A min,Am} Beat_2={8.424725284151835,0,A min,Am} Beat_3={9.0680879262277525,0,A min,Am} Beat_4={9.71145056830367,1,A min,Am} Beat_5={10.354813210379588,0,A min,Am} Beat_6={10.998175852455505,0,A min,Am} Beat_7={11.641538494531423,0,A min,Am} Beat_8={12.28490113660734,1,A min,Am} Beat_9={12.928263778683258,0,A min,Am} Beat_10={13.571626420759175,0,A min,Am} Beat_11={14.214989062835093,0,A min,Am} Beat_12={14.85835170491101,1,A min,Am} Beat_13={15.501714346986928,0,A min,Am} Beat_14={16.145076989062844,0,A min,Am} Beat_15={16.788439631138761,0,A min,Am} Beat_16={17.431802273214679,1,A min,Am} Beat_17={18.075164915290596,0,A min,Am} Beat_18={18.718527557366514,0,A min,Am} Beat_19={19.361890199442431,0,A min,Am} Beat_20={20.005252841518349,1,A min,Dm} Beat_21={20.648615483594266,0,A min,Dm} Beat_22={21.291978125670184,0,A min,Dm} Beat_23={21.9353407677461,0,A min,Dm} Beat_24={22.578703409822019,1,A min,G} Beat_25={23.222066051897936,0,A min,G} Beat_26={23.865428693973854,0,A min,G} Beat_27={24.508791336049772,0,A min,G} Beat_28={25.152153978125689,1,A min,Am} Beat_29={25.795516620201607,0,A min,Am} Beat_30={26.438879262277524,0,A min,Am} Beat_31={27.082241904353442,0,A min,Am} Beat_32={27.725604546429359,1,A min,Am} Beat_33={28.368967188505277,0,A min,Am} Beat_34={29.012329830581194,0,A min,Am} Beat_35={29.655692472657112,0,A min,Am} Beat_36={30.299055114733029,1,A min,Dm} Beat_37={30.942417756808947,0,A min,Dm} Beat_38={31.585780398884864,0,A min,Dm} Beat_39={32.229143040960778,0,A min,Dm} Beat_40={32.872505683036692,1,A min,G} Beat_41={33.515868325112606,0,A min,G} Beat_42={34.15923096718852,0,A min,G} Beat_43={34.802593609264434,0,A min,G} Beat_44={35.445956251340348,1,A min,C} Beat_45={36.089318893416262,0,A min,C} Beat_46={36.732681535492176,0,A min,C} Beat_47={37.37604417756809,0,A min,C} Beat_48={38.019406819644004,1,A min,F} Beat_49={38.662769461719918,0,A min,F} Beat_50={39.306132103795832,0,A min,G} Beat_51={39.949494745871746,0,A min,G} Beat_52={40.59285738794766,1,A min,Em} Beat_53={41.236220030023574,0,A min,Em} Beat_54={41.879582672099488,0,A min,Am} Beat_55={42.5229453141754,0,A min,Am} Beat_56={43.166307956251316,1,A min,Dm} Beat_57={43.80967059832723,0,A min,Dm} Beat_58={44.453033240403144,0,A min,Dm} Beat_59={45.096395882479058,0,A min,Dm} Beat_60={45.739758524554972,1,A min,G} Beat_61={46.383121166630886,0,A min,G} Beat_62={47.0264838087068,0,A min,G} Beat_63={47.669846450782714,0,A min,G} Beat_64={48.313209092858628,1,A min,C} Beat_65={48.956571734934542,0,A min,C} Beat_66={49.599934377010456,0,A min,C} Beat_67={50.24329701908637,0,A min,C} Beat_68={50.886659661162284,1,A min,C} Beat_69={51.5300223032382,0,A min,C} Beat_70={52.173384945314112,0,A min,C} Beat_71={52.816747587390026,0,A min,C} Beat_72={53.46011022946594,1,A min,Am} Beat_73={54.103472871541854,0,A min,Am} Beat_74={54.746835513617768,0,A min,Am} Beat_75={55.390198155693682,0,A min,Am} Beat_76={56.033560797769596,1,A min,Em} Beat_77={56.67692343984551,0,A min,Em} Beat_78={57.320286081921424,0,A min,Em} Beat_79={57.963648723997338,0,A min,Em} Beat_80={58.607011366073252,1,A min,Am} Beat_81={59.250374008149166,0,A min,Am} Beat_82={59.89373665022508,0,A min,Am} Beat_83={60.537099292300994,0,A min,Am} Beat_84={61.180461934376908,1,A min,Em} Beat_85={61.823824576452822,0,A min,Em} Beat_86={62.467187218528736,0,A min,Em} Beat_87={63.11054986060465,0,A min,Em} Beat_88={63.753912502680564,1,A min,Am} Beat_89={64.397275144756478,0,A min,Am} Beat_90={65.040637786832392,0,A min,Am} Beat_91={65.6840004289083,0,A min,Am} Beat_92={66.327363070984219,1,A min,Em} Beat_93={66.970725713060133,0,A min,Em} Beat_94={67.614088355136047,0,A min,Em} Beat_95={68.257450997211961,0,A min,Em} Beat_96={68.900813639287875,1,A min,Em} Beat_97={69.544176281363789,0,A min,Em} Beat_98={70.1875389234397,0,A min,Em} Beat_99={70.830901565515617,0,A min,Em} Beat_100={71.474264207591531,1,A min,F} Beat_101={72.117626849667445,0,A min,F} Beat_102={72.760989491743359,0,A min,F} Beat_103={73.404352133819273,0,A min,F} Beat_104={74.047714775895187,1,A min,G} Beat_105={74.6910774179711,0,A min,G} Beat_106={75.334440060047015,0,A min,G} Beat_107={75.977802702122929,0,A min,G} Beat_108={76.621165344198843,1,A min,F} Beat_109={77.264527986274757,0,A min,F} Beat_110={77.907890628350671,0,A min,F} Beat_111={78.551253270426585,0,A min,F} Beat_112={79.1946159125025,1,A min,G} Beat_113={79.837978554578413,0,A min,G} Beat_114={80.481341196654327,0,A min,G} Beat_115={81.124703838730241,0,A min,G} Beat_116={81.768066480806155,1,A min,Am} Beat_117={82.411429122882069,0,A min,Am} Beat_118={83.054791764957983,0,A min,Em} Beat_119={83.6981544070339,0,A min,Em} Beat_120={84.341517049109811,1,A min,Am} Beat_121={84.984879691185725,0,A min,Am} Beat_122={85.628242333261639,0,A min,G} Beat_123={86.271604975337553,0,A min,G} Beat_124={86.914967617413467,1,A min,Am} Beat_125={87.558330259489381,0,A min,Am} Beat_126={88.2016929015653,0,A min,Em} Beat_127={88.845055543641209,0,A min,Em} Beat_128={89.488418185717123,1,A min,Am} Beat_129={90.131780827793037,0,A min,Am} Beat_130={90.775143469868951,0,A min,C} Beat_131={91.418506111944865,0,A min,C} Beat_132={92.061868754020779,1,A min,G} Beat_133={92.705231396096693,0,A min,G} Beat_134={93.3485940381726,0,A min,G} Beat_135={93.991956680248521,0,A min,G} Beat_136={94.635319322324435,1,A min,G} Beat_137={95.278681964400349,0,A min,G} Beat_138={95.922044606476263,0,A min,G} Beat_139={96.565407248552177,0,A min,G} Beat_140={97.208769890628091,1,A min,Am} Beat_141={97.852132532704,0,A min,Am} Beat_142={98.495495174779919,0,A min,Am} Beat_143={99.138857816855833,0,A min,Am} Beat_144={99.782220458931747,1,A min,Dm} Beat_145={100.42558310100766,0,A min,Dm} Beat_146={101.06894574308357,0,A min,Dm} Beat_147={101.71230838515949,0,A min,Dm} Beat_148={102.3556710272354,1,A min,G} Beat_149={102.99903366931132,0,A min,G} Beat_150={103.64239631138723,0,A min,G} Beat_151={104.28575895346314,0,A min,G} Beat_152={104.92912159553906,1,A min,Am} Beat_153={105.57248423761497,0,A min,Am} Beat_154={106.21584687969089,0,A min,Am} Beat_155={106.8592095217668,0,A min,Am} Beat_156={107.50257216384271,1,A min,Am} Beat_157={108.14593480591863,0,A min,Am} Beat_158={108.78929744799454,0,A min,Am} Beat_159={109.43266009007046,0,A min,Am} Beat_160={110.07602273214637,1,A min,Dm} Beat_161={110.71938537422228,0,A min,Dm} Beat_162={111.3627480162982,0,A min,Dm} Beat_163={112.00611065837411,0,A min,Dm} Beat_164={112.64947330045003,1,A min,G} Beat_165={113.29283594252594,0,A min,G} Beat_166={113.93619858460185,0,A min,G} Beat_167={114.57956122667777,0,A min,G} Beat_168={115.22292386875368,1,A min,C} Beat_169={115.8662865108296,0,A min,C} Beat_170={116.50964915290551,0,A min,C} Beat_171={117.15301179498142,0,A min,C} Beat_172={117.79637443705734,1,A min,F} Beat_173={118.43973707913325,0,A min,F} Beat_174={119.08309972120917,0,A min,G} Beat_175={119.72646236328508,0,A min,G} Beat_176={120.369825005361,1,A min,Em} Beat_177={121.01318764743691,0,A min,Em} Beat_178={121.65655028951282,0,A min,Am} Beat_179={122.29991293158874,0,A min,Am} Beat_180={122.94327557366465,1,A min,Dm} Beat_181={123.58663821574056,0,A min,Dm} Beat_182={124.23000085781648,0,A min,Dm} Beat_183={124.87336349989239,0,A min,Dm} Beat_184={125.51672614196831,1,A min,G} Beat_185={126.16008878404422,0,A min,G} Beat_186={126.80345142612013,0,A min,G} Beat_187={127.44681406819605,0,A min,G} Beat_188={128.09017671027198,1,A min,C} Beat_189={128.73353935234789,0,A min,C} Beat_190={129.3769019944238,0,A min,C} Beat_191={130.02026463649972,0,A min,C} Beat_192={130.66362727857563,1,A min,C} Beat_193={131.30698992065155,0,A min,C} Beat_194={131.95035256272746,0,A min,C} Beat_195={132.59371520480337,0,A min,C} Beat_196={133.23707784687929,1,A min,Am} Beat_197={133.8804404889552,0,A min,Am} Beat_198={134.52380313103112,0,A min,Am} Beat_199={135.16716577310703,0,A min,Am} Beat_200={135.81052841518294,1,A min,Em} Beat_201={136.45389105725886,0,A min,Em} Beat_202={137.09725369933477,0,A min,Em} Beat_203={137.74061634141069,0,A min,Em} Beat_204={138.3839789834866,1,A min,Am} Beat_205={139.02734162556251,0,A min,Am} Beat_206={139.67070426763843,0,A min,Am} Beat_207={140.31406690971434,0,A min,Am} Beat_208={140.95742955179026,1,A min,Em} Beat_209={141.60079219386617,0,A min,Em} Beat_210={142.24415483594208,0,A min,Em} Beat_211={142.887517478018,0,A min,Em} Beat_212={143.53088012009391,1,A min,Am} Beat_213={144.17424276216983,0,A min,Am} Beat_214={144.81760540424574,0,A min,Am} Beat_215={145.46096804632165,0,A min,Am} Beat_216={146.10433068839757,1,A min,Em} Beat_217={146.74769333047348,0,A min,Em} Beat_218={147.3910559725494,0,A min,Em} Beat_219={148.03441861462531,0,A min,Em} Beat_220={148.67778125670122,1,A min,Em} Beat_221={149.32114389877714,0,A min,Em} Beat_222={149.96450654085305,0,A min,Em} Beat_223={150.60786918292897,0,A min,Em} Beat_224={151.25123182500488,1,A min,F} Beat_225={151.89459446708079,0,A min,F} Beat_226={152.53795710915671,0,A min,F} Beat_227={153.18131975123262,0,A min,F} Beat_228={153.82468239330854,1,A min,G} Beat_229={154.46804503538445,0,A min,G} Beat_230={155.11140767746036,0,A min,G} Beat_231={155.75477031953628,0,A min,G} Beat_232={156.39813296161219,1,A min,F} Beat_233={157.04149560368811,0,A min,F} Beat_234={157.68485824576402,0,A min,F} Beat_235={158.32822088783993,0,A min,F} Beat_236={158.97158352991585,1,A min,G} Beat_237={159.61494617199176,0,A min,G} Beat_238={160.25830881406768,0,A min,G} Beat_239={160.90167145614359,0,A min,G} Beat_240={161.5450340982195,1,A min,Am} Beat_241={162.18839674029542,0,A min,Am} Beat_242={162.83175938237133,0,A min,Em} Beat_243={163.47512202444725,0,A min,Em} Beat_244={164.11848466652316,1,A min,Am} Beat_245={164.76184730859907,0,A min,Am} Beat_246={165.405209950675,0,A min,G} Beat_247={166.0485725927509,0,A min,G} Beat_248={166.69193523482682,1,A min,Am} Beat_249={167.33529787690273,0,A min,Am} Beat_250={167.97866051897864,0,A min,Em} Beat_251={168.62202316105456,0,A min,Em} Beat_252={169.26538580313047,1,A min,Am} Beat_253={169.90874844520639,0,A min,Am} Beat_254={170.5521110872823,0,A min,Em} Beat_255={171.19547372935821,0,A min,Em} Beat_256={171.83883637143413,1,A min,Am} Beat_257={172.48219901351004,0,A min,Am} Beat_258={173.12556165558596,0,A min,Em} Beat_259={173.76892429766187,0,A min,Em} Beat_260={174.41228693973778,1,A min,Am} Beat_261={175.0556495818137,0,A min,Am} Beat_262={175.69901222388961,0,A min,G} Beat_263={176.34237486596553,0,A min,G} Beat_264={176.98573750804144,1,A min,Am} Beat_265={177.62910015011735,0,A min,Am} Beat_266={178.27246279219327,0,A min,Em} Beat_267={178.91582543426918,0,A min,Em} Beat_268={179.55918807634509,1,?,X} ",8252,True,3038.5304393160104,median "[[box-component]] = Box Component :docTitle: Box :artifactId: camel-box :description: Upload, download and manage files, folders, groups, collaborations, etc. on box.com. :since: 2.14 :supportLevel: Stable :component-header: Both producer and consumer are supported *Since Camel {since}* *{component-header}* The Box component provides access to all of the Box.com APIs accessible using https://github.com/box/box-java-sdk/[https://github.com/box/box-java-sdk]. It allows producing messages to upload and download files, create, edit, and manage folders, etc. It also supports APIs that allow polling for updates to user accounts and even changes to enterprise accounts, etc. Box.com requires the use of OAuth2.0 for all client application authentication. In order to use camel-box with your account, you'll need to create a new application within Box.com at https://developer.box.com/[https://developer.box.com]. The Box application's client id and secret will allow access to Box APIs which require a current user. A user access token is generated and managed by the API for an end user. Maven users will need to add the following dependency to their pom.xml for this component: [source,xml] ---- org.apache.camel camel-box ${camel-version} ---- == Connection Authentication Types The Box component supports three different types of authenticated connections. === Standard Authentication *Standard Authentication* uses the *OAuth 2.0 three-legged authentication process* to authenticate its connections with Box.com. This type of authentication enables Box *managed users* and *external users* to access, edit, and save their Box content through the Box component. === App Enterprise Authentication *App Enterprise Authentication* uses the *OAuth 2.0 with JSON Web Tokens (JWT)* to authenticate its connections as a *Service Account* for a *Box Application*. This type of authentication enables a service account to access, edit, and save the Box content of its *Box Application* through the Box component. === App User Authentication *App User Authentication* uses the *OAuth 2.0 with JSON Web Tokens (JWT)* to authenticate its connections as an *App User* for a *Box Application*. This type of authentication enables app users to access, edit, and save their Box content in its *Box Application* through the Box component. == Box Options // component options: START The Box component supports 19 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *clientId* (common) | Box application client ID | | String | *configuration* (common) | To use the shared configuration | | BoxConfiguration | *enterpriseId* (common) | The enterprise ID to use for an App Enterprise. | | String | *userId* (common) | The user ID to use for an App User. | | String | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *basicPropertyBinding* (advanced) | *Deprecated* Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *httpParams* (advanced) | Custom HTTP params for settings like proxy host | | Map | *authenticationType* (authentication) | The type of authentication for connection. Types of Authentication: STANDARD_AUTHENTICATION - OAuth 2.0 (3-legged) SERVER_AUTHENTICATION - OAuth 2.0 with JSON Web Tokens | APP_USER_AUTHENTICATION | String | *accessTokenCache* (security) | Custom Access Token Cache for storing and retrieving access tokens. | | IAccessTokenCache | *clientSecret* (security) | Box application client secret | | String | *encryptionAlgorithm* (security) | The type of encryption algorithm for JWT. Supported Algorithms: RSA_SHA_256 RSA_SHA_384 RSA_SHA_512. There are 3 enums and the value can be one of: RSA_SHA_256, RSA_SHA_384, RSA_SHA_512 | RSA_SHA_256 | EncryptionAlgorithm | *maxCacheEntries* (security) | The maximum number of access tokens in cache. | 100 | int | *privateKeyFile* (security) | The private key for generating the JWT signature. | | String | *privateKeyPassword* (security) | The password for the private key. | | String | *publicKeyId* (security) | The ID for public key for validating the JWT signature. | | String | *sslContextParameters* (security) | To configure security using SSLContextParameters. | | SSLContextParameters | *userName* (security) | Box user name, MUST be provided | | String | *userPassword* (security) | Box user password, MUST be provided if authSecureStorage is not set, or returns null on first call | | String |=== // component options: END // endpoint options: START The Box endpoint is configured using URI syntax: ---- box:apiName/methodName ---- with the following path and query parameters: === Path Parameters (2 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *apiName* | *Required* What kind of operation to perform. There are 10 enums and the value can be one of: COLLABORATIONS, COMMENTS, EVENT_LOGS, FILES, FOLDERS, GROUPS, EVENTS, SEARCH, TASKS, USERS | | BoxApiName | *methodName* | *Required* What sub operation to use for the selected operation | | String |=== === Query Parameters (21 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *clientId* (common) | Box application client ID | | String | *enterpriseId* (common) | The enterprise ID to use for an App Enterprise. | | String | *inBody* (common) | Sets the name of a parameter to be passed in the exchange In Body | | String | *userId* (common) | The user ID to use for an App User. | | String | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | | ExceptionHandler | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. There are 3 enums and the value can be one of: InOnly, InOut, InOptionalOut | | ExchangePattern | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *basicPropertyBinding* (advanced) | Whether the endpoint should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *httpParams* (advanced) | Custom HTTP params for settings like proxy host | | Map | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported). | false | boolean | *authenticationType* (authentication) | The type of authentication for connection. Types of Authentication: STANDARD_AUTHENTICATION - OAuth 2.0 (3-legged) SERVER_AUTHENTICATION - OAuth 2.0 with JSON Web Tokens | APP_USER_AUTHENTICATION | String | *accessTokenCache* (security) | Custom Access Token Cache for storing and retrieving access tokens. | | IAccessTokenCache | *clientSecret* (security) | Box application client secret | | String | *encryptionAlgorithm* (security) | The type of encryption algorithm for JWT. Supported Algorithms: RSA_SHA_256 RSA_SHA_384 RSA_SHA_512. There are 3 enums and the value can be one of: RSA_SHA_256, RSA_SHA_384, RSA_SHA_512 | RSA_SHA_256 | EncryptionAlgorithm | *maxCacheEntries* (security) | The maximum number of access tokens in cache. | 100 | int | *privateKeyFile* (security) | The private key for generating the JWT signature. | | String | *privateKeyPassword* (security) | The password for the private key. | | String | *publicKeyId* (security) | The ID for public key for validating the JWT signature. | | String | *sslContextParameters* (security) | To configure security using SSLContextParameters. | | SSLContextParameters | *userName* (security) | Box user name, MUST be provided | | String | *userPassword* (security) | Box user password, MUST be provided if authSecureStorage is not set, or returns null on first call | | String |=== === API Parameters (10 APIs): The Box endpoint is an API based component and has additional parameters based on which API name and API method is used. The API name and API method is located in the endpoint URI as the apiName/methodName path parameters: ---- box:apiName/methodName ---- There are 10 API names as listed in the table below: [width=""100%"",cols=""2,1,7"",options=""header""] |=== | API Name | Type | Description | *collaborations* | Producer | Provides operations to manage Box collaborations | *comments* | Producer | Provides operations to manage Box comments | *event-logs* | Producer | Provides operations to read Box enterprise (admin) event logs | *events* | Consumer | Provides operations to manage Box events | *files* | Producer | Provides operations to manage Box files | *folders* | Producer | Provides operations to manage Box folders | *groups* | Producer | Provides operations to manage Box groups | *search* | Producer | Provides operations to manage Box searches | *tasks* | Producer | Provides operations to manage Box tasks | *users* | Producer | Provides operations to manage Box users |=== Each API is documented in the following sections to come. ==== API: collaborations *Only producer is supported* The collaborations API has 6 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.BoxCollaboration addFolderCollaboration(String folderId, com.box.sdk.BoxCollaborator collaborator, com.box.sdk.BoxCollaboration.Role role); com.box.sdk.BoxCollaboration addFolderCollaborationByEmail(String folderId, String email, com.box.sdk.BoxCollaboration.Role role); void deleteCollaboration(String collaborationId); com.box.sdk.BoxCollaboration.Info getCollaborationInfo(String collaborationId); java.util.Collection getFolderCollaborations(String folderId); com.box.sdk.BoxCollaboration updateCollaborationInfo(String collaborationId, com.box.sdk.BoxCollaboration.Info info); ---- The collaborations API is defined in the syntax as follows: ---- box:collaborations/methodName?[parameters] ---- The 6 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *addFolderCollaboration* | add | Add a collaboration to this folder | *addFolderCollaborationByEmail* | addByEmail | Add a collaboration to this folder | *deleteCollaboration* | delete | Delete collaboration | *getCollaborationInfo* | info | Get collaboration information | *getFolderCollaborations* | collaborations | Get information about all of the collaborations for folder | *updateCollaborationInfo* | updateInfo | Update collaboration information |=== The collaborations API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | addFolderCollaboration | *collaborator* | The collaborator to add | BoxCollaborator | addFolderCollaboration | *folderId* | The id of folder to add collaboration to | String | addFolderCollaboration | *role* | The role of the collaborator | Role | addFolderCollaborationByEmail | *email* | The email address of the collaborator to add | String | addFolderCollaborationByEmail | *folderId* | The id of folder to add collaboration to | String | addFolderCollaborationByEmail | *role* | The role of the collaborator | Role | deleteCollaboration | *collaborationId* | The id of comment to change | String | getCollaborationInfo | *collaborationId* | The id of collaboration | String | getFolderCollaborations | *folderId* | The id of folder to get collaborations information on | String | updateCollaborationInfo | *collaborationId* | The id of collaboration | String | updateCollaborationInfo | *info* | | Info |=== In addition to the parameters above, the collaborations API can also use from the 21 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: comments *Only producer is supported* The comments API has 6 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.BoxFile addFileComment(String fileId, String message); com.box.sdk.BoxComment changeCommentMessage(String commentId, String message); void deleteComment(String commentId); com.box.sdk.BoxComment.Info getCommentInfo(String commentId); java.util.List getFileComments(String fileId); com.box.sdk.BoxComment replyToComment(String commentId, String message); ---- The comments API is defined in the syntax as follows: ---- box:comments/methodName?[parameters] ---- The 6 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *addFileComment* | add | Add comment to file | *changeCommentMessage* | updateMessage | Change comment message | *deleteComment* | delete | Delete comment | *getCommentInfo* | info | Get comment information | *getFileComments* | comments | Get a list of any comments on this file | *replyToComment* | reply | Reply to a comment |=== The comments API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | addFileComment | *fileId* | The id of file | String | addFileComment | *message* | The comment's message | String | changeCommentMessage | *commentId* | The id of comment to change | String | changeCommentMessage | *message* | The new message for the comment | String | deleteComment | *commentId* | The id of comment to delete | String | getCommentInfo | *commentId* | The id of comment | String | getFileComments | *fileId* | The id of file | String | replyToComment | *commentId* | The id of comment to reply to | String | replyToComment | *message* | The message for the reply | String |=== In addition to the parameters above, the comments API can also use from the 21 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: event-logs *Only producer is supported* The event-logs API has 1 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- java.util.List getEnterpriseEvents(String position, java.util.Date after, java.util.Date before, com.box.sdk.BoxEvent.Type[] types); ---- The event-logs API is defined in the syntax as follows: ---- box:event-logs/methodName?[parameters] ---- The 1 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *getEnterpriseEvents* | events | Create an event stream with optional starting initial position and add listener that will be notified when an event is received |=== The event-logs API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | getEnterpriseEvents | *after* | The lower bound on the timestamp of the events returned | Date | getEnterpriseEvents | *before* | The upper bound on the timestamp of the events returned | Date | getEnterpriseEvents | *position* | *Optional* The starting position of the event stream. May be null in which case all events within bounds returned. | String | getEnterpriseEvents | *types* | *Optional* An optional list of event types to filter by | Type[] |=== In addition to the parameters above, the event-logs API can also use from the 21 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: events *Only consumer is supported* The events API has 1 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- void listen(com.box.sdk.EventListener listener, Long startingPosition); ---- The events API is defined in the syntax as follows: ---- box:events/methodName?[parameters] ---- The 1 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *listen* | | Create an event stream with optional starting initial position and add listener that will be notified when an event is received |=== The events API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | listen | *startingPosition* | *Optional* The starting position of the event stream | Long |=== In addition to the parameters above, the events API can also use from the 21 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: files *Only producer is supported* The files API has 22 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- void checkUpload(String fileName, String parentFolderId, Long size); com.box.sdk.BoxFile copyFile(String fileId, String destinationFolderId, String newName); com.box.sdk.Metadata createFileMetadata(String fileId, com.box.sdk.Metadata metadata, String typeName); com.box.sdk.BoxSharedLink createFileSharedLink(String fileId, com.box.sdk.BoxSharedLink.Access access, java.util.Date unshareDate, com.box.sdk.BoxSharedLink.Permissions permissions); void deleteFile(String fileId); void deleteFileMetadata(String fileId); void deleteFileVersion(String fileId, Integer version); java.io.OutputStream downloadFile(String fileId, java.io.OutputStream output, Long rangeStart, Long rangeEnd, com.box.sdk.ProgressListener listener); java.io.OutputStream downloadPreviousFileVersion(String fileId, Integer version, java.io.OutputStream output, com.box.sdk.ProgressListener listener); java.net.URL getDownloadURL(String fileId); com.box.sdk.BoxFile.Info getFileInfo(String fileId, String[] fields); com.box.sdk.Metadata getFileMetadata(String fileId, String typeName); java.net.URL getFilePreviewLink(String fileId); byte[] getFileThumbnail(String fileId, com.box.sdk.BoxFile.ThumbnailFileType fileType, Integer minWidth, Integer minHeight, Integer maxWidth, Integer maxHeight); java.util.Collection getFileVersions(String fileId); com.box.sdk.BoxFile moveFile(String fileId, String destinationFolderId, String newName); com.box.sdk.BoxFileVersion promoteFileVersion(String fileId, Integer version); com.box.sdk.BoxFile renameFile(String fileId, String newFileName); com.box.sdk.BoxFile updateFileInfo(String fileId, com.box.sdk.BoxFile.Info info); com.box.sdk.Metadata updateFileMetadata(String fileId, com.box.sdk.Metadata metadata); com.box.sdk.BoxFile uploadFile(String parentFolderId, java.io.InputStream content, String fileName, java.util.Date created, java.util.Date modified, Long size, Boolean check, com.box.sdk.ProgressListener listener); com.box.sdk.BoxFile uploadNewFileVersion(String fileId, java.io.InputStream fileContent, java.util.Date modified, Long fileSize, com.box.sdk.ProgressListener listener); ---- The files API is defined in the syntax as follows: ---- box:files/methodName?[parameters] ---- The 22 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *checkUpload* | canUpload | Does a pre-verification before upload, to check if the filename already exists or if there is permission to upload | *copyFile* | copy | Copy file to destination folder while optionally giving it a new name | *createFileMetadata* | createMetadata | Create metadata for file in either the global properties template or the specified template type | *createFileSharedLink* | link | Create a shared link to file | *deleteFile* | delete | Delete the file | *deleteFileMetadata* | deleteMetadata | Delete the file properties metadata | *deleteFileVersion* | deleteVersion | Delete a file version | *downloadFile* | download | Download a file | *downloadPreviousFileVersion* | downloadVersion | Download a previous version of file | *getDownloadURL* | url | Get an expiring URL for downloading a file directly from Box | *getFileInfo* | info | Get file information | *getFileMetadata* | metadata | Gets the file properties metadata | *getFilePreviewLink* | | Get an expiring URL for creating an embedded preview session | *getFileThumbnail* | thumbnail | Retrieves a thumbnail, or smaller image representation, of this file | *getFileVersions* | versions | Get any previous versions of file | *moveFile* | move | Move file to destination folder while optionally giving it a new name | *promoteFileVersion* | promoteVersion | Promote a previous version of file | *renameFile* | rename | Rename file giving it the name newName | *updateFileInfo* | updateInfo | Update file information | *updateFileMetadata* | updateMetadata | Update the file properties metadata | *uploadFile* | upload | Upload a new file to parent folder | *uploadNewFileVersion* | uploadVersion | Upload a new version of file |=== The files API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | checkUpload | *fileName* | The name to give the uploaded file | String | checkUpload | *parentFolderId* | The id of parent folder | String | checkUpload | *size* | *Optional* The size of the file's content used for monitoring the upload's progress | Long | copyFile | *destinationFolderId* | The id of the destination folder | String | copyFile | *fileId* | The id of file to copy | String | copyFile | *newName* | *Optional* The new name for copied file; if newName is null, the copied file has same name as the original. | String | createFileMetadata | *fileId* | The id of the file to create metadata for | String | createFileMetadata | *metadata* | The new metadata values | Metadata | createFileMetadata | *typeName* | *Optional* The metadata template type name; if null the global properties template type is used. | String | createFileSharedLink | *access* | The access level of the shared link | Access | createFileSharedLink | *fileId* | The id of the file to create shared link on | String | createFileSharedLink | *permissions* | *Optional* The permissions of the created link; if permissions is null then the created shared link is create with default permissions. | Permissions | createFileSharedLink | *unshareDate* | *Optional* The date and time at which time the created shared link will expire; if unsharedDate is null then a non-expiring link is created. | Date | deleteFile | *fileId* | The id of file to delete | String | deleteFileMetadata | *fileId* | The id of file to delete | String | deleteFileVersion | *fileId* | The id of file with version to delete | String | deleteFileVersion | *version* | The version of file to delete; initial version of file has value of 0, second version of file is 1 and so on. | Integer | downloadFile | *fileId* | The id of file | String | downloadFile | *listener* | *Optional* A listener for monitoring the download's progress; if null the download's progress will not be monitored. | ProgressListener | downloadFile | *output* | The stream to which the file contents will be written | OutputStream | downloadFile | *rangeEnd* | *Optional* The byte offset in file at which to stop the download; if null the entire contents of file will be downloaded. | Long | downloadFile | *rangeStart* | *Optional* The byte offset in file at which to start the download; if null the entire contents of file will be downloaded. | Long | downloadPreviousFileVersion | *fileId* | The id of file | String | downloadPreviousFileVersion | *listener* | *Optional* A listener for monitoring the download's progress; if null the download's progress will not be monitored. | ProgressListener | downloadPreviousFileVersion | *output* | The stream to which the version contents will be written | OutputStream | downloadPreviousFileVersion | *version* | The version of file to download; initial version of file has value of 0, second version of file is 1 and so on. | Integer | getDownloadURL | *fileId* | The id of file | String | getFileInfo | *fields* | *Optional* The information fields to retrieve; if null all information fields are retrieved. | String[] | getFileInfo | *fileId* | The id of file | String | getFileMetadata | *fileId* | The id of the file to retrieve metadata for | String | getFileMetadata | *typeName* | *Optional* The metadata template type name; if null the global properties template type is used. | String | getFilePreviewLink | *fileId* | The id of the file to get preview link on | String | getFileThumbnail | *fileId* | The id of the file to get thumbnail | String | getFileThumbnail | *fileType* | Either PNG of JPG | ThumbnailFileType | getFileThumbnail | *maxHeight* | Maximum height | Integer | getFileThumbnail | *maxWidth* | Maximum width | Integer | getFileThumbnail | *minHeight* | Minimum height | Integer | getFileThumbnail | *minWidth* | Minimum width | Integer | getFileVersions | *fileId* | The id of file | String | moveFile | *destinationFolderId* | The id of the destination folder | String | moveFile | *fileId* | The id of file to move | String | moveFile | *newName* | *Optional* The new name of moved file; if newName is null, the moved file has same name as the original. | String | promoteFileVersion | *fileId* | The id of file | String | promoteFileVersion | *version* | The version of file to promote; initial version of file has value of 0, second version of file is 1 and so on. | Integer | renameFile | *fileId* | The id of file to rename | String | renameFile | *newFileName* | The new name of file | String | updateFileInfo | *fileId* | The id of file to update | String | updateFileInfo | *info* | The updated information | Info | updateFileMetadata | *fileId* | The id of file to delete | String | updateFileMetadata | *metadata* | The new metadata values | Metadata | uploadFile | *check* | *Optional* If the file name is already used, call the uploadNewVersion instead. | Boolean | uploadFile | *content* | A stream containing contents of the file to upload | InputStream | uploadFile | *created* | *Optional* The content created date that will be given to the uploaded file | Date | uploadFile | *fileName* | The name to give the uploaded file | String | uploadFile | *listener* | *Optional* A listener for monitoring the upload's progress | ProgressListener | uploadFile | *modified* | *Optional* The content modified date that will be given to the uploaded file | Date | uploadFile | *parentFolderId* | The id of parent folder | String | uploadFile | *size* | *Optional* The size of the file's content used for monitoring the upload's progress | Long | uploadNewFileVersion | *fileContent* | A stream containing contents of the file to upload | InputStream | uploadNewFileVersion | *fileId* | The id of file | String | uploadNewFileVersion | *fileSize* | *Optional* The size of the file's content used for monitoring the upload's progress | Long | uploadNewFileVersion | *listener* | *Optional* A listener for monitoring the upload's progress | ProgressListener | uploadNewFileVersion | *modified* | *Optional* The content modified date that will be given to the uploaded file | Date |=== In addition to the parameters above, the files API can also use from the 21 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: folders *Only producer is supported* The folders API has 10 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.BoxFolder copyFolder(String folderId, String destinationFolderId, String newName); com.box.sdk.BoxFolder createFolder(String parentFolderId, String folderName); com.box.sdk.BoxFolder createFolder(String parentFolderId, String[] path); com.box.sdk.BoxSharedLink createFolderSharedLink(String folderId, com.box.sdk.BoxSharedLink.Access access, java.util.Date unshareDate, com.box.sdk.BoxSharedLink.Permissions permissions); void deleteFolder(String folderId); com.box.sdk.BoxFolder getFolder(String[] path); com.box.sdk.BoxFolder.Info getFolderInfo(String folderId, String[] fields); java.util.Collection getFolderItems(String folderId, Long offset, Long limit, String[] fields); com.box.sdk.BoxFolder moveFolder(String folderId, String destinationFolderId, String newName); com.box.sdk.BoxFolder renameFolder(String folderId, String newFolderName); com.box.sdk.BoxFolder updateFolderInfo(String folderId, com.box.sdk.BoxFolder.Info info); ---- The folders API is defined in the syntax as follows: ---- box:folders/methodName?[parameters] ---- The 10 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *copyFolder* | copy | Copy folder to destination folder while optionally giving it a new name | *createFolder* | create | Create a folder specified by path from parent folder with given parentFolderId, creating intermediate directories as required | *createFolderSharedLink* | link | Create a shared link to folder | *deleteFolder* | delete | Delete folder | *getFolder* | folder | Return the Box folder referenced by path | *getFolderInfo* | info | Get folder information | *getFolderItems* | items | Returns a specific range of child items in folder and specifies which fields of each item to retrieve | *moveFolder* | move | Move folder to destination folder while optionally giving it a new name | *renameFolder* | rename | Rename folder giving it the name newName | *updateFolderInfo* | updateInfo | Update folder information |=== The folders API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | copyFolder | *destinationFolderId* | The id of the destination folder | String | copyFolder | *folderId* | The id of folder to copy | String | copyFolder | *newName* | *Optional* The new name for copied folder; if newName is null, the copied folder has same name as the original. | String | createFolder | *folderName* | The name of created folder | String | createFolder | *parentFolderId* | The id of parent folder | String | createFolder | *path* | Sequence of Box folder names from parent folder to returned folder | String[] | createFolderSharedLink | *access* | The access level of the shared link | Access | createFolderSharedLink | *folderId* | The id of folder to create shared link on | String | createFolderSharedLink | *permissions* | The permissions of the created link; if permissions is null then the created shared link is create with default permissions. | Permissions | createFolderSharedLink | *unshareDate* | The date and time at which time the created shared link will expire; if unsharedDate is null then a non-expiring link is created. | Date | deleteFolder | *folderId* | The id of folder to delete | String | getFolder | *path* | Sequence of Box folder names from root folder to returned folder | String[] | getFolderInfo | *fields* | *Optional* The information fields to retrieve; if null all information fields are retrieved. | String[] | getFolderInfo | *folderId* | The id of folder | String | getFolderItems | *fields* | *Optional* The item fields to retrieve for each child item; if null all item fields are retrieved. | String[] | getFolderItems | *folderId* | The id of folder | String | getFolderItems | *limit* | *Optional* The maximum number of children to retrieve after the offset; if null all child items are retrieved. | Long | getFolderItems | *offset* | *Optional* The index of first child item to retrieve; if null all child items are retrieved. | Long | moveFolder | *destinationFolderId* | The id of the destination folder | String | moveFolder | *folderId* | The id of folder to move | String | moveFolder | *newName* | *Optional* The new name of moved folder; if newName is null, the moved folder has same name as the original. | String | renameFolder | *folderId* | The id of folder to rename | String | renameFolder | *newFolderName* | The new name of folder | String | updateFolderInfo | *folderId* | The id of folder to update | String | updateFolderInfo | *info* | The updated information | Info |=== In addition to the parameters above, the folders API can also use from the 21 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: groups *Only producer is supported* The groups API has 9 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.BoxGroupMembership addGroupMembership(String groupId, String userId, com.box.sdk.BoxGroupMembership.Role role); com.box.sdk.BoxGroup createGroup(String name, String provenance, String externalSyncIdentifier, String description, String invitabilityLevel, String memberViewabilityLevel); void deleteGroup(String groupId); void deleteGroupMembership(String groupMembershipId); com.box.sdk.BoxGroup.Info getGroupInfo(String groupId); com.box.sdk.BoxGroupMembership.Info getGroupMembershipInfo(String groupMembershipId); java.util.Collection getGroupMemberships(String groupId); com.box.sdk.BoxGroup updateGroupInfo(String groupId, com.box.sdk.BoxGroup.Info groupInfo); com.box.sdk.BoxGroupMembership updateGroupMembershipInfo(String groupMembershipId, com.box.sdk.BoxGroupMembership.Info info); ---- The groups API is defined in the syntax as follows: ---- box:groups/methodName?[parameters] ---- The 9 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *addGroupMembership* | addMembership | Add a member to group with the specified role | *createGroup* | create | Create a new group with a specified name and optional additional parameters | *deleteGroup* | delete | Delete group | *deleteGroupMembership* | deleteMembership | Delete group membership | *getGroupInfo* | info | Get group information | *getGroupMembershipInfo* | membershipInfo | Get group membership information | *getGroupMemberships* | memberships | Get information about all of the group memberships for this group | *updateGroupInfo* | | Update group information | *updateGroupMembershipInfo* | updateMembershipInfo | Update group membership information |=== The groups API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | addGroupMembership | *groupId* | The id of group | String | addGroupMembership | *role* | *Optional* The role of the user in this group. Can be null to assign the default role. | Role | addGroupMembership | *userId* | The id of user to be added to group | String | createGroup | *description* | *Optional* The description of the new group | String | createGroup | *externalSyncIdentifier* | *Optional* The external_sync_identifier of the new group | String | createGroup | *invitabilityLevel* | *Optional* The invitibility_level of the new group | String | createGroup | *memberViewabilityLevel* | *Optional* The member_viewability_level of the new group | String | createGroup | *name* | The name of the new group | String | createGroup | *provenance* | *Optional* The provenance of the new group | String | deleteGroup | *groupId* | The id of group to delete | String | deleteGroupMembership | *groupMembershipId* | The id of group membership to delete | String | getGroupInfo | *groupId* | The id of group | String | getGroupMembershipInfo | *groupMembershipId* | The id of group membership | String | getGroupMemberships | *groupId* | The id of group | String | updateGroupInfo | *groupId* | The id of group to update | String | updateGroupInfo | *groupInfo* | The updated information | Info | updateGroupMembershipInfo | *groupMembershipId* | The id of group membership to update | String | updateGroupMembershipInfo | *info* | The updated information | Info |=== In addition to the parameters above, the groups API can also use from the 21 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: search *Only producer is supported* The search API has 1 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- java.util.Collection searchFolder(String folderId, String query); ---- The search API is defined in the syntax as follows: ---- box:search/methodName?[parameters] ---- The 1 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *searchFolder* | search | Search folder and all descendant folders using the given query |=== The search API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | searchFolder | *folderId* | The id of folder searched | String | searchFolder | *query* | The search query | String |=== In addition to the parameters above, the search API can also use from the 21 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: tasks *Only producer is supported* The tasks API has 9 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.BoxTask addAssignmentToTask(String taskId, com.box.sdk.BoxUser assignTo); com.box.sdk.BoxTask addFileTask(String fileId, com.box.sdk.BoxTask.Action action, java.util.Date dueAt, String message); void deleteTask(String taskId); void deleteTaskAssignment(String taskAssignmentId); java.util.List getFileTasks(String fileId); com.box.sdk.BoxTaskAssignment.Info getTaskAssignmentInfo(String taskAssignmentId); java.util.List getTaskAssignments(String taskId); com.box.sdk.BoxTask.Info getTaskInfo(String taskId); com.box.sdk.BoxTask updateTaskInfo(String taskId, com.box.sdk.BoxTask.Info info); ---- The tasks API is defined in the syntax as follows: ---- box:tasks/methodName?[parameters] ---- The 9 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *addAssignmentToTask* | addAssignment | Add assignment for task | *addFileTask* | add | Add task to file | *deleteTask* | delete | Delete task | *deleteTaskAssignment* | deleteAssignment | Delete task assignment | *getFileTasks* | tasks | Get a list of any tasks on file | *getTaskAssignmentInfo* | assignmentInfo | Get task assignment information | *getTaskAssignments* | assignments | Get a list of any assignments for task | *getTaskInfo* | info | Get task information | *updateTaskInfo* | updateInfo | Update task information |=== The tasks API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | addAssignmentToTask | *assignTo* | The user to assign to task | BoxUser | addAssignmentToTask | *taskId* | The id of task to add assignment for | String | addFileTask | *action* | The action the task assignee will be prompted to do | Action | addFileTask | *dueAt* | The day at which this task is due | Date | addFileTask | *fileId* | The id of file to add task to | String | addFileTask | *message* | *Optional* An optional message to include with the task | String | deleteTask | *taskId* | The id of task to delete | String | deleteTaskAssignment | *taskAssignmentId* | The id of task assignment to delete | String | getFileTasks | *fileId* | The id of file | String | getTaskAssignmentInfo | *taskAssignmentId* | The id of task assignment | String | getTaskAssignments | *taskId* | The id of task | String | getTaskInfo | *taskId* | The id of task | String | updateTaskInfo | *info* | The updated information | Info | updateTaskInfo | *taskId* | The id of task | String |=== In addition to the parameters above, the tasks API can also use from the 21 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: users *Only producer is supported* The users API has 10 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.EmailAlias addUserEmailAlias(String userId, String email); com.box.sdk.BoxUser createAppUser(String name, com.box.sdk.CreateUserParams params); com.box.sdk.BoxUser createEnterpriseUser(String login, String name, com.box.sdk.CreateUserParams params); void deleteUser(String userId, boolean notifyUser, boolean force); void deleteUserEmailAlias(String userId, String emailAliasId); java.util.List getAllEnterpriseOrExternalUsers(String filterTerm, String[] fields); java.util.Collection getUserEmailAlias(String userId); com.box.sdk.BoxUser.Info getUserInfo(String userId); com.box.sdk.BoxFolder.Info moveFolderToUser(String userId, String sourceUserId); com.box.sdk.BoxUser updateUserInfo(String userId, com.box.sdk.BoxUser.Info info); ---- The users API is defined in the syntax as follows: ---- box:users/methodName?[parameters] ---- The 10 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *addUserEmailAlias* | addEmailAlias | Add a new email alias to user's account | *createAppUser* | create | Provision a new app user in an enterprise with additional user information using Box Developer Edition | *createEnterpriseUser* | create | Provision a new user in an enterprise with additional user information | *deleteUser* | delete | Delete user from an enterprise account | *deleteUserEmailAlias* | deleteEmailAlias | Delete an email alias from user's account | *getAllEnterpriseOrExternalUsers* | users | Get any managed users that match the filter term as well as any external users that match the filter term | *getUserEmailAlias* | emailAlias | Get a collection of all the email aliases for user | *getUserInfo* | info | Get user information | *moveFolderToUser* | | Move root folder for specified user to current user | *updateUserInfo* | updateInfo | Update user information |=== The users API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | addUserEmailAlias | *email* | The email address to add as an alias | String | addUserEmailAlias | *userId* | The id of user | String | createAppUser | *name* | The name of the user | String | createAppUser | *params* | *Optional* Additional user information | CreateUserParams | createEnterpriseUser | *login* | The email address the user will use to login | String | createEnterpriseUser | *name* | The name of the user | String | createEnterpriseUser | *params* | *Optional* Additional user information | CreateUserParams | deleteUser | *force* | Whether or not this user should be deleted even if they still own files | Boolean | deleteUser | *notifyUser* | Whether or not to send an email notification to the user that their account has been deleted | Boolean | deleteUser | *userId* | The id of user to delete | String | deleteUserEmailAlias | *emailAliasId* | The id of the email alias to delete | String | deleteUserEmailAlias | *userId* | The id of user | String | getAllEnterpriseOrExternalUsers | *fields* | *Optional* The fields to retrieve. Leave this out for the standard fields. | String[] | getAllEnterpriseOrExternalUsers | *filterTerm* | *Optional* The filter term to lookup users by (login for external, login or name for managed); if null all managed users are returned. | String | getUserEmailAlias | *userId* | The id of user | String | getUserInfo | *userId* | The id of user | String | moveFolderToUser | *sourceUserId* | The user id of the user whose files will be the source for this operation | String | moveFolderToUser | *userId* | The id of user | String | updateUserInfo | *info* | The updated information | Info | updateUserInfo | *userId* | The id of user to update | String |=== In addition to the parameters above, the users API can also use from the 21 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. // endpoint options: END == Samples The following route uploads new files to the user's root folder: [source,java] ---- from(""file:..."") .to(""box://files/upload/inBody=fileUploadRequest""); ---- The following route polls user's account for updates: [source,java] ---- from(""box://events/listen?startingPosition=-1"") .to(""bean:blah""); ---- The following route uses a producer with dynamic header options. The *fileId* property has the Box file id and the *output* property has the output stream of the file contents, so they are assigned to the *CamelBox.fileId* header and *CamelBox.output* header respectively as follows: [source,java] ---- from(""direct:foo"") .setHeader(""CamelBox.fileId"", header(""fileId"")) .setHeader(""CamelBox.output"", header(""output"")) .to(""box://files/download"") .to(""file://...""); ---- === More information See more details at the Box API reference: https://developer.box.com/reference include::camel-spring-boot::page$box-starter.adoc[] ",12287,True,2574.978804425354,median "= jbang - Unleash the power of Java :idprefix: :idseparator: - ifndef::env-github[] :toc: left :icons: font endif::[] ifdef::env-github[] :toc: macro :caution-caption: :fire: :important-caption: :exclamation: :note-caption: :paperclip: :tip-caption: :bulb: :warning-caption: :warning: endif::[] image:https://img.shields.io/github/release/jbangdev/jbang.svg[Release,link=https://github.com/jbangdev/jbang/releases] image:https://github.com/jbangdev/jbang/workflows/ci-build/badge.svg[Build Status,link=https://github.com/jbangdev/jbang/actions] image:https://www.eclipse.org/che/contribute.svg[Che, link=https://che.openshift.io/f?url=https://github.com/jbangdev/jbang] image:https://img.shields.io/badge/Gitpod-Workspace-blue?logo=gitpodp[Gitpod, link=https://gitpod.io/#https://github.com/jbangdev/jbang] image:https://badges.gitter.im/jbangdev/community.svg[Gitter, link=https://gitter.im/jbangdev/community] image:images/jbang_logo.svg[JBang Logo, title=""JBang Logo""] == Intro Want to learn, explore or use Java instantly without setup ? Do you like Java but use python, groovy, kotlin or similar languages for scripts, experimentation and exploration ? Ever wanted to just be able to run java from anywhere without any or very minimal setup ? Ever tried out Java 11+ support for running `.java` files directly in your shell but felt it was a bit too cumbersome ? Then try `jbang` which lets you do this: image:https://asciinema.org/a/4AiobRxUwPUPztCtrDYcmoKjs.svg[link=https://asciinema.org/a/4AiobRxUwPUPztCtrDYcmoKjs?autoplay=true&theme=solarized-dark] [source, bash] ---- $ jbang init --template=cli hello.java $ jbang hello.java Max! [jbang] Resolving dependencies... [jbang] Resolving info.picocli:picocli:4.5.0...Done [jbang] Dependencies resolved [jbang] Building jar... Hello Max! $ jbang hello.java -h Usage: hello [-hV] hello made with jbang The greeting to print -h, --help Show this help message and exit. -V, --version Print version information and exit. ---- Instant cli app generated built using java and picocli as a dependency that was fetched as needed for the compilation and execution. JBang goes beyond more than just easy scripting; you can use `jbang` to launch any kind of java application or library packaged as a jar available locally, via http/https download or in a Maven repository. toc::[] == Features * `.java` Scripting for Java 8 and upwards * `.jsh` via JShell from Java 9 and upwards * Works on icon:windows[] Windows, icon:apple[] OSX and icon:linux[] Linux * Install using curl, power shell, SDKMan (icon:apple[]/icon:linux[]), Homebrew (icon:apple[]), Chocolatey (icon:windows[]) or Scoop (icon:windows[]) * If needed will automatically install Java and even a Java editor (vscodium) for editing * Installation of scripts to user `PATH` * Include multiple files and sources * Dependency declarations using `//DEPS ` for automatic dependency resolution * Control compile and runtime options with `//JAVAC_OPTIONS ` and `//JAVA_OPTIONS ` * Compiled jar and Dependency resolution caching * native-image generation (`--native`) * Launch with debug enabled for instant debugging from your favorite IDE * Transparent launch of JavaFX Applications on Java 8 and higher * Can be used for writing plugins to other cli's like `kubectl` * Init templates to get started easily (`jbang init -t cli hello.java`) * Generate gradle and IDE config with dependencies for easy editing in your favorite IDE (`jbang edit myfile.java`) To use it install `jbang` and run `jbang yourscript.java` == Requirements Tested and verified to use on OSX, Linux and Windows (incl. command.exe, cygwin and mingw shells). == Installation To use `jbang` Java 8 is the minimum required version, however Java 11 or higher is recommended. Note: `jbang` will download and install `java` from Adopt OpenJDK if no `java` is available. Once you have installed from one of the below approaches it is recommended you run `jbang app setup` to have it setup your `PATH` to include jbang app scripts + it will on operating systems that supports it setup a `j!` alias you can use instead of `jbang`. === SDKMan icon:linux[] / icon:apple[] To install both java and `jbang` we recommend https://sdkman.io[sdkman] on Linux and OSX. [source, bash] ---- curl -s ""https://get.sdkman.io"" | bash # <.> source ~/.bash_profile # <.> sdk install java # <.> ---- Once Java is installed and ready, you install `jbang` with [source, bash] ---- sdk install jbang ---- To test your installation run: [source, bash] ---- jbang --help ---- This should print out usage information. To update run: [source] ---- sdk update jbang ---- === Chocolatey icon:windows[] On Windows you can install both `java` and jbang` with https://chocolatey.org[Chocolatey]. From a command prompt with enough rights to install with choco: choco install jdk11 Once Java in installed run: choco install jbang To upgrade to latest version: choco upgrade jbang The latest package will be published to https://chocolatey.org/packages/jbang[jbang choco package page], it might be a bit delayed as the review is still manual. In case the default version is not the latest you can see the https://chocolatey.org/packages/jbang/#versionhistory[version list] and install specific version using: choco install jbang --version= === Scoop icon:windows[] On Windows you can also install `jbang` with https://scoop.sh[Scoop]. [source, bash] ---- scoop bucket add jbangdev https://github.com/jbangdev/scoop-bucket scoop install jbang ---- To upgrade to latest version: scoop update jbang === Homebrew icon:apple[] On OSX you can install 'java' and `jbang` with https://brew.sh[Homebrew] using custom taps. To install Java 11: [source, bash] ---- brew tap AdoptOpenJDK/openjdk brew cask install adoptopenjdk11 ---- Once Java is installed you can use brew with https://github.com/jbangdev/homebrew-tap/[jbangdev/tap] to get `jbang`: brew install jbangdev/tap/jbang To upgrade to latest version: brew upgrade jbangdev/tap/jbang === (Experimental) Linux packages icon:linux[] WARNING: These builds are not fully automated yet thus might be slightly behind. You can install rpm packages from https://copr.fedorainfracloud.org/coprs/maxandersen/jbang/[Fedora Copr] by doing the following: [source] ---- dnf copr enable maxandersen/jbang dnf install jbang ---- The COPR currently includes builds from various versions of CentOS, Fedora, Mageia and OpenSuse. === Docker / GitHub Action icon:docker[] You can run `jbang` via Docker: [source, bash] ---- docker run -v `pwd`:/ws --workdir=/ws jbangdev/jbang-action helloworld.java ---- or if you prefer using Quay.io: [source, bash] ---- docker run -v `pwd`:/ws --workdir=/ws quay.io/jbangdev/jbang-action helloworld.java ---- The same container images can be used with GitHub Actions, see https://github.com/jbangdev/jbang-action[jbang-action] for details. === Manual install Unzip the https://github.com/jbangdev/jbang/releases/latest[latest binary release], add the `jbang-/bin` folder to your `$PATH` and you are set. === Wrapper install If you would like to have `jbang` available in a local directory and committed into a source code repository (akin to Maven and Gradle wrappers) you can use the `jbang wrapper` command. If you have `jbang` already installed you call `jbang wrapper install` in a folder to install a local `jbang` that will run out of that directory using `./jbang`. The `./.jbang` directory which `jbang wrapper install` creates is just a cache which you typically would not commit to a source code repository, so you can e.g. `echo .jbang/ >>.gitignore`. === ""Zero"" Install If you want to try out jbang without a package manager or similar you can run the following to download jbang in `~/.jbang` and if necessary `java`. Linux/OSX/Windows Bash: [source, bash] ---- curl -Ls https://sh.jbang.dev | bash -s - ---- For example `curl -Ls https://sh.jbang.dev | bash -s - properties@jbangdev` Windows Powershell: [source, powershell] ---- iex ""& { $(iwr -useb https://ps.jbang.dev) } "" ---- For example `iex ""& { $(iwr -useb https://ps.jbang.dev) } properties@jbangdev""` == Usage A script is just a single `.java` file with a classic static main method or a `.jsh` file which will be passed to `jshell`. Below is an (almost) minimal example you can save in `helloworld.java` or simply run `jbang init helloworld.java`: [source,java] ---- ///usr/bin/env jbang ""$0"" ""$@"" ; exit $? # <.> class helloworld { // <.> public static void main(String[] args) { if(args.length==0) { System.out.println(""Hello World!""); } else { System.out.println(""Hello "" + args[0]); } } } ---- <.> By using this `//` style instead of shebang `#!` you trick `bash`, `zsh` etc. to run this as a script while still being valid java code. <.> A classname, can be anything when using `jbang` but to be valid java for most IDEs you'll want to name it the same as the source file. Now to run this you can call it via `jbang`: [source] ---- jbang helloworld.java ---- or if on Linux/OSX run it directly. If you created it manually you need to mark it as executable before running it. [source] ---- chmod +x helloworld.java ./helloworld.java jbang! ---- [WARNING] ==== When no <> is available in the PATH, JDK 11 will be downloaded by default to bootstrap jbang. If your script requires a higher version and you don' want to download two JDK's, you can define an alternative default with `JBANG_DEFAULT_JAVA_VERSION` env variable. $ JBANG_DEFAULT_JAVA_VERSION=14 jbang my-script.java Note that if JDK is found in the PATH, `JBANG_DEFAULT_JAVA_VERSION` will be ignored. ==== === Default application If you pass a directory or a url ending in `/` jbang will look for `main.java` to run as default application for that directory / location. === URLs from Trusted Sources You can use `http(s):/` and `file:/` url's for input:. [source] ---- jbang https://gist.github.com/maxandersen/f43b4c52dfcfc42dcd59a04e49acf6ec ---- For safety reasons jbang will not run arbitrary urls before you indicated you trust their source. Thus when running the above for the first time you will see the following warning about the url not being a trusted source: [source,bash] ---- jbang https://gist.github.com/maxandersen/f43b4c52dfcfc42dcd59a04e49acf6ec [jbang] https://gist.github.com/maxandersen/f43b4c52dfcfc42dcd59a04e49acf6ec is not from a trusted source thus not running it automatically. If you trust the url to be safe to run you can do one of the following: 0) Trust once: Add no trust, just run this time 1) Trust this url in future: jbang trust add https://gist.github.com/maxandersen/ Any other response will result in exit. [jbang] Type in your choice (0 or 1) and hit enter. Times out after 10 seconds. ---- You can then choose 0 to run once or 1 to trust the suggested url. If you don't answer within 10 seconds jbang will exit. To enable running it without such question you need to mark that url or a sub part of it as a trusted source. i.e. `jbang trust add https://github.com/maxandersen/` will tell `jbang` to trust anything with that base url. You can see more in the comments of the `~/.jbang/trusted-sources.json`. [TIP] ==== Sites such as GitHub, gitlab, bitbucket, gist, carbon.now.sh jbang will try and extract the proper source rather than the raw html. i.e. doing `jbang https://carbon.now.sh/ae51bf967c98f31a13cba976903030d5 carbon!` is possible. ==== [TIP] ==== URL's will follow redirects. In case you need to use it with sites with self-signed/non-trusted certificates you can if you trust the site use `--insecure`. ==== === Build and run native image (Experimental) There is support for using `native-image` from GraalVM project to produce a binary executable. Since not all java libraries can automatically be built with `native-image` - especially if using reflection feature are considered highly experimental. Just run `jbang --native helloworld.java` and `jbang` will use `native-image` from either `$JAVA_HOME/bin` or `$GRAALVM_HOME/bin` or `$PATH` to produce a native image binary. You can install the `native-image` utility binary e.g. by installing GraalVM from https://www.graalvm.org/downloads, and then once running `gu install native-image` as per https://www.graalvm.org/reference-manual/native-image. [TIP] ==== If you use `--native` with picocli remember to add `info.picocli:picocli-codegen` as that will ensure it will actually work with `native-image`. ==== === Using `.jsh` for `jshell` There is support to run `.jsh` via `jshell`. The advantage of `jshell` is that you do not need to have a class or static main method. Classic `jshell` does not support passing in arguments nor system properties, `jbang` does. In the case of `.jsh` files `jbang` injects a startup script that declares a `String[] args` which will contain any passed in arguments, and it sets any properties passed in as `-Dkey=value` as parameters to `jbang`. That means you can run a script as `jbang -Dkey=value helloworld.jsh World` and retrieve arguments and properties as: [source,java] ---- System.out.println(""Hello "" + (args.length>0?args[0]:""World"")); // <.> System.out.println(System.getProperty(""key"")); // <.> ---- <.> Line where `args` are accessible without previous declaration. <.> System properties set when passed as `-D` arguments to `jbang` The script will have the output: Hello World value Please note that `.jsh` files are source only, they are not compiled thus they are https://github.com/jbangdev/jbang/issues/506[not cached] nor can they be https://github.com/jbangdev/jbang/issues/510[built as native images]. [TIP] ==== If you use `-Dkey` where no value is specified `jbang` will interpret this as `-Dkey=true` allowing you to easily have flags passed into, i.e. `jbang -DskipTests mytestrunner.java`. Now within your script `Boolean.getBoolean('skipTests') will return true. ==== ==== Running script from standard input jbang can run scripts directly from standard input using `-` or `/dev/stdin` as input. i.e. `echo 'System.out.println(""Hello World!"");' | jbang -` [TIP] ==== If you use `--interactive` `jbang` will let `jshell` enter into interactive/REPL mode. You can write `/exit` to leave this mode. ==== [TIP] ==== If your own code needs to handle chained pipes well it is recommended to add the following code: [source,java] ---- import sun.misc.Signal; if (!""Windows"".equals(System.getProperty(""os.name""))) { Signal.handle(new Signal(""PIPE""), (final Signal sig) -> System.exit(1)); } ---- It will give a compiler warning as it is internal API; but for now it works. ==== === Running ``.jar``'s `jbang` will also run `.jar` files directly. i.e. `jbang helloworld.jar` will run `helloworld.jar` if found on your local file system. The `.jar` can be a local file or a http/https url. You can also run a `.jar` file referenced by a Maven coordinate, i.e.: jbang info.picocli:picocli-codegen:4.5.0 This will fetch the dependency stated and put the transitive dependencies on the class-path. If you need to specify a main class you can do so by using `--main` i.e. jbang --main picocli.codegen.aot.graalvm.ReflectionConfigGenerator info.picocli:picocli-codegen:4.5.0 [TIP] ==== A side effect of running GAV as a jar, the GAV could also be a `.java` or `.jsh` file and it would be launched as a script instead of a jar. No one would want to do that (right?) but now you know. ==== == Init templates To get started you can run `jbang init helloworld.java` and a simple java class with a static main is generated. Using `jbang init --template=cli helloworld.java` you get a more complete Hello World CLI using https://picocli.info/[picocli] as dependency. == Declare dependencies If you want to write real scripts you will want to use some java libraries. To specify dependencies you use gradle-style locators or links to Git sources. Below are examples for `log4j`. === Using `//DEPS` [source,java] ---- ///usr/bin/env jbang ""$0"" ""$@"" ; exit $? // <.> //DEPS log4j:log4j:1.2.17 import static java.lang.System.out; import org.apache.log4j.Logger; import org.apache.log4j.BasicConfigurator; import java.util.Arrays; class classpath_example { static final Logger logger = Logger.getLogger(classpath_example.class); public static void main(String[] args) { BasicConfigurator.configure(); // <.> logger.info(""Welcome to jbang""); Arrays.asList(args).forEach(arg -> logger.warn(""arg: "" + arg)); logger.info(""Hello from Java!""); } } ---- <.> `//DEPS` must be placed at the start of line and can be one or more space separated dependencies. <.> Minimal logging setup - required by log4j. Now when you run this, the first time with no existing dependencies installed you should get an output like this: [source] ---- $ ./classpath_example.java [jbang] Resolving dependencies... [jbang] Resolving log4j:log4j:1.2.17...Done [jbang] Dependencies resolved 0 [main] INFO classpath_example - Welcome to jbang 1 [main] INFO classpath_example - Hello from Java! ---- === Using links to Git sources Instead of gradle-style locators you can also use URLs to projects on GitHub, GitLab or BitBucket. Links to those projects will then be converted to artifacts references on https://jitpack.io/[jitpack]. You can use links to the root of the project, to the root of a tag/release and to specific commits. If the project you link to has multiple modules and you want only a specific module you can specify the name of the module by appending `#name-of-module` to the URL. And finally if the link you provide is to a specific branch of the project then you need to append `#:SNAPSHOT` to the URL. (If you have both a branch and a module name then use `#name-of-module:SNAPSHOT`) .Examples of links and their resulting locator: |=== |Link | Locator |https://github.com/jbangdev/jbang |com.github.jbangdev:jbang:HEAD-SNAPSHOT |https://github.com/jbangdev/jbang/tree/v1.2.3 |com.github.jbangdev:jbang:v1.2.3 |https://github.com/jbangdev/jbang/tree/f1f34b031d2163e0cdc6f9a3725b59f47129c923[https://github.com/jbangdev/jbang/tree/f1f34b031...] |com.github.jbangdev:jbang:f1f34b031d |https://github.com/jbangdev/jbang#mymodule |com.github.jbangdev.jbang:mymodule:HEAD-SNAPSHOT |https://github.com/jbangdev/jbang/tree/mybranch#:SNAPSHOT |com.github.jbangdev:jbang:mybranch-SNAPSHOT |https://github.com/jbangdev/jbang/tree/mybranch#mymodule:SNAPSHOT |com.github.jbangdev.jbang.mymodule:mybranch-SNAPSHOT |=== === Offline mode In case you prefer `jbang` to just fail-fast when dependencies cannot be found locally you can run `jbang` in offline mode using `jbang -o` or `jbang --offline`. In this mode `jbang` will simply fail if dependencies have not been cached already. === Repositories By default `jbang` uses https://jcenter.bintray.com/[jcenter] as its repository as it is a superset of Maven Central and supposedly should be faster. And if you are using the above mentioned URL dependencies https://jitpack.io[jitpack] will be added automatically as well. If that is not sufficient for you or need some custom repo you can use `//REPOS id=repourl` to state which repository URL to use. For ease of use there are also a few shorthands to use popular commonly available repositories. |=== |Short name | Description |`mavencentral` |Maven Central |`jcenter` |`https://jcenter.bintray.com/` |`google` |`https://maven.google.com/` |`jitpack` |`https://jitpack.io/` |=== Following example enables use of Maven Central and add a custom `acme` repository. [source,java] ---- //REPOS mavenCentral,acme=https://maven.acme.local/maven ---- [WARNING] ==== If you add any `//REPOS` lines `jbang` will no longer consult `jcenter` thus you need to explicitly add it if needed. ==== [TIP] ==== For secure authentication `jbang` will honor `~/.m2/settings-security.xml` for configuring username/passwords. ==== === Using `@Grab` There is also support for using Groovy lang style `@Grab` syntax. [source,java] ---- ///usr/bin/env jbang ""$0"" ""$@"" ; exit $? import static java.lang.System.out; import org.apache.log4j.Logger; import org.apache.log4j.BasicConfigurator; import java.util.Arrays; import groovy.lang.Grab; // <.> import groovy.lang.Grapes; import groovy.lang.GrabResolver; @GrabResolver(""mavenCentral"") // <.> @GrabResolver(name='acme', root='https://maven.acme.local/maven') @Grapes({ // <.> @Grab(group=""org.codehaus.groovy"", module=""groovy"", version=""2.5.8""), // <.> @Grab(module = ""log4j"", group = ""log4j"", version = ""1.2.17"") }) class classpath_example { static final Logger logger = Logger.getLogger(classpath_example.class); public static void main(String[] args) { BasicConfigurator.configure(); Arrays.asList(args).forEach(arg -> out.println(arg)); } } ---- <.> Import needed to make the compiler be okey with `@Grab` annotation. <.> Using `GrabResolver` to enable `mavenCentral` and custom `acme` repository <.> In Groovy you normally put `@Grab` on import statements. That is not allowed in Java thus when having multiple imports you need to put them in a `@Grapes` annotation first. <.> `jbang` will grab any `@Grab` annotation and assume it is declaring dependencies. === System properties and Environment variables In dependencies you can refer to environment and system properties to parameterize the dependencies. It uses the format `${[env.]propertyname:}`. Furthermore to align with properties commonly used to make dependency resolution portable `jbang` exposes properties similar to what the `https://github.com/trustin/os-maven-plugin[os-maven-plugin]` does. Plus for ease of use for javafx dependencies it also setups a property named `${os.detected.jfxname}`. Examples: [source,bash] ---- ${env.USER} = 'max' ${os.name} = 'Mac OS X' ${non.existing.key:empty} = 'empty' ${os.detected.jfxname} = 'mac' ---- This can be put to use in `//DEPS` like so: //DEPS org.openjfx:javafx-graphics:11.0.2:${os.detected.jfxname} Here we use the properties to avoid hardcoding your script to a specific operating system. === JavaFX If `jbang` detects you have a `javafx-` dependency in your list of dependencies it will if you `java` command supports Java modules automatically set the necessary `--module-path` and `--add-modules`. See `link:https://github.com/jbangdev/jbang-examples/tree/master/examples/jfx.java[]` and `link:https://github.com/jbangdev/jbang-examples/tree/master/examples/jfxtiles.java[]` for examples of this. == Multiple source files It is possible to use multiple source files just by having the files in the same source directory, it will even work for a limited extent with packages. For example the example below works by just calling `jbang Main.java`: .Main.java [source,java] ---- import model.Person; public class Main { public static void main(String... args) { Person p = new Person(args[0]); System.out.println(""Hello "" + p.getName()); } } ---- .model/Person.java [source,java] ---- package model; public class Person { String name; public String getName() { return name; } public Person(String n) { this.name = n; } } ---- There are some cases where the above does not work; i.e. if two packages refer to each other - i.e. `model.Person` referring to `util.Generator` will fail. Also `jbang edit` does not know about multiple sources as it runs and must run before compilation occurs. Thus version 0.46 there is now support for having that all work with multiple source files. The main script file defines all the dependencies and you add more source files into the application using `//SOURCES `. If included source has `//SOURCES` that will also get included recursively. The listed file name(s) gets added to source list when compiling. Currently there are not `*.java` style matching or support for these `.java` files to declare `//DEPS` or other jbang configuration. That will currently only be honored by the main script/app. These will be loosened up in future based on feedback. == Adding more resources If you want to add a `META-INF/application.properties` or `META-INF/resource.index.html` or other files to the generated jar you can use `//FILES` to add them. The format is `//FILES [=]`. Example: //FILES resource.properties //FILES META-INF/resources/index.html=index.html Here `resource.properties` will be copied as is and `META-INF/resources/index.html` gets its content from `index.html`. All locations are relative to the script location. WARNING: Currently `jbang edit` and http(s) based script do not work with `//FILES`. Will be added later. == Extension-less/non-java files for cli-plugins You can use `jbang` to write plugins for cli's like `kubectl`, `git`, etc. They expect their plugins to be named like `-`, i.e. `kubectl-myplugin`. Furthermore some of them, particularly `kubectl` currently require the file to start with `#!` otherwise you get a `exec format error`. There are two ways to have that work. The first recommended way is to use `jbang app install` which setups an intermediate script to avoid the issue, i.e. `jbang app install --name kubectl-my-plugin myplugin.java`. The second is to use a bit of auto-magic `jbang` has to help in case you only want a single file, no intermediate script. That is described below. === Kebab casing of filename `jbang` lets you name your file without a `.java` or `.jsh` extension, such as `kubectl-my-plugin` or `myjavascript.sh`. `jbang` will in this case copy the file to a temporary directory using kebab-case to map the name to a proper java class name. For example, if you make a file called `kubectl-my-plugin` then `jbang` will assume the actual class name to launch to be `KubectlMyPlugin`. Note, similar is done when using `jbang edit`, here the symbolic link will be made so the IDE will treat it as regular camel cased java class. NOTE: If you do not follow this naming pattern you will get a compile error as `javac` expects both the public class and file names to be equal. === she-bang auto-stripped For extension less scripts, you can put `#!' header at the beginning to let apps recognize it is to be treated as a script. To avoid issues when compiling, `jbang` will remove that line before compilation. For now this is required for `kubectl` plugin but not `git`. https://github.com/kubernetes/kubectl/issues/822[Issue opened] on this limitation. == Java version `jbang` will by default use `JAVA_HOME` and if not available, check the `PATH` to locate the `java` executable to run the script with. If your script requires a specific or minimal version of Java you can use `//JAVA (+)`. If Jbang finds a java executable using `JAVA_HOME` or `PATH` which satisfies the stated java version jbang will use it. If no such version is found it will automatically download and install it. Examples: `//JAVA 11` will force use of Java 11. + `//JAVA 13+` will require at least java 13. Java 13 or higher will be used. In case no matching `java` is found `jbang` will fail. You can always force running with specific version of `java` using `--java` command line option, i.e. `jbang --java 8 hello.java` == Managing JDKs In the previous section it was mentioned that Jbang will automatically download and install JDKs when necessary. You can use the `jdk` command to manage JDKs, for example you can run the following: jbang jdk list which will list all the JDKs that are currently installed by Jbang. It's easy to `install` additional JDKs by running: jbang jdk install 14 which will download and install JDK version 14 into Jbang's cache (`~/.jbang/cache/jdks` by default). The list of versions that are available for installation can be found here: https://adoptopenjdk.net/releases.html The first JDK that gets installed by Jbang will be set as the ""default"" JDK. This is from then on the JDK that will be used by Jbang if no Java could be found on the system (meaning `javac` wasn't found on the `PATH` and no `JAVA_HOME` is set). You can change the default JDK by running: jbang jdk default 12 Running it without an argument will return the version of the JDK that is currently set as the default. NOTE: On Windows you might need elevated privileges to create symbolic links. If you don't have permissions then running the above command will result in an error. To use it https://stackoverflow.com/a/24353758[enable symbolic links] for your user or run your shell/terminal as administrator to have this feature working. When you `uninstall` a JDK by running: jbang jdk uninstall 12 and that JDK was set as the default, Jbang will set the next higher version JDK as the default. If no higher version is available it will select the next lower version. === Using managed JDKs yourself Given the fact that Jbang is able to easily download and install JDKs we thought that it might be a good option for our users to be able to access those JDKs for their own use instead of having to install yet another version themselves. To make that easy we added a couple of useful commands. The first can be used to set retrieve to location where the JDK is installed: jbang jdk home This will return the path to the ""default"" JDK (by default `~/.jbang/currentjdk)`, if you want to know the location of a specific JDK you can pass the version as an argument: `jbang jdk home 14`. This command could be used by scripts to find a JDK to use to run a Java program for example (eg: `JAVA_HOME=$(jbang jdk home)`. For setting up your current command line environment there's something simpler. You can run: jbang jdk java-env On Linux and Mac this will output something like: [source] ---- export PATH=""/home/user/.jbang/currentjdk/bin:$PATH"" export JAVA_HOME=""/home/user/.jbang/currentjdk"" # Run this command to configure your shell: # eval $(jbang jdk java-env) ---- And the output itself shows how to properly use it to configure your command line to use the JDK. In this case it's by running: eval $(jbang jdk java-env) To do this by default for all shells you start simply add the above line to your `~/.bashrc` file. Unfortunately on Windows using CMD things are not as easy as is show by the output of `jbang jdk java-env` on that platform: [source] ---- set PATH=C:\\Users\\user\\.jbang\\currentjdk\\bin;%PATH% set JAVA_HOME=C:\\Users\\user\\.jbang\\currentjdk rem Copy & paste the above commands in your CMD window or add rem them to your Environment Variables in the System Settings. ---- Instead of copying and pasting lines you could also redirect the output to a .bat file and execute that instead: > jbang jdk java-env > setenv.bat > setenv == Editing You can edit your script in an IDE/editor by using `jbang edit helloworld.java`. This will generate a project in a temporary location with symbolic links to your script and output the generated folder name. The easiest way to use that is to use it in a call to your IDE: [source, bash] ---- code `jbang edit helloworld.java` ---- If you add further dependencies to your file just re-run the edit command and the relevant files will be regenerated with the updated dependencies. Above does require using a shell that allows for variable evaluation, if you are on i.e. Windows then you might prefer using: [source, bash] ---- jbang edit --open=[editor] helloworld.java ---- The editor used will be what is specified as the argument to `--open` or value of `JBANG_EDITOR` environment variable. The editor command must be available on the PATH to be executed from jbang. If you are executing `jbang edit --open=code helloworld.java` a `code` executable (visual studio code) must be on the PATH. Next to this you can pass the full path to the `open` parameter like in `--open=/usr/bin/code`. NOTE: On Windows you might need elevated privileges to create symbolic links. If you don't have permissions then the `edit` option will result in an error. To use it https://stackoverflow.com/a/24353758[enable symbolic links] for your user or run your shell/terminal as administrator to have this feature working. === Install of default vscodium editor [EXPERIMENTAL] If no editor available at all jbang will offer to install https://vscodium.com[VSCodium] (free/libre version of Visual Studio code) with default java extensions enabled in so called https://code.visualstudio.com/docs/editor/portable[""portable mode""]. Portable mode means all the installed binaries and configuration does not affect rest of your system; everything is stored in `~/.jbang/editor`. This automatic install and setup of editor is fully optional and if you have another IDE or editor already installed use it using `jbang edit --open=` or set JBANG_EDITOR environment variable to have jbang use it by default. === Live Editing You can also use `jbang edit --live` and `jbang` will launch your editor while watching for file changes and regenerate the temporary project to pick up changes in dependencies. === IDE and Editor support The `edit` feature been tested with the following IDE's: :sicons: https://simpleicons.org/icons .IDE's and Editors tested with `jbang` [width=75%,frame=none,grid=none] |=== |image:{sicons}/visualstudiocode.svg[50,50] https://code.visualstudio.com[Visual Studio Code] |image:{sicons}/eclipseide.svg[50,50] https://www.eclipse.org/downloads/download.php[Eclipse] |image:{sicons}/intellijidea.svg[50,50] https://www.jetbrains.com/idea/download[IntelliJ Idea] |image:{sicons}/apachenetbeanside.svg[50,50] https://netbeans.apache.org/download/[Apache NetBeans] |image:{sicons}/neovim.svg[50,50] https://github.com/neovim/neovim/wiki/Installing-Neovim[Neovim] w/ https://spacevim.org/use-vim-as-a-java-ide/[spacevim Java] |image:{sicons}/gnuemacs.svg[50,50] https://www.gnu.org/software/emacs/[Emacs] w/ https://www.spacemacs.org[Spacemacs Java] |=== The `edit` feature works with various IDE's - it generates a `build.gradle` to use with IDE's that understands Gradle directly. For speed and consistency `jbang` also generates IDE specific settings. Currently launchers and project files are generated for Eclipse and vscode. Intellij just reads `build.gradle` for now thus to run/debug you will need to manually set it up. Some editors like Code or IDEA are not per default executable / startable from the command line. Here are some helpfull documentations for supporting command line usage of different editors: * https://www.jetbrains.com/help/idea/working-with-the-ide-features-from-command-line.html[CLI support for IDEA] * https://code.visualstudio.com/docs/setup/mac[Terminal support for VS Code on macOS] == Debugging When running `.java` scripts with `jbang` you can pass the `--debug`-flag and the script will enable debug, suspend the execution and wait until you connect a debugger to port 4004. [source, bash] ---- jbang --debug helloworld.java Listening for transport dt_socket at address: 4004 ---- You can change the debug port and host by passing in a interface pattern and number to the debug argument, e.g., `--debug=*:4321`. This will make it use port 4321 and make it listen on all ('*') network interfaces. NOTE: Be sure to put a breakpoint in your IDE/debugger before you connect to make the debugger actually stop when you need it. === Debug jbang itself Java itself will add `JAVA_TOOL_OPTIONS` which will apply to `jbang` too. For finer and more explicit control the scripts, `jbang` will add `JBANG_JAVA_OPTIONS` to the call to `jbang` itself. Thus if you want to enable debug or other details for `jbang` set that environment variable. == Flight Recorder Flight recorder is a feature of the Java VM that lets you gather diagnostic and profiling data about your script. You can use `//JAVA_OPTIONS` to have full control over it; but for the easiest setup `jbang` lets you just run with `--jfr`, e.g., jbang --jfr myapp.java By default `--jfr` will start flight recorder and tell it to dump event recordings to `myapp.jfr` (i.e. using base name of the script as its filename). Then you can use tools like `jvisualvm` or `jmc` to explore the data. If you want to tweak the configuration you can pass flight recorder options, like `jbang --jfr=filename={baseName}.jfr,maxage=24h` where `{baseName}` will be replaced by the filename and then added `maxage=24h` to flight recording options. If you want further control use `//JAVAC_OPTS -XX:StartFlightRecording=` instead. == `java` and `javac` Options If you want to tweak memory settings or enable preview features you can setup the necessary options using `//JAVA_OPTS` and `//COMPILER_OPTS` as in the following example using Java 14 experimental `record` feature: [source, java] ---- ///usr/bin/env jbang ""$0"" ""$@"" ; exit $? //JAVAC_OPTIONS --enable-preview -source 14 <.> //JAVA_OPTIONS --enable-preview // <.> import static java.lang.System.*; public class records { record Point(int x, int y) {} public static void main(String[] args) { var p = new Point(2,4); out.println(p); } } ---- Since Java 9 https://docs.oracle.com/javase/9/tools/java.htm#GUID-3B1CE181-CD30-4178-9602-230B800D4FAE__USINGTHEJDK_JAVA_OPTIONSLAUNCHERENV-F3C0E3BA[JDK_JAVA_OPTIONS] and https://docs.oracle.com/javase/9/tools/javac.htm#GUID-AEEC9F07-CB49-4E96-8BC7-BCC2C7F725C9\\_\\_USINGJDK_JAVAC_OPTIONSENVIRONMENTVA-F3C76845[JDK_JAVAC_OPTIONS] are also picked up by the Java runtime and compiler automatically. For Java 8 and if you want to set explicitly only for `jbang` you can also add flags by setting `JBANG_JAVA_OPTIONS` and `JBANG_JAVAC_OPTIONS` respectively. === (Experimental) Application Class Data Sharing If your scripts uses a lot of classes Class Data Sharing might help on your startup. The following requires Java 13+. Using `--cds` jbang will build the jar with Application Class Data Sharing enabled and when run have it load shared class data. You can put `//CDS` in the java file to enable it by default, or simply use `--cds` to force it or `--no-cds` to turn it off no matter what the jbang script file contains. == Aliases To avoid remembering long paths and to enable easy launch of jbang scripts there is an `alias` command to setup and manage aliases to actual scripts. jbang alias add hello https://github.com/jbangdev/jbang-examples/blob/master/examples/helloworld.java will add an alias named `hello` pointing to that github url which then can be run using `jbang hello`. jbang alias list will show you all the aliases that are defined locally. === Implicit Alias Catalogs The aliases you create are stored locally (see <>), but Jbang can also use remote catalogs. You can access those catalogs explicitly (see <>) but it is much easier to use what we call ""implicit catalogs"", which are aliases that have a special format and Jbang is smart enough to know where to find their definition. Examples: `jbang hello@jbangdev` will run the alias `hello` as defined in `jbang-catalog.json` found in https://github.com/jbangdev/jbang-catalog. This allows anyone to provide a set of jbang scripts defined in their github, gitlab or bitbucket repositories. The full format is `@(/repository)(/branch)(~path)` allowing you to do things like: .Implicit Catalog Examples: |==== |Command | Description |`jbang hello@acme` |`hello` alias found in `acme/jbang-catalog/jbang-catalog.json` of the default branch searched on github, gitlab and bitbucket in that order. |`jbang hello@acme/mycatalog` |`hello` found in `acme/mycatalog/jbang-catalog.json` searched on github, gitlab and bitbucket in that order. |`jbang hello@acme/mycatalog/dev` |`hello` found in `acme/mycatalog/jbang-catalog.json` in the `dev` branch searched on github, gitlab and bitbucket in that order. |`jbang hello@acme~experimental` |`hello` found in `acme/jbang-catalog/experimental/jbang-catalog.json` |==== === Local Alias Catalogs Jbang will also look in the current directory for a `jbang-catalog.json` file and if it exists it will look up any aliases in there too. In fact it will look in several places in the following order: 1. Current directory, `./jbang-catalog.json` 2. In `.jbang/jbang-catalog.json` 3. In the parent directory, `../jbang-catalog.json` 4. In the parent's `.jbang` directory, ../.jbang/jbang-catalog.json` 5. And repeating steps 3 and 4 recursively upwards to the root of the file system 6. As the last step it will look in `$HOME/.jbang/jbang-catalog.json` Jbang will use any aliases defined in those files, but on top of that it will also look at the aliases defined in any catalogs mentioned in those files as well. Aliases defined in the file have preference over aliases found in any catalogs defined in the same file. When you create aliases using `jbang alias add`, or add catalogs using `jbang catalog add` the _same_ ordering will be used to determine where to store the alias or catalog. Btw, this will only take into account _existing_ files! So if no `jbang-catalog.json` file exists in the local directory it will _not_ be created for you, but Jbang will keep looking until it finds a file to use (as a last option it will always be written to `$HOME/.jbang/jbang-catalog.json`). This means that if you want to write the alias to `jbang-catalog.json` in your local folder you will either have to create the file first (eg by running `touch jbang-catalog.json`) or by explicitly specifying the file location: jbang alias add -f jbang-catalog.json hello https://github.com/jbangdev/jbang-examples/blob/master/examples/helloworld.java Btw, the flag `--show-origin` is very useful when listing aliases to find out where exactly an alias is defined: jbang alias list --show-origin == Catalogs Catalogs are lists of Aliases as defined in the previous section, but while the `alias` command is used to manage aliases within a catalog, the `catalog` command is for managing references to catalogs. This is mostly useful when dealing with remote catalogs. You can for example add a catalog like this: jbang catalog add demo https://github.com/jbangdev/jbang-catalog/blob/master/jbang-catalog.json or simply by using the same ""implicit"" catalog system described in <>: jbang catalog add demo jbangdev The aliases in that catalog are now available by adding `@demo` to their names. For example: $ jbang alias list demo env@demo = Dump table of Environment Variables gavsearch@demo = Search search.maven.org for maven artifacts. hello@demo = Script that says hello back for each argument properties@demo = Dump table of System properties $ jbang run hello@demo World! [jbang] Building jar... Hello World! In fact it's possible to run the alias just by using `jbang run hello`, the `@demo` part is only necessary when trying to disambiguate between aliases with the same name from different catalogs. You can list the available catalogs by running: jbang catalog list NB: The output will not only show the catalogs you defined yourself but also the ones that get added implicitly when running aliases as described in the section <>. == Java Agents You can activate a javaagent using `--javaagent=[=]` where agent can be a already packaged agent jar from file, http url or Maven Coordinate. It can also be a jbang script itself where you have put `//JAVAAGENT` to activate agent packaging. You can create a basic agent using `jbang init -t agent myagent.java` to get started. == Bash/Zsh auto-completion If you are using bash or zsh in your terminal you can get auto-completion by running the following: [source, bash] ---- source <(jbang completion) ---- == Caching In previous versions of `jbang`, Java 10+ direct launch of `.java` was used, but since v0.6 `jbang` works with Java 8 and thus it needs to do a separate compile step. Besides now working with Java 8 this also allows to cache the compiled script and thus launch faster on consecutive runs. The caching goes to `~/.jbang/cache` by default, you can run `jbang cache clear` to remove all cache data from this folder. == Install apps [EXPERIMENTAL] Since version 0.56 jbang comes with ability to setup jbang to put scripts/apps into your `PATH` using `jbang app`. This is useful to easily make scripts available from anywhere on any Operating System; To get started run `jbang app setup` this will on Windows modify your system wide `PATH` to include a folder managed by jbang. On bash/zsh based shells it will setup `PATH` in your `bashrc` or `zshrc` file(s.) Once setup, you can use `jbang app install ` to install that script into the jbang managed path. i.e. `jbang app install myscript.java` will add `myscript` as a command you can run. You can also use aliases, like `jbang app install gavsearch@jbangdev`. If you have two script/apps with same name or just want to use a specific name you can use `--name` to control the generated command: `jbang app install --name mvnsearch gavsearch@jbangdev` If you want to see which are already installed use `jbang list` and you can use `jbang uinstall ` to uninstall the script/app. == Build Integration [EXPERIMENTAL] While `jbang` prepares and builds the underlying jar used for launch there is since v0.40 (for now) experimental API allowing user included dependencies to influence the generated jar and possible native image. An example use case enabled by this is to have full Quarkus integration, `jbang quarkuscode.java` will have Quarkus participate to perform its build time optimizations rather than doing it at runtime every time. It works as following: Before the jar is created `jbang` will scan the classpath for `META-INF/jbang-integration.list`. Any classes listed in this file will be loaded and jbang will expect and call the following method on these classes: [source,java] ---- /** * * @param param build dir directory which will be made into a jar when build is done * @param pomFile location of pom.xml representing the projects dependencies * @param dependencies list of GAV to Path of artifact/classpath dependencies * @param nativeImage true if --native been requested * @return Map map of returns; special keys are ""native-image"" which is a and ""files"" to * return native-image to be run and list of files to get written to the output directory. * */ Map postBuild(Path builddir, Path pomFile, List> dependencies, boolean nativeImage) ---- Still very experimental and bound to change. Example of its use can be found in https://github.com/quarkusio/quarkus/pull/11542[Quarkus]. == Cheatsheet You can get examples on running/using `jbang` using https://github.com/cheat/cheat[cheat] command with `cheat jbang`. == FAQ [qanda] Why the name j'bang?:: I was reading up on how to use the new shebang (#!) feature support in Java 10 and came up with the idea of port `kscript` to Java and needed a name. From there came j'bang which is a ""bad"" spelling of how shebang is pronounced in French. Why use gradle resource locators rather than ?:: kscript used it and it's nice as it is a one-liner and easily parsable. How does this compare to ?:: After doing `jbang` I've learned about similar projects and thought it would be nice with some comparison; + https://github.com/scijava/jgo[jgo]: an alternative way to launch jars using maven coordinates. Implemented in python, depends on Java and Maven to be available. Not really for scripting but a novel way to launch java apps already packaged as a maven dependency. + Why would I use Java to write scripts ? Java sucks for that... Use groovy, kotlin, scala, etc. instead!:: Well, does it really suck ? With Java 8 streams, static imports and greatly improved standard java libraries it is very close to what kscript and grape look like. With the following advantages: + * works with plain Java without installing additional compiler/build tools * all IDE's support editing .java files very well, content assist, etc. * great debugging + And to be honest I built `jbang` just to see if I could and get my Java skills refreshed for the newer features in the language. Use it at your own risk :) Why not use normal shebang(`#!`) in the header ?:: You can use normal shebang (`#!/usr/bin/env jbang`) and Java 10+ will actually work with it from the command line. Not recommended though as many tools and especially IDE's will start complaining about syntax errors as they don't ignore the first line in this case. + By using the `//` form it is treated as both a bash/shell file AND a valid java file and thus works everywhere a java file will work. + It's worth noting that Go https://golangcookbook.com/chapters/running/shebang/[uses a similar approach] which is also where I learned it from. HELP! My code formatter keeps breaking my `//` directives!:: When using automated code formatting tools, some care and configuration must be made to prevent the tooling from rewriting and preventing `jbang` from working as expected. + Use the following configuration blocks to correctly configure your tool: + .Configuration Tool Settings: |==== | Formatting Tool | Configuration | Clang Format a| [source] ---- CommentPragmas: '^[^ ]' ---- |==== == Thanks `jbang` was heavily inspired by how `https://github.com/holgerbrandl/kscript[kscript]` by Holger Brand works. ",12522,False,2284.795400812309,median "// Copyright (c) 2017-2018, The Monero Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. 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. // // 3. 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 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. // #include ""device_ledger.hpp"" #include ""log.hpp"" #include ""ringct/rctOps.h"" #include ""cryptonote_basic/account.h"" #include ""cryptonote_basic/subaddress_index.h"" #include #include namespace hw { namespace ledger { #ifdef WITH_DEVICE_LEDGER #undef MONERO_DEFAULT_LOG_CATEGORY #define MONERO_DEFAULT_LOG_CATEGORY ""device.ledger"" /* ===================================================================== */ /* === Debug ==== */ /* ===================================================================== */ #ifdef WIN32 static char *pcsc_stringify_error(LONG rv) { static __thread char out[20]; sprintf_s(out, sizeof(out), ""0x%08lX"", rv); return out; } #endif void set_apdu_verbose(bool verbose) { apdu_verbose = verbose; } #define TRACKD MTRACE(""hw"") #define ASSERT_RV(rv) CHECK_AND_ASSERT_THROW_MES((rv)==SCARD_S_SUCCESS, ""Fail SCard API : ("" << (rv) << "") ""<< pcsc_stringify_error(rv)<<"" Device=""<id<<"", hCard=""<buffer_send[0], this->buffer_send[1], this->buffer_send[2], this->buffer_send[3], this->buffer_send[4] ); const size_t len = strlen(strbuffer); buffer_to_str(strbuffer+len, sizeof(strbuffer)-len, (char*)(this->buffer_send+5), this->length_send-5); MDEBUG( ""CMD :"" << strbuffer); } } void device_ledger::logRESP() { if (apdu_verbose) { char strbuffer[1024]; snprintf(strbuffer, sizeof(strbuffer), ""%.02x%.02x "", this->buffer_recv[this->length_recv-2], this->buffer_recv[this->length_recv-1] ); const size_t len = strlen(strbuffer); buffer_to_str(strbuffer+len, sizeof(strbuffer)-len, (char*)(this->buffer_recv), this->length_recv-2); MDEBUG( ""RESP :"" << strbuffer); } } /* -------------------------------------------------------------- */ device_ledger::device_ledger() { this->id = device_id++; this->hCard = 0; this->hContext = 0; this->reset_buffer(); this->mode = NONE; this->has_view_key = false; MDEBUG( ""Device ""<id <<"" Created""); } device_ledger::~device_ledger() { this->release(); MDEBUG( ""Device ""<id <<"" Destroyed""); } /* ======================================================================= */ /* LOCKER */ /* ======================================================================= */ //automatic lock one more level on device ensuring the current thread is allowed to use it #define AUTO_LOCK_CMD() \\ /* lock both mutexes without deadlock*/ \\ boost::lock(device_locker, command_locker); \\ /* make sure both already-locked mutexes are unlocked at the end of scope */ \\ boost::lock_guard lock1(device_locker, boost::adopt_lock); \\ boost::lock_guard lock2(command_locker, boost::adopt_lock) //lock the device for a long sequence void device_ledger::lock(void) { MDEBUG( ""Ask for LOCKING for device ""<name << "" in thread ""); device_locker.lock(); MDEBUG( ""Device ""<name << "" LOCKed""); } //lock the device for a long sequence bool device_ledger::try_lock(void) { MDEBUG( ""Ask for LOCKING(try) for device ""<name << "" in thread ""); bool r = device_locker.try_lock(); if (r) { MDEBUG( ""Device ""<name << "" LOCKed(try)""); } else { MDEBUG( ""Device ""<name << "" not LOCKed(try)""); } return r; } //lock the device for a long sequence void device_ledger::unlock(void) { try { MDEBUG( ""Ask for UNLOCKING for device ""<name << "" in thread ""); } catch (...) { } device_locker.unlock(); MDEBUG( ""Device ""<name << "" UNLOCKed""); } /* ======================================================================= */ /* MISC */ /* ======================================================================= */ int device_ledger::set_command_header(BYTE ins, BYTE p1, BYTE p2) { reset_buffer(); int offset = 0; this->buffer_send[0] = 0x00; this->buffer_send[1] = ins; this->buffer_send[2] = p1; this->buffer_send[3] = p2; this->buffer_send[4] = 0x00; return 5; } int device_ledger::set_command_header_noopt(BYTE ins, BYTE p1, BYTE p2) { int offset = set_command_header(ins, p1, p2); //options this->buffer_send[offset++] = 0; this->buffer_send[4] = offset - 5; return offset; } void device_ledger::send_simple(BYTE ins, BYTE p1) { this->length_send = set_command_header_noopt(ins, p1); this->exchange(); } bool device_ledger::reset() { send_simple(INS_RESET); return true; } unsigned int device_ledger::exchange(unsigned int ok, unsigned int mask) { LONG rv; unsigned int sw; ASSERT_T0(this->length_send <= BUFFER_SEND_SIZE); logCMD(); this->length_recv = BUFFER_RECV_SIZE; rv = SCardTransmit(this->hCard, SCARD_PCI_T0, this->buffer_send, this->length_send, NULL, this->buffer_recv, &this->length_recv); ASSERT_RV(rv); ASSERT_T0(this->length_recv >= 2); ASSERT_T0(this->length_recv <= BUFFER_RECV_SIZE); logRESP(); sw = (this->buffer_recv[this->length_recv-2]<<8) | this->buffer_recv[this->length_recv-1]; ASSERT_SW(sw,ok,msk); return sw; } void device_ledger::reset_buffer() { this->length_send = 0; memset(this->buffer_send, 0, BUFFER_SEND_SIZE); this->length_recv = 0; memset(this->buffer_recv, 0, BUFFER_RECV_SIZE); } /* ======================================================================= */ /* SETUP/TEARDOWN */ /* ======================================================================= */ bool device_ledger::set_name(const std::string & name) { this->name = name; return true; } const std::string device_ledger::get_name() const { if (this->full_name.empty() || (this->hCard == 0)) { return std::string(""name).append("">""); } return this->full_name; } bool device_ledger::init(void) { #ifdef DEBUG_HWDEVICE this->controle_device = &hw::get_device(""default""); #endif LONG rv; this->release(); rv = SCardEstablishContext(SCARD_SCOPE_SYSTEM,0,0, &this->hContext); ASSERT_RV(rv); MDEBUG( ""Device ""<id <<"" SCardContext created: hContext=""<hContext); this->hCard = 0; return true; } bool device_ledger::release() { this->disconnect(); if (this->hContext) { SCardReleaseContext(this->hContext); MDEBUG( ""Device ""<id <<"" SCardContext released: hContext=""<hContext); this->hContext = 0; this->full_name.clear(); } return true; } bool device_ledger::connect(void) { BYTE pbAtr[MAX_ATR_SIZE]; LPSTR mszReaders; DWORD dwReaders; LONG rv; DWORD dwState, dwProtocol, dwAtrLen, dwReaderLen; this->disconnect(); #ifdef SCARD_AUTOALLOCATE dwReaders = SCARD_AUTOALLOCATE; rv = SCardListReaders(this->hContext, NULL, (LPSTR)&mszReaders, &dwReaders); #else dwReaders = 0; rv = SCardListReaders(this->hContext, NULL, NULL, &dwReaders); if (rv != SCARD_S_SUCCESS) return false; mszReaders = (LPSTR)calloc(dwReaders, sizeof(char)); rv = SCardListReaders(this->hContext, NULL, mszReaders, &dwReaders); #endif if (rv == SCARD_S_SUCCESS) { char* p; const char* prefix = this->name.c_str(); p = mszReaders; MDEBUG( ""Looking for "" << std::string(prefix)); while (*p) { MDEBUG( ""Device Found: "" << std::string(p)); if ((strncmp(prefix, p, strlen(prefix))==0)) { MDEBUG( ""Device Match: "" << std::string(p)); if ((rv = SCardConnect(this->hContext, p, SCARD_SHARE_EXCLUSIVE, SCARD_PROTOCOL_T0, &this->hCard, &dwProtocol))!=SCARD_S_SUCCESS) { break; } MDEBUG( ""Device ""<id <<"" Connected: hCard=""<hCard); dwAtrLen = sizeof(pbAtr); if ((rv = SCardStatus(this->hCard, NULL, &dwReaderLen, &dwState, &dwProtocol, pbAtr, &dwAtrLen))!=SCARD_S_SUCCESS) { break; } MDEBUG( ""Device ""<id <<"" Status OK""); rv = SCARD_S_SUCCESS ; this->full_name = std::string(p); break; } p += strlen(p) +1; } } if (rv == SCARD_S_SUCCESS && mszReaders) { #ifdef SCARD_AUTOALLOCATE SCardFreeMemory(this->hContext, mszReaders); #else free(mszReaders); #endif mszReaders = NULL; } if (rv != SCARD_S_SUCCESS) { if ( hCard) { SCardDisconnect(this->hCard, SCARD_UNPOWER_CARD); MDEBUG( ""Device ""<id <<"" disconnected: hCard=""<hCard); this->hCard = 0; } } ASSERT_RV(rv); this->reset(); #ifdef DEBUG_HWDEVICE cryptonote::account_public_address pubkey; this->get_public_address(pubkey); #endif crypto::secret_key vkey; crypto::secret_key skey; this->get_secret_keys(vkey,skey); return rv==SCARD_S_SUCCESS; } bool device_ledger::disconnect() { if (this->hCard) { SCardDisconnect(this->hCard, SCARD_UNPOWER_CARD); MDEBUG( ""Device ""<id <<"" disconnected: hCard=""<hCard); this->hCard = 0; } return true; } bool device_ledger::set_mode(device_mode mode) { AUTO_LOCK_CMD(); int offset; switch(mode) { case TRANSACTION_CREATE_REAL: case TRANSACTION_CREATE_FAKE: offset = set_command_header_noopt(INS_SET_SIGNATURE_MODE, 1); //account this->buffer_send[offset] = mode; offset += 1; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); this->mode = mode; break; case TRANSACTION_PARSE: case NONE: this->mode = mode; break; default: CHECK_AND_ASSERT_THROW_MES(false, "" device_ledger::set_mode(unsigned int mode): invalid mode: ""<buffer_recv, 32); memmove(pubkey.m_spend_public_key.data, this->buffer_recv+32, 32); return true; } bool device_ledger::get_secret_keys(crypto::secret_key &vkey , crypto::secret_key &skey) { AUTO_LOCK_CMD(); //secret key are represented as fake key on the wallet side memset(vkey.data, 0x00, 32); memset(skey.data, 0xFF, 32); //spcialkey, normal conf handled in decrypt send_simple(INS_GET_KEY, 0x02); //View key is retrievied, if allowed, to speed up blockchain parsing memmove(this->viewkey.data, this->buffer_recv+0, 32); if (is_fake_view_key(this->viewkey)) { MDEBUG(""Have Not view key""); this->has_view_key = false; } else { MDEBUG(""Have view key""); this->has_view_key = true; } #ifdef DEBUG_HWDEVICE memmove(dbg_viewkey.data, this->buffer_recv+0, 32); memmove(dbg_spendkey.data, this->buffer_recv+32, 32); #endif return true; } bool device_ledger::generate_chacha_key(const cryptonote::account_keys &keys, crypto::chacha_key &key) { AUTO_LOCK_CMD(); #ifdef DEBUG_HWDEVICE crypto::chacha_key key_x; cryptonote::account_keys keys_x = hw::ledger::decrypt(keys); this->controle_device->generate_chacha_key(keys_x, key_x); #endif send_simple(INS_GET_CHACHA8_PREKEY); char prekey[200]; memmove(prekey, &this->buffer_recv[0], 200); crypto::generate_chacha_key_prehashed(&prekey[0], sizeof(prekey), key); #ifdef DEBUG_HWDEVICE hw::ledger::check32(""generate_chacha_key_prehashed"", ""key"", (char*)key_x.data(), (char*)key.data()); #endif return true; } /* ======================================================================= */ /* SUB ADDRESS */ /* ======================================================================= */ bool device_ledger::derive_subaddress_public_key(const crypto::public_key &pub, const crypto::key_derivation &derivation, const std::size_t output_index, crypto::public_key &derived_pub){ AUTO_LOCK_CMD(); #ifdef DEBUG_HWDEVICE const crypto::public_key pub_x = pub; crypto::key_derivation derivation_x; if ((this->mode == TRANSACTION_PARSE) && has_view_key) { derivation_x = derivation; } else { derivation_x = hw::ledger::decrypt(derivation); } const std::size_t output_index_x = output_index; crypto::public_key derived_pub_x; hw::ledger::log_hexbuffer(""derive_subaddress_public_key: [[IN]] pub "", pub_x.data, 32); hw::ledger::log_hexbuffer(""derive_subaddress_public_key: [[IN]] derivation"", derivation_x.data, 32); hw::ledger::log_message (""derive_subaddress_public_key: [[IN]] index "", std::to_string((int)output_index_x)); this->controle_device->derive_subaddress_public_key(pub_x, derivation_x,output_index_x,derived_pub_x); hw::ledger::log_hexbuffer(""derive_subaddress_public_key: [[OUT]] derived_pub"", derived_pub_x.data, 32); #endif if ((this->mode == TRANSACTION_PARSE) && has_view_key) { //If we are in TRANSACTION_PARSE, the given derivation has been retrieved uncrypted (wihtout the help //of the device), so continue that way. MDEBUG( ""derive_subaddress_public_key : PARSE mode with known viewkey""); crypto::derive_subaddress_public_key(pub, derivation, output_index,derived_pub); } else { int offset = set_command_header_noopt(INS_DERIVE_SUBADDRESS_PUBLIC_KEY); //pub memmove(this->buffer_send+offset, pub.data, 32); offset += 32; //derivation memmove(this->buffer_send+offset, derivation.data, 32); offset += 32; //index this->buffer_send[offset+0] = output_index>>24; this->buffer_send[offset+1] = output_index>>16; this->buffer_send[offset+2] = output_index>>8; this->buffer_send[offset+3] = output_index>>0; offset += 4; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); //pub key memmove(derived_pub.data, &this->buffer_recv[0], 32); } #ifdef DEBUG_HWDEVICE hw::ledger::check32(""derive_subaddress_public_key"", ""derived_pub"", derived_pub_x.data, derived_pub.data); #endif return true; } crypto::public_key device_ledger::get_subaddress_spend_public_key(const cryptonote::account_keys& keys, const cryptonote::subaddress_index &index) { AUTO_LOCK_CMD(); crypto::public_key D; #ifdef DEBUG_HWDEVICE const cryptonote::account_keys keys_x = hw::ledger::decrypt(keys); const cryptonote::subaddress_index index_x = index; crypto::public_key D_x; hw::ledger::log_hexbuffer(""get_subaddress_spend_public_key: [[IN]] keys.m_view_secret_key "", keys_x.m_view_secret_key.data,32); hw::ledger::log_hexbuffer(""get_subaddress_spend_public_key: [[IN]] keys.m_spend_secret_key"", keys_x.m_spend_secret_key.data,32); hw::ledger::log_message (""get_subaddress_spend_public_key: [[IN]] index "", std::to_string(index_x.major)+"".""+std::to_string(index_x.minor)); D_x = this->controle_device->get_subaddress_spend_public_key(keys_x, index_x); hw::ledger::log_hexbuffer(""get_subaddress_spend_public_key: [[OUT]] derivation "", D_x.data, 32); #endif if (index.is_zero()) { D = keys.m_account_address.m_spend_public_key; } else { int offset = set_command_header_noopt(INS_GET_SUBADDRESS_SPEND_PUBLIC_KEY); //index static_assert(sizeof(cryptonote::subaddress_index) == 8, ""cryptonote::subaddress_index shall be 8 bytes length""); memmove(this->buffer_send+offset, &index, sizeof(cryptonote::subaddress_index)); offset +=8 ; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); memmove(D.data, &this->buffer_recv[0], 32); } #ifdef DEBUG_HWDEVICE hw::ledger::check32(""get_subaddress_spend_public_key"", ""D"", D_x.data, D.data); #endif return D; } std::vector device_ledger::get_subaddress_spend_public_keys(const cryptonote::account_keys &keys, uint32_t account, uint32_t begin, uint32_t end) { std::vector pkeys; cryptonote::subaddress_index index = {account, begin}; crypto::public_key D; for (uint32_t idx = begin; idx < end; ++idx) { index.minor = idx; D = this->get_subaddress_spend_public_key(keys, index); pkeys.push_back(D); } return pkeys; } cryptonote::account_public_address device_ledger::get_subaddress(const cryptonote::account_keys& keys, const cryptonote::subaddress_index &index) { AUTO_LOCK_CMD(); cryptonote::account_public_address address; #ifdef DEBUG_HWDEVICE const cryptonote::account_keys keys_x = hw::ledger::decrypt(keys); const cryptonote::subaddress_index index_x = index; cryptonote::account_public_address address_x; hw::ledger::log_hexbuffer(""get_subaddress: [[IN]] keys.m_view_secret_key "", keys_x.m_view_secret_key.data, 32); hw::ledger::log_hexbuffer(""get_subaddress: [[IN]] keys.m_view_public_key"", keys_x.m_account_address.m_view_public_key.data, 32); hw::ledger::log_hexbuffer(""get_subaddress: [[IN]] keys.m_view_secret_key "", keys_x.m_view_secret_key.data, 32); hw::ledger::log_hexbuffer(""get_subaddress: [[IN]] keys.m_spend_public_key"", keys_x.m_account_address.m_spend_public_key.data, 32); hw::ledger::log_message (""get_subaddress: [[IN]] index "", std::to_string(index_x.major)+"".""+std::to_string(index_x.minor)); address_x = this->controle_device->get_subaddress(keys_x, index_x); hw::ledger::log_hexbuffer(""get_subaddress: [[OUT]] keys.m_view_public_key "", address_x.m_view_public_key.data, 32); hw::ledger::log_hexbuffer(""get_subaddress: [[OUT]] keys.m_spend_public_key"", address_x.m_spend_public_key.data, 32); #endif if (index.is_zero()) { address = keys.m_account_address; } else { int offset = set_command_header_noopt(INS_GET_SUBADDRESS); //index static_assert(sizeof(cryptonote::subaddress_index) == 8, ""cryptonote::subaddress_index shall be 8 bytes length""); memmove(this->buffer_send+offset, &index, sizeof(cryptonote::subaddress_index)); offset +=8 ; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); memmove(address.m_view_public_key.data, &this->buffer_recv[0], 32); memmove(address.m_spend_public_key.data, &this->buffer_recv[32], 32); } #ifdef DEBUG_HWDEVICE hw::ledger::check32(""get_subaddress"", ""address.m_view_public_key.data"", address_x.m_view_public_key.data, address.m_view_public_key.data); hw::ledger::check32(""get_subaddress"", ""address.m_spend_public_key.data"", address_x.m_spend_public_key.data, address.m_spend_public_key.data); #endif return address; } crypto::secret_key device_ledger::get_subaddress_secret_key(const crypto::secret_key &sec, const cryptonote::subaddress_index &index) { AUTO_LOCK_CMD(); crypto::secret_key sub_sec; #ifdef DEBUG_HWDEVICE const crypto::secret_key sec_x = hw::ledger::decrypt(sec); const cryptonote::subaddress_index index_x = index; crypto::secret_key sub_sec_x; hw::ledger::log_message (""get_subaddress_secret_key: [[IN]] index "", std::to_string(index.major)+"".""+std::to_string(index.minor)); hw::ledger::log_hexbuffer(""get_subaddress_secret_key: [[IN]] sec "", sec_x.data, 32); sub_sec_x = this->controle_device->get_subaddress_secret_key(sec_x, index_x); hw::ledger::log_hexbuffer(""get_subaddress_secret_key: [[OUT]] sub_sec"", sub_sec_x.data, 32); #endif int offset = set_command_header_noopt(INS_GET_SUBADDRESS_SECRET_KEY); //sec memmove(this->buffer_send+offset, sec.data, 32); offset += 32; //index static_assert(sizeof(cryptonote::subaddress_index) == 8, ""cryptonote::subaddress_index shall be 8 bytes length""); memmove(this->buffer_send+offset, &index, sizeof(cryptonote::subaddress_index)); offset +=8 ; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); memmove(sub_sec.data, &this->buffer_recv[0], 32); #ifdef DEBUG_HWDEVICE crypto::secret_key sub_sec_clear = hw::ledger::decrypt(sub_sec); hw::ledger::check32(""get_subaddress_secret_key"", ""sub_sec"", sub_sec_x.data, sub_sec_clear.data); #endif return sub_sec; } /* ======================================================================= */ /* DERIVATION & KEY */ /* ======================================================================= */ bool device_ledger::verify_keys(const crypto::secret_key &secret_key, const crypto::public_key &public_key) { AUTO_LOCK_CMD(); int offset, sw; offset = set_command_header_noopt(INS_VERIFY_KEY); //sec memmove(this->buffer_send+offset, secret_key.data, 32); offset += 32; //pub memmove(this->buffer_send+offset, public_key.data, 32); offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); uint32_t verified = this->buffer_recv[0] << 24 | this->buffer_recv[1] << 16 | this->buffer_recv[2] << 8 | this->buffer_recv[3] << 0 ; return verified == 1; } bool device_ledger::scalarmultKey(rct::key & aP, const rct::key &P, const rct::key &a) { AUTO_LOCK_CMD(); #ifdef DEBUG_HWDEVICE const rct::key P_x = P; const rct::key a_x = hw::ledger::decrypt(a); rct::key aP_x; hw::ledger::log_hexbuffer(""scalarmultKey: [[IN]] P "", (char*)P_x.bytes, 32); hw::ledger::log_hexbuffer(""scalarmultKey: [[IN]] a "", (char*)a_x.bytes, 32); this->controle_device->scalarmultKey(aP_x, P_x, a_x); hw::ledger::log_hexbuffer(""scalarmultKey: [[OUT]] aP"", (char*)aP_x.bytes, 32); #endif int offset = set_command_header_noopt(INS_SECRET_SCAL_MUL_KEY); //pub memmove(this->buffer_send+offset, P.bytes, 32); offset += 32; //sec memmove(this->buffer_send+offset, a.bytes, 32); offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); //pub key memmove(aP.bytes, &this->buffer_recv[0], 32); #ifdef DEBUG_HWDEVICE hw::ledger::check32(""scalarmultKey"", ""mulkey"", (char*)aP_x.bytes, (char*)aP.bytes); #endif return true; } bool device_ledger::scalarmultBase(rct::key &aG, const rct::key &a) { AUTO_LOCK_CMD(); #ifdef DEBUG_HWDEVICE const rct::key a_x = hw::ledger::decrypt(a); rct::key aG_x; hw::ledger::log_hexbuffer(""scalarmultKey: [[IN]] a "", (char*)a_x.bytes, 32); this->controle_device->scalarmultBase(aG_x, a_x); hw::ledger::log_hexbuffer(""scalarmultKey: [[OUT]] aG"", (char*)aG_x.bytes, 32); #endif int offset = set_command_header_noopt(INS_SECRET_SCAL_MUL_BASE); //sec memmove(this->buffer_send+offset, a.bytes, 32); offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); //pub key memmove(aG.bytes, &this->buffer_recv[0], 32); #ifdef DEBUG_HWDEVICE hw::ledger::check32(""scalarmultBase"", ""mulkey"", (char*)aG_x.bytes, (char*)aG.bytes); #endif return true; } bool device_ledger::sc_secret_add( crypto::secret_key &r, const crypto::secret_key &a, const crypto::secret_key &b) { AUTO_LOCK_CMD(); #ifdef DEBUG_HWDEVICE const crypto::secret_key a_x = hw::ledger::decrypt(a); const crypto::secret_key b_x = hw::ledger::decrypt(b); crypto::secret_key r_x; this->controle_device->sc_secret_add(r_x, a_x, b_x); #endif int offset = set_command_header_noopt(INS_SECRET_KEY_ADD); //sec key memmove(this->buffer_send+offset, a.data, 32); offset += 32; //sec key memmove(this->buffer_send+offset, b.data, 32); offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); //pub key memmove(r.data, &this->buffer_recv[0], 32); #ifdef DEBUG_HWDEVICE crypto::secret_key r_clear = hw::ledger::decrypt(r); hw::ledger::check32(""sc_secret_add"", ""r"", r_x.data, r_clear.data); #endif return true; } crypto::secret_key device_ledger::generate_keys(crypto::public_key &pub, crypto::secret_key &sec, const crypto::secret_key& recovery_key, bool recover) { AUTO_LOCK_CMD(); if (recover) { throw std::runtime_error(""device generate key does not support recover""); } #ifdef DEBUG_HWDEVICE bool recover_x = recover; const crypto::secret_key recovery_key_x = recovery_key; crypto::public_key pub_x; crypto::secret_key sec_x; #endif send_simple(INS_GENERATE_KEYPAIR); //pub key memmove(pub.data, &this->buffer_recv[0], 32); memmove(sec.data, &this->buffer_recv[32], 32); #ifdef DEBUG_HWDEVICE crypto::secret_key sec_clear = hw::ledger::decrypt(sec); sec_x = sec_clear; crypto::secret_key_to_public_key(sec_x,pub_x); hw::ledger::check32(""generate_keys"", ""pub"", pub_x.data, pub.data); #endif return sec; } bool device_ledger::generate_key_derivation(const crypto::public_key &pub, const crypto::secret_key &sec, crypto::key_derivation &derivation) { AUTO_LOCK_CMD(); bool r = false; #ifdef DEBUG_HWDEVICE const crypto::public_key pub_x = pub; const crypto::secret_key sec_x = hw::ledger::decrypt(sec); crypto::key_derivation derivation_x; hw::ledger::log_hexbuffer(""generate_key_derivation: [[IN]] pub "", pub_x.data, 32); hw::ledger::log_hexbuffer(""generate_key_derivation: [[IN]] sec "", sec_x.data, 32); this->controle_device->generate_key_derivation(pub_x, sec_x, derivation_x); hw::ledger::log_hexbuffer(""generate_key_derivation: [[OUT]] derivation"", derivation_x.data, 32); #endif if ((this->mode == TRANSACTION_PARSE) && has_view_key) { //A derivation is resquested in PASRE mode and we have the view key, //so do that wihtout the device and return the derivation unencrypted. MDEBUG( ""generate_key_derivation : PARSE mode with known viewkey""); //Note derivation in PARSE mode can only happen with viewkey, so assert it! assert(is_fake_view_key(sec)); r = crypto::generate_key_derivation(pub, this->viewkey, derivation); } else { int offset = set_command_header_noopt(INS_GEN_KEY_DERIVATION); //pub memmove(this->buffer_send+offset, pub.data, 32); offset += 32; //sec memmove(this->buffer_send+offset, sec.data, 32); offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); //derivattion data memmove(derivation.data, &this->buffer_recv[0], 32); r = true; } #ifdef DEBUG_HWDEVICE crypto::key_derivation derivation_clear ; if ((this->mode == TRANSACTION_PARSE) && has_view_key) { derivation_clear = derivation; }else { derivation_clear = hw::ledger::decrypt(derivation); } hw::ledger::check32(""generate_key_derivation"", ""derivation"", derivation_x.data, derivation_clear.data); #endif return r; } bool device_ledger::conceal_derivation(crypto::key_derivation &derivation, const crypto::public_key &tx_pub_key, const std::vector &additional_tx_pub_keys, const crypto::key_derivation &main_derivation, const std::vector &additional_derivations) { const crypto::public_key *pkey=NULL; if (derivation == main_derivation) { pkey = &tx_pub_key; MDEBUG(""conceal derivation with main tx pub key""); } else { for(size_t n=0; n < additional_derivations.size();++n) { if(derivation == additional_derivations[n]) { pkey = &additional_tx_pub_keys[n]; MDEBUG(""conceal derivation with additionnal tx pub key""); break; } } } ASSERT_X(pkey, ""Mismatched derivation on scan info""); return this->generate_key_derivation(*pkey, crypto::null_skey, derivation); } bool device_ledger::derivation_to_scalar(const crypto::key_derivation &derivation, const size_t output_index, crypto::ec_scalar &res) { AUTO_LOCK_CMD(); #ifdef DEBUG_HWDEVICE const crypto::key_derivation derivation_x = hw::ledger::decrypt(derivation); const size_t output_index_x = output_index; crypto::ec_scalar res_x; hw::ledger::log_hexbuffer(""derivation_to_scalar: [[IN]] derivation "", derivation_x.data, 32); hw::ledger::log_message (""derivation_to_scalar: [[IN]] output_index "", std::to_string(output_index_x)); this->controle_device->derivation_to_scalar(derivation_x, output_index_x, res_x); hw::ledger::log_hexbuffer(""derivation_to_scalar: [[OUT]] res "", res_x.data, 32); #endif int offset = set_command_header_noopt(INS_DERIVATION_TO_SCALAR); //derivattion memmove(this->buffer_send+offset, derivation.data, 32); offset += 32; //index this->buffer_send[offset+0] = output_index>>24; this->buffer_send[offset+1] = output_index>>16; this->buffer_send[offset+2] = output_index>>8; this->buffer_send[offset+3] = output_index>>0; offset += 4; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); //derivattion data memmove(res.data, &this->buffer_recv[0], 32); #ifdef DEBUG_HWDEVICE crypto::ec_scalar res_clear = hw::ledger::decrypt(res); hw::ledger::check32(""derivation_to_scalar"", ""res"", res_x.data, res_clear.data); #endif return true; } bool device_ledger::derive_secret_key(const crypto::key_derivation &derivation, const std::size_t output_index, const crypto::secret_key &sec, crypto::secret_key &derived_sec) { AUTO_LOCK_CMD(); #ifdef DEBUG_HWDEVICE const crypto::key_derivation derivation_x = hw::ledger::decrypt(derivation); const std::size_t output_index_x = output_index; const crypto::secret_key sec_x = hw::ledger::decrypt(sec); crypto::secret_key derived_sec_x; hw::ledger::log_hexbuffer(""derive_secret_key: [[IN]] derivation "", derivation_x.data, 32); hw::ledger::log_message (""derive_secret_key: [[IN]] index "", std::to_string(output_index_x)); hw::ledger::log_hexbuffer(""derive_secret_key: [[IN]] sec "", sec_x.data, 32); this->controle_device->derive_secret_key(derivation_x, output_index_x, sec_x, derived_sec_x); hw::ledger::log_hexbuffer(""derive_secret_key: [[OUT]] derived_sec"", derived_sec_x.data, 32); #endif int offset = set_command_header_noopt(INS_DERIVE_SECRET_KEY); //derivation memmove(this->buffer_send+offset, derivation.data, 32); offset += 32; //index this->buffer_send[offset+0] = output_index>>24; this->buffer_send[offset+1] = output_index>>16; this->buffer_send[offset+2] = output_index>>8; this->buffer_send[offset+3] = output_index>>0; offset += 4; //sec memmove(this->buffer_send+offset, sec.data, 32); offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); //pub key memmove(derived_sec.data, &this->buffer_recv[0], 32); #ifdef DEBUG_HWDEVICE crypto::secret_key derived_sec_clear = hw::ledger::decrypt(derived_sec); hw::ledger::check32(""derive_secret_key"", ""derived_sec"", derived_sec_x.data, derived_sec_clear.data); #endif return true; } bool device_ledger::derive_public_key(const crypto::key_derivation &derivation, const std::size_t output_index, const crypto::public_key &pub, crypto::public_key &derived_pub){ AUTO_LOCK_CMD(); #ifdef DEBUG_HWDEVICE const crypto::key_derivation derivation_x = hw::ledger::decrypt(derivation); const std::size_t output_index_x = output_index; const crypto::public_key pub_x = pub; crypto::public_key derived_pub_x; hw::ledger::log_hexbuffer(""derive_public_key: [[IN]] derivation "", derivation_x.data, 32); hw::ledger::log_message (""derive_public_key: [[IN]] output_index"", std::to_string(output_index_x)); hw::ledger::log_hexbuffer(""derive_public_key: [[IN]] pub "", pub_x.data, 32); this->controle_device->derive_public_key(derivation_x, output_index_x, pub_x, derived_pub_x); hw::ledger::log_hexbuffer(""derive_public_key: [[OUT]] derived_pub "", derived_pub_x.data, 32); #endif int offset = set_command_header_noopt(INS_DERIVE_PUBLIC_KEY); //derivation memmove(this->buffer_send+offset, derivation.data, 32); offset += 32; //index this->buffer_send[offset+0] = output_index>>24; this->buffer_send[offset+1] = output_index>>16; this->buffer_send[offset+2] = output_index>>8; this->buffer_send[offset+3] = output_index>>0; offset += 4; //pub memmove(this->buffer_send+offset, pub.data, 32); offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); //pub key memmove(derived_pub.data, &this->buffer_recv[0], 32); #ifdef DEBUG_HWDEVICE hw::ledger::check32(""derive_public_key"", ""derived_pub"", derived_pub_x.data, derived_pub.data); #endif return true; } bool device_ledger::secret_key_to_public_key(const crypto::secret_key &sec, crypto::public_key &pub) { AUTO_LOCK_CMD(); #ifdef DEBUG_HWDEVICE const crypto::secret_key sec_x = hw::ledger::decrypt(sec); crypto::public_key pub_x; hw::ledger::log_hexbuffer(""secret_key_to_public_key: [[IN]] sec "", sec_x.data, 32); bool rc = this->controle_device->secret_key_to_public_key(sec_x, pub_x); hw::ledger::log_hexbuffer(""secret_key_to_public_key: [[OUT]] pub"", pub_x.data, 32); if (!rc){ hw::ledger::log_message(""secret_key_to_public_key"", ""secret_key rejected""); } #endif int offset = set_command_header_noopt(INS_SECRET_KEY_TO_PUBLIC_KEY); //sec key memmove(this->buffer_send+offset, sec.data, 32); offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); //pub key memmove(pub.data, &this->buffer_recv[0], 32); #ifdef DEBUG_HWDEVICE hw::ledger::check32(""secret_key_to_public_key"", ""pub"", pub_x.data, pub.data); #endif return true; } bool device_ledger::generate_key_image(const crypto::public_key &pub, const crypto::secret_key &sec, crypto::key_image &image){ AUTO_LOCK_CMD(); #ifdef DEBUG_HWDEVICE const crypto::public_key pub_x = pub; const crypto::secret_key sec_x = hw::ledger::decrypt(sec); crypto::key_image image_x; hw::ledger::log_hexbuffer(""generate_key_image: [[IN]] pub "", pub_x.data, 32); hw::ledger::log_hexbuffer(""generate_key_image: [[IN]] sec "", sec_x.data, 32); this->controle_device->generate_key_image(pub_x, sec_x, image_x); hw::ledger::log_hexbuffer(""generate_key_image: [[OUT]] image "", image_x.data, 32); #endif int offset = set_command_header_noopt(INS_GEN_KEY_IMAGE); //pub memmove(this->buffer_send+offset, pub.data, 32); offset += 32; //sec memmove(this->buffer_send+offset, sec.data, 32); offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); //pub key memmove(image.data, &this->buffer_recv[0], 32); #ifdef DEBUG_HWDEVICE hw::ledger::check32(""generate_key_image"", ""image"", image_x.data, image.data); #endif return true; } /* ======================================================================= */ /* TRANSACTION */ /* ======================================================================= */ bool device_ledger::open_tx(crypto::secret_key &tx_key) { AUTO_LOCK_CMD(); key_map.clear(); int offset = set_command_header_noopt(INS_OPEN_TX, 0x01); //account this->buffer_send[offset+0] = 0x00; this->buffer_send[offset+1] = 0x00; this->buffer_send[offset+2] = 0x00; this->buffer_send[offset+3] = 0x00; offset += 4; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); memmove(tx_key.data, &this->buffer_recv[32], 32); return true; } bool device_ledger::encrypt_payment_id(crypto::hash8 &payment_id, const crypto::public_key &public_key, const crypto::secret_key &secret_key) { AUTO_LOCK_CMD(); #ifdef DEBUG_HWDEVICE const crypto::public_key public_key_x = public_key; const crypto::secret_key secret_key_x = hw::ledger::decrypt(secret_key); crypto::hash8 payment_id_x = payment_id; this->controle_device->encrypt_payment_id(payment_id_x, public_key_x, secret_key_x); #endif int offset = set_command_header_noopt(INS_STEALTH); //pub memmove(&this->buffer_send[offset], public_key.data, 32); offset += 32; //sec memmove(&this->buffer_send[offset], secret_key.data, 32); offset += 32; //id memmove(&this->buffer_send[offset], payment_id.data, 8); offset += 8; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); memmove(payment_id.data, &this->buffer_recv[0], 8); #ifdef DEBUG_HWDEVICE hw::ledger::check8(""stealth"", ""payment_id"", payment_id_x.data, payment_id.data); #endif return true; } bool device_ledger::add_output_key_mapping(const crypto::public_key &Aout, const crypto::public_key &Bout, const bool is_subaddress, const size_t real_output_index, const rct::key &amount_key, const crypto::public_key &out_eph_public_key) { AUTO_LOCK_CMD(); key_map.add(ABPkeys(rct::pk2rct(Aout),rct::pk2rct(Bout), is_subaddress, real_output_index, rct::pk2rct(out_eph_public_key), amount_key)); return true; } bool device_ledger::ecdhEncode(rct::ecdhTuple & unmasked, const rct::key & AKout) { AUTO_LOCK_CMD(); #ifdef DEBUG_HWDEVICE const rct::key AKout_x = hw::ledger::decrypt(AKout); rct::ecdhTuple unmasked_x = unmasked; this->controle_device->ecdhEncode(unmasked_x, AKout_x); #endif int offset = set_command_header_noopt(INS_BLIND); // AKout memmove(this->buffer_send+offset, AKout.bytes, 32); offset += 32; //mask k memmove(this->buffer_send+offset, unmasked.mask.bytes, 32); offset += 32; //value v memmove(this->buffer_send+offset, unmasked.amount.bytes, 32); offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); memmove(unmasked.amount.bytes, &this->buffer_recv[0], 32); memmove(unmasked.mask.bytes, &this->buffer_recv[32], 32); #ifdef DEBUG_HWDEVICE hw::ledger::check32(""ecdhEncode"", ""amount"", (char*)unmasked_x.amount.bytes, (char*)unmasked.amount.bytes); hw::ledger::check32(""ecdhEncode"", ""mask"", (char*)unmasked_x.mask.bytes, (char*)unmasked.mask.bytes); hw::ledger::log_hexbuffer(""Blind AKV input"", (char*)&this->buffer_recv[64], 3*32); #endif return true; } bool device_ledger::ecdhDecode(rct::ecdhTuple & masked, const rct::key & AKout) { AUTO_LOCK_CMD(); #ifdef DEBUG_HWDEVICE const rct::key AKout_x = hw::ledger::decrypt(AKout); rct::ecdhTuple masked_x = masked; this->controle_device->ecdhDecode(masked_x, AKout_x); #endif int offset = set_command_header_noopt(INS_UNBLIND); // AKout memmove(this->buffer_send+offset, AKout.bytes, 32); offset += 32; //mask k memmove(this->buffer_send+offset, masked.mask.bytes, 32); offset += 32; //value v memmove(this->buffer_send+offset, masked.amount.bytes, 32); offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); memmove(masked.amount.bytes, &this->buffer_recv[0], 32); memmove(masked.mask.bytes, &this->buffer_recv[32], 32); #ifdef DEBUG_HWDEVICE hw::ledger::check32(""ecdhDecode"", ""amount"", (char*)masked_x.amount.bytes, (char*)masked.amount.bytes); hw::ledger::check32(""ecdhDecode"", ""mask"", (char*)masked_x.mask.bytes,(char*) masked.mask.bytes); #endif return true; } bool device_ledger::mlsag_prehash(const std::string &blob, size_t inputs_size, size_t outputs_size, const rct::keyV &hashes, const rct::ctkeyV &outPk, rct::key &prehash) { AUTO_LOCK_CMD(); unsigned int data_offset, C_offset, kv_offset, i; const char *data; #ifdef DEBUG_HWDEVICE const std::string blob_x = blob; size_t inputs_size_x = inputs_size; size_t outputs_size_x = outputs_size; const rct::keyV hashes_x = hashes; const rct::ctkeyV outPk_x = outPk; rct::key prehash_x; this->controle_device->mlsag_prehash(blob_x, inputs_size_x, outputs_size_x, hashes_x, outPk_x, prehash_x); if (inputs_size) { log_message(""mlsag_prehash"", (std::string(""inputs_size not null: "") + std::to_string(inputs_size)).c_str()); } this->key_map.log(); #endif data = blob.data(); // ====== u8 type, varint txnfee ====== int offset = set_command_header(INS_VALIDATE, 0x01, 0x01); //options this->buffer_send[offset] = (inputs_size == 0)?0x00:0x80; offset += 1; //type uint8_t type = data[0]; this->buffer_send[offset] = data[0]; offset += 1; //txnfee data_offset = 1; while (data[data_offset]&0x80) { this->buffer_send[offset] = data[data_offset]; offset += 1; data_offset += 1; } this->buffer_send[offset] = data[data_offset]; offset += 1; data_offset += 1; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); //pseudoOuts if ((type == rct::RCTTypeSimple) || (type == rct::RCTTypeSimpleBulletproof)) { for ( i = 0; i < inputs_size; i++) { offset = set_command_header(INS_VALIDATE, 0x01, i+2); //options this->buffer_send[offset] = (i==inputs_size-1)? 0x00:0x80; offset += 1; //pseudoOut memmove(this->buffer_send+offset, data+data_offset,32); offset += 32; data_offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); } } // ====== Aout, Bout, AKout, C, v, k ====== kv_offset = data_offset; C_offset = kv_offset+ (32*2)*outputs_size; for ( i = 0; i < outputs_size; i++) { ABPkeys outKeys; bool found; found = this->key_map.find(outPk[i].dest, outKeys); if (!found) { log_hexbuffer(""Pout not found"", (char*)outPk[i].dest.bytes, 32); CHECK_AND_ASSERT_THROW_MES(found, ""Pout not found""); } offset = set_command_header(INS_VALIDATE, 0x02, i+1); //options this->buffer_send[offset] = (i==outputs_size-1)? 0x00:0x80 ; offset += 1; if (found) { //is_subaddress this->buffer_send[offset] = outKeys.is_subaddress; offset++; //Aout memmove(this->buffer_send+offset, outKeys.Aout.bytes, 32); offset+=32; //Bout memmove(this->buffer_send+offset, outKeys.Bout.bytes, 32); offset+=32; //AKout memmove(this->buffer_send+offset, outKeys.AKout.bytes, 32); offset+=32; } else { // dummy: is_subaddress Aout Bout AKout offset += 1+32*3; } //C memmove(this->buffer_send+offset, data+C_offset,32); offset += 32; C_offset += 32; //k memmove(this->buffer_send+offset, data+kv_offset,32); offset += 32; //v kv_offset += 32; memmove(this->buffer_send+offset, data+kv_offset,32); offset += 32; kv_offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); #ifdef DEBUG_HWDEVICE hw::ledger::log_hexbuffer(""Prehash AKV input"", (char*)&this->buffer_recv[64], 3*32); #endif } // ====== C[], message, proof====== C_offset = kv_offset; for (i = 0; i < outputs_size; i++) { offset = set_command_header(INS_VALIDATE, 0x03, i+1); //options this->buffer_send[offset] = 0x80 ; offset += 1; //C memmove(this->buffer_send+offset, data+C_offset,32); offset += 32; C_offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); } offset = set_command_header_noopt(INS_VALIDATE, 0x03, i+1); //message memmove(this->buffer_send+offset, hashes[0].bytes,32); offset += 32; //proof memmove(this->buffer_send+offset, hashes[2].bytes,32); offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); memmove(prehash.bytes, this->buffer_recv, 32); #ifdef DEBUG_HWDEVICE hw::ledger::check32(""mlsag_prehash"", ""prehash"", (char*)prehash_x.bytes, (char*)prehash.bytes); #endif return true; } bool device_ledger::mlsag_prepare(const rct::key &H, const rct::key &xx, rct::key &a, rct::key &aG, rct::key &aHP, rct::key &II) { AUTO_LOCK_CMD(); unsigned char options; #ifdef DEBUG_HWDEVICE const rct::key H_x = H; const rct::key xx_x = hw::ledger::decrypt(xx); rct::key a_x; rct::key aG_x; rct::key aHP_x; rct::key II_x; #endif int offset = set_command_header_noopt(INS_MLSAG, 0x01); //value H memmove(this->buffer_send+offset, H.bytes, 32); offset += 32; //mask xin memmove(this->buffer_send+offset, xx.bytes, 32); offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); memmove(a.bytes, &this->buffer_recv[32*0], 32); memmove(aG.bytes, &this->buffer_recv[32*1], 32); memmove(aHP.bytes, &this->buffer_recv[32*2], 32); memmove(II.bytes, &this->buffer_recv[32*3], 32); #ifdef DEBUG_HWDEVICE a_x = hw::ledger::decrypt(a); rct::scalarmultBase(aG_x, a_x); rct::scalarmultKey(aHP_x, H_x, a_x); rct::scalarmultKey(II_x, H_x, xx_x); hw::ledger::check32(""mlsag_prepare"", ""AG"", (char*)aG_x.bytes, (char*)aG.bytes); hw::ledger::check32(""mlsag_prepare"", ""aHP"", (char*)aHP_x.bytes, (char*)aHP.bytes); hw::ledger::check32(""mlsag_prepare"", ""II"", (char*)II_x.bytes, (char*)II.bytes); #endif return true; } bool device_ledger::mlsag_prepare(rct::key &a, rct::key &aG) { AUTO_LOCK_CMD(); unsigned char options; #ifdef DEBUG_HWDEVICE rct::key a_x; rct::key aG_x; #endif send_simple(INS_MLSAG, 0x01); memmove(a.bytes, &this->buffer_recv[32*0], 32); memmove(aG.bytes, &this->buffer_recv[32*1], 32); #ifdef DEBUG_HWDEVICE a_x = hw::ledger::decrypt(a); rct::scalarmultBase(aG_x, a_x); hw::ledger::check32(""mlsag_prepare"", ""AG"", (char*)aG_x.bytes, (char*)aG.bytes); #endif return true; } bool device_ledger::mlsag_hash(const rct::keyV &long_message, rct::key &c) { AUTO_LOCK_CMD(); unsigned char options; size_t cnt; #ifdef DEBUG_HWDEVICE const rct::keyV long_message_x = long_message; rct::key c_x; this->controle_device->mlsag_hash(long_message_x, c_x); #endif cnt = long_message.size(); for (size_t i = 0; ibuffer_send[offset] = (i==(cnt-1))?0x00:0x80; //last offset += 1; //msg part memmove(this->buffer_send+offset, long_message[i].bytes, 32); offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); } memmove(c.bytes, &this->buffer_recv[0], 32); #ifdef DEBUG_HWDEVICE hw::ledger::check32(""mlsag_hash"", ""c"", (char*)c_x.bytes, (char*)c.bytes); #endif return true; } bool device_ledger::mlsag_sign(const rct::key &c, const rct::keyV &xx, const rct::keyV &alpha, const size_t rows, const size_t dsRows, rct::keyV &ss) { AUTO_LOCK_CMD(); CHECK_AND_ASSERT_THROW_MES(dsRows<=rows, ""dsRows greater than rows""); CHECK_AND_ASSERT_THROW_MES(xx.size() == rows, ""xx size does not match rows""); CHECK_AND_ASSERT_THROW_MES(alpha.size() == rows, ""alpha size does not match rows""); CHECK_AND_ASSERT_THROW_MES(ss.size() == rows, ""ss size does not match rows""); #ifdef DEBUG_HWDEVICE const rct::key c_x = c; const rct::keyV xx_x = hw::ledger::decrypt(xx); const rct::keyV alpha_x = hw::ledger::decrypt(alpha); const int rows_x = rows; const int dsRows_x = dsRows; rct::keyV ss_x(ss.size()); this->controle_device->mlsag_sign(c_x, xx_x, alpha_x, rows_x, dsRows_x, ss_x); #endif for (size_t j = 0; j < dsRows; j++) { int offset = set_command_header(INS_MLSAG, 0x03, j+1); //options this->buffer_send[offset] = 0x00; if (j==(dsRows-1)) { this->buffer_send[offset] |= 0x80; //last } offset += 1; //xx memmove(this->buffer_send+offset, xx[j].bytes, 32); offset += 32; //alpa memmove(this->buffer_send+offset, alpha[j].bytes, 32); offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); //ss memmove(ss[j].bytes, &this->buffer_recv[0], 32); } for (size_t j = dsRows; j < rows; j++) { sc_mulsub(ss[j].bytes, c.bytes, xx[j].bytes, alpha[j].bytes); } #ifdef DEBUG_HWDEVICE for (size_t j = 0; j < rows; j++) { hw::ledger::check32(""mlsag_sign"", ""ss[""+std::to_string(j)+""]"", (char*)ss_x[j].bytes, (char*)ss[j].bytes); } #endif return true; } bool device_ledger::close_tx() { AUTO_LOCK_CMD(); send_simple(INS_CLOSE_TX); return true; } /* ---------------------------------------------------------- */ static device_ledger *legder_device = NULL; void register_all(std::map> ®istry) { if (!legder_device) { legder_device = new device_ledger(); legder_device->set_name(""Ledger""); } registry.insert(std::make_pair(""Ledger"", std::unique_ptr(legder_device))); } #else //WITH_DEVICE_LEDGER void register_all(std::map> ®istry) { } #endif //WITH_DEVICE_LEDGER } } ",16171,True,3262.400096817926,median "// rijndael.cpp - modified by Chris Morgan // and Wei Dai from Paulo Baretto's Rijndael implementation // The original code and all modifications are in the public domain. // use ""cl /EP /P /DCRYPTOPP_GENERATE_X64_MASM rijndael.cpp"" to generate MASM code /* July 2018: Added support for ARMv7 AES instructions via Cryptogams ASM. See the head notes in aes_armv4.S for copyright and license. */ /* September 2017: Added support for Power8 AES instructions via compiler intrinsics. */ /* July 2017: Added support for ARMv8 AES instructions via compiler intrinsics. */ /* July 2010: Added support for AES-NI instructions via compiler intrinsics. */ /* Feb 2009: The x86/x64 assembly code was rewritten in by Wei Dai to do counter mode caching, which was invented by Hongjun Wu and popularized by Daniel J. Bernstein and Peter Schwabe in their paper ""New AES software speed records"". The round function was also modified to include a trick similar to one in Brian Gladman's x86 assembly code, doing an 8-bit register move to minimize the number of register spills. Also switched to compressed tables and copying round keys to the stack. The C++ implementation uses compressed tables if CRYPTOPP_ALLOW_RIJNDAEL_UNALIGNED_DATA_ACCESS is defined. It is defined on x86 platforms by default but no others. */ /* July 2006: Defense against timing attacks was added in by Wei Dai. The code now uses smaller tables in the first and last rounds, and preloads them into L1 cache before usage (by loading at least one element in each cache line). We try to delay subsequent accesses to each table (used in the first and last rounds) until all of the table has been preloaded. Hopefully the compiler isn't smart enough to optimize that code away. After preloading the table, we also try not to access any memory location other than the table and the stack, in order to prevent table entries from being unloaded from L1 cache, until that round is finished. (Some popular CPUs have 2-way associative caches.) */ // This is the original introductory comment: /** * version 3.0 (December 2000) * * Optimised ANSI C code for the Rijndael cipher (now AES) * * author Vincent Rijmen * author Antoon Bosselaers * author Paulo Barreto * * This code is hereby placed in the public domain. * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include ""pch.h"" #include ""config.h"" #ifndef CRYPTOPP_IMPORTS #ifndef CRYPTOPP_GENERATE_X64_MASM #include ""rijndael.h"" #include ""misc.h"" #include ""cpu.h"" // VS2017 and global optimization bug. TODO, figure out when // we can re-enable full optimizations for VS2017. Also see // https://github.com/weidai11/cryptopp/issues/649 #if (_MSC_VER >= 1910) # ifndef CRYPTOPP_DEBUG # pragma optimize("""", off) # pragma optimize(""ts"", on) # endif #endif NAMESPACE_BEGIN(CryptoPP) // Hack for http://github.com/weidai11/cryptopp/issues/42 and http://github.com/weidai11/cryptopp/issues/132 #if (CRYPTOPP_SSE2_ASM_AVAILABLE || defined(CRYPTOPP_X64_MASM_AVAILABLE)) # define CRYPTOPP_ALLOW_RIJNDAEL_UNALIGNED_DATA_ACCESS 1 #endif // Clang intrinsic casts #define M128I_CAST(x) ((__m128i *)(void *)(x)) #define CONST_M128I_CAST(x) ((const __m128i *)(const void *)(x)) #if defined(CRYPTOPP_ALLOW_RIJNDAEL_UNALIGNED_DATA_ACCESS) # if (CRYPTOPP_SSE2_ASM_AVAILABLE || defined(CRYPTOPP_X64_MASM_AVAILABLE)) && !defined(CRYPTOPP_DISABLE_RIJNDAEL_ASM) namespace rdtable {CRYPTOPP_ALIGN_DATA(16) word64 Te[256+2];} using namespace rdtable; # else static word64 Te[256]; # endif static word64 Td[256]; #else // Not CRYPTOPP_ALLOW_RIJNDAEL_UNALIGNED_DATA_ACCESS # if defined(CRYPTOPP_X64_MASM_AVAILABLE) // Unused; avoids linker error on Microsoft X64 non-AESNI platforms namespace rdtable {CRYPTOPP_ALIGN_DATA(16) word64 Te[256+2];} # endif CRYPTOPP_ALIGN_DATA(16) static word32 Te[256*4]; CRYPTOPP_ALIGN_DATA(16) static word32 Td[256*4]; #endif // CRYPTOPP_ALLOW_RIJNDAEL_UNALIGNED_DATA_ACCESS static volatile bool s_TeFilled = false, s_TdFilled = false; ANONYMOUS_NAMESPACE_BEGIN #if CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X86 // Determine whether the range between begin and end overlaps // with the same 4k block offsets as the Te table. Logically, // the code is trying to create the condition: // // Two sepearate memory pages: // // +-----+ +-----+ // |XXXXX| |YYYYY| // |XXXXX| |YYYYY| // | | | | // | | | | // +-----+ +-----+ // Te Table Locals // // Have a logical cache view of (X and Y may be inverted): // // +-----+ // |XXXXX| // |XXXXX| // |YYYYY| // |YYYYY| // +-----+ // static inline bool AliasedWithTable(const byte *begin, const byte *end) { ptrdiff_t s0 = uintptr_t(begin)%4096, s1 = uintptr_t(end)%4096; ptrdiff_t t0 = uintptr_t(Te)%4096, t1 = (uintptr_t(Te)+sizeof(Te))%4096; if (t1 > t0) return (s0 >= t0 && s0 < t1) || (s1 > t0 && s1 <= t1); else return (s0 < t1 || s1 <= t1) || (s0 >= t0 || s1 > t0); } struct Locals { word32 subkeys[4*12], workspace[8]; const byte *inBlocks, *inXorBlocks, *outXorBlocks; byte *outBlocks; size_t inIncrement, inXorIncrement, outXorIncrement, outIncrement; size_t regSpill, lengthAndCounterFlag, keysBegin; }; const size_t s_aliasPageSize = 4096; const size_t s_aliasBlockSize = 256; const size_t s_sizeToAllocate = s_aliasPageSize + s_aliasBlockSize + sizeof(Locals); #endif // CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X86 ANONYMOUS_NAMESPACE_END // ************************* Portable Code ************************************ #define QUARTER_ROUND(L, T, t, a, b, c, d) \\ a ^= L(T, 3, byte(t)); t >>= 8;\\ b ^= L(T, 2, byte(t)); t >>= 8;\\ c ^= L(T, 1, byte(t)); t >>= 8;\\ d ^= L(T, 0, t); #define QUARTER_ROUND_LE(t, a, b, c, d) \\ tempBlock[a] = ((byte *)(Te+byte(t)))[1]; t >>= 8;\\ tempBlock[b] = ((byte *)(Te+byte(t)))[1]; t >>= 8;\\ tempBlock[c] = ((byte *)(Te+byte(t)))[1]; t >>= 8;\\ tempBlock[d] = ((byte *)(Te+t))[1]; #if defined(CRYPTOPP_ALLOW_RIJNDAEL_UNALIGNED_DATA_ACCESS) #define QUARTER_ROUND_LD(t, a, b, c, d) \\ tempBlock[a] = ((byte *)(Td+byte(t)))[GetNativeByteOrder()*7]; t >>= 8;\\ tempBlock[b] = ((byte *)(Td+byte(t)))[GetNativeByteOrder()*7]; t >>= 8;\\ tempBlock[c] = ((byte *)(Td+byte(t)))[GetNativeByteOrder()*7]; t >>= 8;\\ tempBlock[d] = ((byte *)(Td+t))[GetNativeByteOrder()*7]; #else #define QUARTER_ROUND_LD(t, a, b, c, d) \\ tempBlock[a] = Sd[byte(t)]; t >>= 8;\\ tempBlock[b] = Sd[byte(t)]; t >>= 8;\\ tempBlock[c] = Sd[byte(t)]; t >>= 8;\\ tempBlock[d] = Sd[t]; #endif #define QUARTER_ROUND_E(t, a, b, c, d) QUARTER_ROUND(TL_M, Te, t, a, b, c, d) #define QUARTER_ROUND_D(t, a, b, c, d) QUARTER_ROUND(TL_M, Td, t, a, b, c, d) #if (CRYPTOPP_LITTLE_ENDIAN) #define QUARTER_ROUND_FE(t, a, b, c, d) QUARTER_ROUND(TL_F, Te, t, d, c, b, a) #define QUARTER_ROUND_FD(t, a, b, c, d) QUARTER_ROUND(TL_F, Td, t, d, c, b, a) #if defined(CRYPTOPP_ALLOW_RIJNDAEL_UNALIGNED_DATA_ACCESS) #define TL_F(T, i, x) (*(word32 *)(void *)((byte *)T + x*8 + (6-i)%4+1)) #define TL_M(T, i, x) (*(word32 *)(void *)((byte *)T + x*8 + (i+3)%4+1)) #else #define TL_F(T, i, x) rotrFixed(T[x], (3-i)*8) #define TL_M(T, i, x) T[i*256 + x] #endif #else #define QUARTER_ROUND_FE(t, a, b, c, d) QUARTER_ROUND(TL_F, Te, t, a, b, c, d) #define QUARTER_ROUND_FD(t, a, b, c, d) QUARTER_ROUND(TL_F, Td, t, a, b, c, d) #if defined(CRYPTOPP_ALLOW_RIJNDAEL_UNALIGNED_DATA_ACCESS) #define TL_F(T, i, x) (*(word32 *)(void *)((byte *)T + x*8 + (4-i)%4)) #define TL_M TL_F #else #define TL_F(T, i, x) rotrFixed(T[x], i*8) #define TL_M(T, i, x) T[i*256 + x] #endif #endif #define f2(x) ((x<<1)^(((x>>7)&1)*0x11b)) #define f4(x) ((x<<2)^(((x>>6)&1)*0x11b)^(((x>>6)&2)*0x11b)) #define f8(x) ((x<<3)^(((x>>5)&1)*0x11b)^(((x>>5)&2)*0x11b)^(((x>>5)&4)*0x11b)) #define f3(x) (f2(x) ^ x) #define f9(x) (f8(x) ^ x) #define fb(x) (f8(x) ^ f2(x) ^ x) #define fd(x) (f8(x) ^ f4(x) ^ x) #define fe(x) (f8(x) ^ f4(x) ^ f2(x)) unsigned int Rijndael::Base::OptimalDataAlignment() const { #if (CRYPTOPP_AESNI_AVAILABLE) if (HasAESNI()) return 16; // load __m128i #endif #if (CRYPTOPP_ARM_AES_AVAILABLE) if (HasAES()) return 4; // load uint32x4_t #endif #if (CRYPTOGAMS_ARM_AES) // Must use 1 here for Cryptogams AES. Also see // https://github.com/weidai11/cryptopp/issues/683 if (HasARMv7()) return 1; #endif #if (CRYPTOPP_POWER8_AES_AVAILABLE) if (HasAES()) return 16; // load uint32x4_p #endif return BlockTransformation::OptimalDataAlignment(); } void Rijndael::Base::FillEncTable() { for (int i=0; i<256; i++) { byte x = Se[i]; #if defined(CRYPTOPP_ALLOW_RIJNDAEL_UNALIGNED_DATA_ACCESS) word32 y = word32(x)<<8 | word32(x)<<16 | word32(f2(x))<<24; Te[i] = word64(y | f3(x))<<32 | y; #else word32 y = f3(x) | word32(x)<<8 | word32(x)<<16 | word32(f2(x))<<24; for (int j=0; j<4; j++) { Te[i+j*256] = y; y = rotrConstant<8>(y); } #endif } #if (CRYPTOPP_SSE2_ASM_AVAILABLE || defined(CRYPTOPP_X64_MASM_AVAILABLE)) && !defined(CRYPTOPP_DISABLE_RIJNDAEL_ASM) Te[256] = Te[257] = 0; #endif s_TeFilled = true; } void Rijndael::Base::FillDecTable() { for (int i=0; i<256; i++) { byte x = Sd[i]; #if defined(CRYPTOPP_ALLOW_RIJNDAEL_UNALIGNED_DATA_ACCESS) word32 y = word32(fd(x))<<8 | word32(f9(x))<<16 | word32(fe(x))<<24; Td[i] = word64(y | fb(x))<<32 | y | x; #else word32 y = fb(x) | word32(fd(x))<<8 | word32(f9(x))<<16 | word32(fe(x))<<24; for (int j=0; j<4; j++) { Td[i+j*256] = y; y = rotrConstant<8>(y); } #endif } s_TdFilled = true; } #if (CRYPTOPP_AESNI_AVAILABLE) extern void Rijndael_UncheckedSetKey_SSE4_AESNI(const byte *userKey, size_t keyLen, word32* rk); extern void Rijndael_UncheckedSetKeyRev_AESNI(word32 *key, unsigned int rounds); extern size_t Rijndael_Enc_AdvancedProcessBlocks_AESNI(const word32 *subkeys, size_t rounds, const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags); extern size_t Rijndael_Dec_AdvancedProcessBlocks_AESNI(const word32 *subkeys, size_t rounds, const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags); #endif #if (CRYPTOPP_ARM_AES_AVAILABLE) extern size_t Rijndael_Enc_AdvancedProcessBlocks_ARMV8(const word32 *subkeys, size_t rounds, const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags); extern size_t Rijndael_Dec_AdvancedProcessBlocks_ARMV8(const word32 *subkeys, size_t rounds, const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags); #endif #if (CRYPTOGAMS_ARM_AES) extern ""C"" int cryptogams_AES_set_encrypt_key(const unsigned char *userKey, const int bitLen, word32 *rkey); extern ""C"" int cryptogams_AES_set_decrypt_key(const unsigned char *userKey, const int bitLen, word32 *rkey); extern ""C"" void cryptogams_AES_encrypt_block(const unsigned char *in, unsigned char *out, const word32 *rkey); extern ""C"" void cryptogams_AES_decrypt_block(const unsigned char *in, unsigned char *out, const word32 *rkey); #endif #if (CRYPTOPP_POWER8_AES_AVAILABLE) extern void Rijndael_UncheckedSetKey_POWER8(const byte* userKey, size_t keyLen, word32* rk, const byte* Se); extern size_t Rijndael_Enc_AdvancedProcessBlocks128_6x1_ALTIVEC(const word32 *subkeys, size_t rounds, const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags); extern size_t Rijndael_Dec_AdvancedProcessBlocks128_6x1_ALTIVEC(const word32 *subkeys, size_t rounds, const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags); #endif #if (CRYPTOGAMS_ARM_AES) int CRYPTOGAMS_set_encrypt_key(const byte *userKey, const int bitLen, word32 *rkey) { return cryptogams_AES_set_encrypt_key(userKey, bitLen, rkey); } int CRYPTOGAMS_set_decrypt_key(const byte *userKey, const int bitLen, word32 *rkey) { return cryptogams_AES_set_decrypt_key(userKey, bitLen, rkey); } void CRYPTOGAMS_encrypt(const byte *inBlock, const byte *xorBlock, byte *outBlock, const word32 *rkey) { cryptogams_AES_encrypt_block(inBlock, outBlock, rkey); if (xorBlock) xorbuf (outBlock, xorBlock, 16); } void CRYPTOGAMS_decrypt(const byte *inBlock, const byte *xorBlock, byte *outBlock, const word32 *rkey) { cryptogams_AES_decrypt_block(inBlock, outBlock, rkey); if (xorBlock) xorbuf (outBlock, xorBlock, 16); } #endif std::string Rijndael::Base::AlgorithmProvider() const { #if (CRYPTOPP_AESNI_AVAILABLE) if (HasAESNI()) return ""AESNI""; #endif #if CRYPTOPP_SSE2_ASM_AVAILABLE && !defined(CRYPTOPP_DISABLE_RIJNDAEL_ASM) if (HasSSE2()) return ""SSE2""; #endif #if (CRYPTOPP_ARM_AES_AVAILABLE) if (HasAES()) return ""ARMv8""; #endif #if (CRYPTOGAMS_ARM_AES) if (HasARMv7()) return ""ARMv7""; #endif #if (CRYPTOPP_POWER8_AES_AVAILABLE) if (HasAES()) return ""Power8""; #endif return ""C++""; } void Rijndael::Base::UncheckedSetKey(const byte *userKey, unsigned int keyLen, const NameValuePairs &) { AssertValidKeyLength(keyLen); #if (CRYPTOGAMS_ARM_AES) if (HasARMv7()) { m_rounds = keyLen/4 + 6; m_key.New(4*(14+1)+4); if (IsForwardTransformation()) CRYPTOGAMS_set_encrypt_key(userKey, keyLen*8, m_key.begin()); else CRYPTOGAMS_set_decrypt_key(userKey, keyLen*8, m_key.begin()); return; } #endif #if CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X86 m_aliasBlock.New(s_sizeToAllocate); // The alias block is only used on IA-32 when unaligned data access is in effect. // Setting the low water mark to 0 avoids zeroization when m_aliasBlock is unused. m_aliasBlock.SetMark(0); #endif m_rounds = keyLen/4 + 6; m_key.New(4*(m_rounds+1)); word32 *rk = m_key; #if (CRYPTOPP_AESNI_AVAILABLE && CRYPTOPP_SSE41_AVAILABLE && (!defined(_MSC_VER) || _MSC_VER >= 1600 || CRYPTOPP_BOOL_X86 || CRYPTOPP_BOOL_X32)) // MSVC 2008 SP1 generates bad code for _mm_extract_epi32() when compiling for X64 if (HasAESNI() && HasSSE41()) { // TODO: Add non-SSE4.1 variant for low-end Atoms. The low-end // Atoms have SSE2-SSSE3 and AES-NI, but not SSE4.1 or SSE4.2. Rijndael_UncheckedSetKey_SSE4_AESNI(userKey, keyLen, rk); if (!IsForwardTransformation()) Rijndael_UncheckedSetKeyRev_AESNI(m_key, m_rounds); return; } #endif #if CRYPTOPP_POWER8_AES_AVAILABLE if (HasAES()) { // We still need rcon and Se to fallback to C/C++ for AES-192 and AES-256. // The IBM docs on AES sucks. Intel's docs on AESNI puts IBM to shame. Rijndael_UncheckedSetKey_POWER8(userKey, keyLen, rk, Se); return; } #endif GetUserKey(BIG_ENDIAN_ORDER, rk, keyLen/4, userKey, keyLen); const word32 *rc = rcon; word32 temp; while (true) { temp = rk[keyLen/4-1]; word32 x = (word32(Se[GETBYTE(temp, 2)]) << 24) ^ (word32(Se[GETBYTE(temp, 1)]) << 16) ^ (word32(Se[GETBYTE(temp, 0)]) << 8) ^ Se[GETBYTE(temp, 3)]; rk[keyLen/4] = rk[0] ^ x ^ *(rc++); rk[keyLen/4+1] = rk[1] ^ rk[keyLen/4]; rk[keyLen/4+2] = rk[2] ^ rk[keyLen/4+1]; rk[keyLen/4+3] = rk[3] ^ rk[keyLen/4+2]; if (rk + keyLen/4 + 4 == m_key.end()) break; if (keyLen == 24) { rk[10] = rk[ 4] ^ rk[ 9]; rk[11] = rk[ 5] ^ rk[10]; } else if (keyLen == 32) { temp = rk[11]; rk[12] = rk[ 4] ^ (word32(Se[GETBYTE(temp, 3)]) << 24) ^ (word32(Se[GETBYTE(temp, 2)]) << 16) ^ (word32(Se[GETBYTE(temp, 1)]) << 8) ^ Se[GETBYTE(temp, 0)]; rk[13] = rk[ 5] ^ rk[12]; rk[14] = rk[ 6] ^ rk[13]; rk[15] = rk[ 7] ^ rk[14]; } rk += keyLen/4; } rk = m_key; if (IsForwardTransformation()) { if (!s_TeFilled) FillEncTable(); ConditionalByteReverse(BIG_ENDIAN_ORDER, rk, rk, 16); ConditionalByteReverse(BIG_ENDIAN_ORDER, rk + m_rounds*4, rk + m_rounds*4, 16); } else { if (!s_TdFilled) FillDecTable(); #define InverseMixColumn(x) \\ TL_M(Td, 0, Se[GETBYTE(x, 3)]) ^ TL_M(Td, 1, Se[GETBYTE(x, 2)]) ^ \\ TL_M(Td, 2, Se[GETBYTE(x, 1)]) ^ TL_M(Td, 3, Se[GETBYTE(x, 0)]) unsigned int i, j; for (i = 4, j = 4*m_rounds-4; i < j; i += 4, j -= 4) { temp = InverseMixColumn(rk[i ]); rk[i ] = InverseMixColumn(rk[j ]); rk[j ] = temp; temp = InverseMixColumn(rk[i + 1]); rk[i + 1] = InverseMixColumn(rk[j + 1]); rk[j + 1] = temp; temp = InverseMixColumn(rk[i + 2]); rk[i + 2] = InverseMixColumn(rk[j + 2]); rk[j + 2] = temp; temp = InverseMixColumn(rk[i + 3]); rk[i + 3] = InverseMixColumn(rk[j + 3]); rk[j + 3] = temp; } rk[i+0] = InverseMixColumn(rk[i+0]); rk[i+1] = InverseMixColumn(rk[i+1]); rk[i+2] = InverseMixColumn(rk[i+2]); rk[i+3] = InverseMixColumn(rk[i+3]); temp = ConditionalByteReverse(BIG_ENDIAN_ORDER, rk[0]); rk[0] = ConditionalByteReverse(BIG_ENDIAN_ORDER, rk[4*m_rounds+0]); rk[4*m_rounds+0] = temp; temp = ConditionalByteReverse(BIG_ENDIAN_ORDER, rk[1]); rk[1] = ConditionalByteReverse(BIG_ENDIAN_ORDER, rk[4*m_rounds+1]); rk[4*m_rounds+1] = temp; temp = ConditionalByteReverse(BIG_ENDIAN_ORDER, rk[2]); rk[2] = ConditionalByteReverse(BIG_ENDIAN_ORDER, rk[4*m_rounds+2]); rk[4*m_rounds+2] = temp; temp = ConditionalByteReverse(BIG_ENDIAN_ORDER, rk[3]); rk[3] = ConditionalByteReverse(BIG_ENDIAN_ORDER, rk[4*m_rounds+3]); rk[4*m_rounds+3] = temp; } #if CRYPTOPP_AESNI_AVAILABLE if (HasAESNI()) ConditionalByteReverse(BIG_ENDIAN_ORDER, rk+4, rk+4, (m_rounds-1)*16); #endif #if CRYPTOPP_ARM_AES_AVAILABLE if (HasAES()) ConditionalByteReverse(BIG_ENDIAN_ORDER, rk+4, rk+4, (m_rounds-1)*16); #endif } void Rijndael::Enc::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const { #if CRYPTOPP_SSE2_ASM_AVAILABLE || defined(CRYPTOPP_X64_MASM_AVAILABLE) || CRYPTOPP_AESNI_AVAILABLE # if (CRYPTOPP_SSE2_ASM_AVAILABLE || defined(CRYPTOPP_X64_MASM_AVAILABLE)) && !defined(CRYPTOPP_DISABLE_RIJNDAEL_ASM) if (HasSSE2()) # else if (HasAESNI()) # endif { (void)Rijndael::Enc::AdvancedProcessBlocks(inBlock, xorBlock, outBlock, 16, 0); return; } #endif #if (CRYPTOPP_ARM_AES_AVAILABLE) if (HasAES()) { (void)Rijndael::Enc::AdvancedProcessBlocks(inBlock, xorBlock, outBlock, 16, 0); return; } #endif #if (CRYPTOGAMS_ARM_AES) if (HasARMv7()) { CRYPTOGAMS_encrypt(inBlock, xorBlock, outBlock, m_key.begin()); return; } #endif #if (CRYPTOPP_POWER8_AES_AVAILABLE) if (HasAES()) { (void)Rijndael::Enc::AdvancedProcessBlocks(inBlock, xorBlock, outBlock, 16, 0); return; } #endif typedef BlockGetAndPut Block; word32 s0, s1, s2, s3, t0, t1, t2, t3; Block::Get(inBlock)(s0)(s1)(s2)(s3); const word32 *rk = m_key; s0 ^= rk[0]; s1 ^= rk[1]; s2 ^= rk[2]; s3 ^= rk[3]; t0 = rk[4]; t1 = rk[5]; t2 = rk[6]; t3 = rk[7]; rk += 8; // timing attack countermeasure. see comments at top for more details. // also see http://github.com/weidai11/cryptopp/issues/146 const int cacheLineSize = GetCacheLineSize(); unsigned int i; volatile word32 _u = 0; word32 u = _u; #if defined(CRYPTOPP_ALLOW_RIJNDAEL_UNALIGNED_DATA_ACCESS) for (i=0; i<2048; i+=cacheLineSize) #else for (i=0; i<1024; i+=cacheLineSize) #endif u &= *(const word32 *)(const void *)(((const byte *)Te)+i); u &= Te[255]; s0 |= u; s1 |= u; s2 |= u; s3 |= u; QUARTER_ROUND_FE(s3, t0, t1, t2, t3) QUARTER_ROUND_FE(s2, t3, t0, t1, t2) QUARTER_ROUND_FE(s1, t2, t3, t0, t1) QUARTER_ROUND_FE(s0, t1, t2, t3, t0) // Nr - 2 full rounds: unsigned int r = m_rounds/2 - 1; do { s0 = rk[0]; s1 = rk[1]; s2 = rk[2]; s3 = rk[3]; QUARTER_ROUND_E(t3, s0, s1, s2, s3) QUARTER_ROUND_E(t2, s3, s0, s1, s2) QUARTER_ROUND_E(t1, s2, s3, s0, s1) QUARTER_ROUND_E(t0, s1, s2, s3, s0) t0 = rk[4]; t1 = rk[5]; t2 = rk[6]; t3 = rk[7]; QUARTER_ROUND_E(s3, t0, t1, t2, t3) QUARTER_ROUND_E(s2, t3, t0, t1, t2) QUARTER_ROUND_E(s1, t2, t3, t0, t1) QUARTER_ROUND_E(s0, t1, t2, t3, t0) rk += 8; } while (--r); word32 tbw[4]; byte *const tempBlock = (byte *)tbw; QUARTER_ROUND_LE(t2, 15, 2, 5, 8) QUARTER_ROUND_LE(t1, 11, 14, 1, 4) QUARTER_ROUND_LE(t0, 7, 10, 13, 0) QUARTER_ROUND_LE(t3, 3, 6, 9, 12) Block::Put(xorBlock, outBlock)(tbw[0]^rk[0])(tbw[1]^rk[1])(tbw[2]^rk[2])(tbw[3]^rk[3]); } void Rijndael::Dec::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const { #if CRYPTOPP_AESNI_AVAILABLE if (HasAESNI()) { (void)Rijndael::Dec::AdvancedProcessBlocks(inBlock, xorBlock, outBlock, 16, 0); return; } #endif #if (CRYPTOPP_ARM_AES_AVAILABLE) if (HasAES()) { (void)Rijndael::Dec::AdvancedProcessBlocks(inBlock, xorBlock, outBlock, 16, 0); return; } #endif #if (CRYPTOGAMS_ARM_AES) if (HasARMv7()) { CRYPTOGAMS_decrypt(inBlock, xorBlock, outBlock, m_key.begin()); return; } #endif #if (CRYPTOPP_POWER8_AES_AVAILABLE) if (HasAES()) { (void)Rijndael::Dec::AdvancedProcessBlocks(inBlock, xorBlock, outBlock, 16, 0); return; } #endif typedef BlockGetAndPut Block; word32 s0, s1, s2, s3, t0, t1, t2, t3; Block::Get(inBlock)(s0)(s1)(s2)(s3); const word32 *rk = m_key; s0 ^= rk[0]; s1 ^= rk[1]; s2 ^= rk[2]; s3 ^= rk[3]; t0 = rk[4]; t1 = rk[5]; t2 = rk[6]; t3 = rk[7]; rk += 8; // timing attack countermeasure. see comments at top for more details. // also see http://github.com/weidai11/cryptopp/issues/146 const int cacheLineSize = GetCacheLineSize(); unsigned int i; volatile word32 _u = 0; word32 u = _u; #if defined(CRYPTOPP_ALLOW_RIJNDAEL_UNALIGNED_DATA_ACCESS) for (i=0; i<2048; i+=cacheLineSize) #else for (i=0; i<1024; i+=cacheLineSize) #endif u &= *(const word32 *)(const void *)(((const byte *)Td)+i); u &= Td[255]; s0 |= u; s1 |= u; s2 |= u; s3 |= u; QUARTER_ROUND_FD(s3, t2, t1, t0, t3) QUARTER_ROUND_FD(s2, t1, t0, t3, t2) QUARTER_ROUND_FD(s1, t0, t3, t2, t1) QUARTER_ROUND_FD(s0, t3, t2, t1, t0) // Nr - 2 full rounds: unsigned int r = m_rounds/2 - 1; do { s0 = rk[0]; s1 = rk[1]; s2 = rk[2]; s3 = rk[3]; QUARTER_ROUND_D(t3, s2, s1, s0, s3) QUARTER_ROUND_D(t2, s1, s0, s3, s2) QUARTER_ROUND_D(t1, s0, s3, s2, s1) QUARTER_ROUND_D(t0, s3, s2, s1, s0) t0 = rk[4]; t1 = rk[5]; t2 = rk[6]; t3 = rk[7]; QUARTER_ROUND_D(s3, t2, t1, t0, t3) QUARTER_ROUND_D(s2, t1, t0, t3, t2) QUARTER_ROUND_D(s1, t0, t3, t2, t1) QUARTER_ROUND_D(s0, t3, t2, t1, t0) rk += 8; } while (--r); #if !(defined(CRYPTOPP_ALLOW_RIJNDAEL_UNALIGNED_DATA_ACCESS)) // timing attack countermeasure. see comments at top for more details // If CRYPTOPP_ALLOW_RIJNDAEL_UNALIGNED_DATA_ACCESS is defined, // QUARTER_ROUND_LD will use Td, which is already preloaded. u = _u; for (i=0; i<256; i+=cacheLineSize) u &= *(const word32 *)(const void *)(Sd+i); u &= *(const word32 *)(const void *)(Sd+252); t0 |= u; t1 |= u; t2 |= u; t3 |= u; #endif word32 tbw[4]; byte *const tempBlock = (byte *)tbw; QUARTER_ROUND_LD(t2, 7, 2, 13, 8) QUARTER_ROUND_LD(t1, 3, 14, 9, 4) QUARTER_ROUND_LD(t0, 15, 10, 5, 0) QUARTER_ROUND_LD(t3, 11, 6, 1, 12) Block::Put(xorBlock, outBlock)(tbw[0]^rk[0])(tbw[1]^rk[1])(tbw[2]^rk[2])(tbw[3]^rk[3]); } // ************************* Assembly Code ************************************ #if CRYPTOPP_MSC_VERSION # pragma warning(disable: 4731) // frame pointer register 'ebp' modified by inline assembly code #endif #endif // #ifndef CRYPTOPP_GENERATE_X64_MASM #if CRYPTOPP_SSE2_ASM_AVAILABLE && !defined(CRYPTOPP_DISABLE_RIJNDAEL_ASM) CRYPTOPP_NAKED void CRYPTOPP_FASTCALL Rijndael_Enc_AdvancedProcessBlocks_SSE2(void *locals, const word32 *k) { CRYPTOPP_UNUSED(locals); CRYPTOPP_UNUSED(k); #if CRYPTOPP_BOOL_X86 #define L_REG esp #define L_INDEX(i) (L_REG+768+i) #define L_INXORBLOCKS L_INBLOCKS+4 #define L_OUTXORBLOCKS L_INBLOCKS+8 #define L_OUTBLOCKS L_INBLOCKS+12 #define L_INCREMENTS L_INDEX(16*15) #define L_SP L_INDEX(16*16) #define L_LENGTH L_INDEX(16*16+4) #define L_KEYS_BEGIN L_INDEX(16*16+8) #define MOVD movd #define MM(i) mm##i #define MXOR(a,b,c) \\ AS2( movzx esi, b)\\ AS2( movd mm7, DWORD PTR [AS_REG_7+8*WORD_REG(si)+MAP0TO4(c)])\\ AS2( pxor MM(a), mm7)\\ #define MMOV(a,b,c) \\ AS2( movzx esi, b)\\ AS2( movd MM(a), DWORD PTR [AS_REG_7+8*WORD_REG(si)+MAP0TO4(c)])\\ #else #define L_REG r8 #define L_INDEX(i) (L_REG+i) #define L_INXORBLOCKS L_INBLOCKS+8 #define L_OUTXORBLOCKS L_INBLOCKS+16 #define L_OUTBLOCKS L_INBLOCKS+24 #define L_INCREMENTS L_INDEX(16*16) #define L_LENGTH L_INDEX(16*18+8) #define L_KEYS_BEGIN L_INDEX(16*19) #define MOVD mov #define MM_0 r9d #define MM_1 r12d #ifdef __GNUC__ #define MM_2 r11d #else #define MM_2 r10d #endif #define MM(i) MM_##i #define MXOR(a,b,c) \\ AS2( movzx esi, b)\\ AS2( xor MM(a), DWORD PTR [AS_REG_7+8*WORD_REG(si)+MAP0TO4(c)])\\ #define MMOV(a,b,c) \\ AS2( movzx esi, b)\\ AS2( mov MM(a), DWORD PTR [AS_REG_7+8*WORD_REG(si)+MAP0TO4(c)])\\ #endif #define L_SUBKEYS L_INDEX(0) #define L_SAVED_X L_SUBKEYS #define L_KEY12 L_INDEX(16*12) #define L_LASTROUND L_INDEX(16*13) #define L_INBLOCKS L_INDEX(16*14) #define MAP0TO4(i) (ASM_MOD(i+3,4)+1) #define XOR(a,b,c) \\ AS2( movzx esi, b)\\ AS2( xor a, DWORD PTR [AS_REG_7+8*WORD_REG(si)+MAP0TO4(c)])\\ #define MOV(a,b,c) \\ AS2( movzx esi, b)\\ AS2( mov a, DWORD PTR [AS_REG_7+8*WORD_REG(si)+MAP0TO4(c)])\\ #ifdef CRYPTOPP_GENERATE_X64_MASM ALIGN 8 Rijndael_Enc_AdvancedProcessBlocks PROC FRAME rex_push_reg rsi push_reg rdi push_reg rbx push_reg r12 .endprolog mov L_REG, rcx mov AS_REG_7, ?Te@rdtable@CryptoPP@@3PA_KA mov edi, DWORD PTR [?g_cacheLineSize@CryptoPP@@3IA] #elif defined(__GNUC__) __asm__ __volatile__ ( INTEL_NOPREFIX #if CRYPTOPP_BOOL_X64 AS2( mov L_REG, rcx) #endif AS_PUSH_IF86(bx) AS_PUSH_IF86(bp) AS2( mov AS_REG_7, WORD_REG(si)) #else AS_PUSH_IF86(si) AS_PUSH_IF86(di) AS_PUSH_IF86(bx) AS_PUSH_IF86(bp) AS2( lea AS_REG_7, [Te]) AS2( mov edi, [g_cacheLineSize]) #endif #if CRYPTOPP_BOOL_X86 AS2( mov [ecx+16*12+16*4], esp) // save esp to L_SP AS2( lea esp, [ecx-768]) #endif // copy subkeys to stack AS2( mov WORD_REG(si), [L_KEYS_BEGIN]) AS2( mov WORD_REG(ax), 16) AS2( and WORD_REG(ax), WORD_REG(si)) AS2( movdqa xmm3, XMMWORD_PTR [WORD_REG(dx)+16+WORD_REG(ax)]) // subkey 1 (non-counter) or 2 (counter) AS2( movdqa [L_KEY12], xmm3) AS2( lea WORD_REG(ax), [WORD_REG(dx)+WORD_REG(ax)+2*16]) AS2( sub WORD_REG(ax), WORD_REG(si)) ASL(0) AS2( movdqa xmm0, [WORD_REG(ax)+WORD_REG(si)]) AS2( movdqa XMMWORD_PTR [L_SUBKEYS+WORD_REG(si)], xmm0) AS2( add WORD_REG(si), 16) AS2( cmp WORD_REG(si), 16*12) ATT_NOPREFIX ASJ( jl, 0, b) INTEL_NOPREFIX // read subkeys 0, 1 and last AS2( movdqa xmm4, [WORD_REG(ax)+WORD_REG(si)]) // last subkey AS2( movdqa xmm1, [WORD_REG(dx)]) // subkey 0 AS2( MOVD MM(1), [WORD_REG(dx)+4*4]) // 0,1,2,3 AS2( mov ebx, [WORD_REG(dx)+5*4]) // 4,5,6,7 AS2( mov ecx, [WORD_REG(dx)+6*4]) // 8,9,10,11 AS2( mov edx, [WORD_REG(dx)+7*4]) // 12,13,14,15 // load table into cache AS2( xor WORD_REG(ax), WORD_REG(ax)) ASL(9) AS2( mov esi, [AS_REG_7+WORD_REG(ax)]) AS2( add WORD_REG(ax), WORD_REG(di)) AS2( mov esi, [AS_REG_7+WORD_REG(ax)]) AS2( add WORD_REG(ax), WORD_REG(di)) AS2( mov esi, [AS_REG_7+WORD_REG(ax)]) AS2( add WORD_REG(ax), WORD_REG(di)) AS2( mov esi, [AS_REG_7+WORD_REG(ax)]) AS2( add WORD_REG(ax), WORD_REG(di)) AS2( cmp WORD_REG(ax), 2048) ATT_NOPREFIX ASJ( jl, 9, b) INTEL_NOPREFIX AS1( lfence) AS2( test DWORD PTR [L_LENGTH], 1) ATT_NOPREFIX ASJ( jz, 8, f) INTEL_NOPREFIX // counter mode one-time setup AS2( mov WORD_REG(si), [L_INBLOCKS]) AS2( movdqu xmm2, [WORD_REG(si)]) // counter AS2( pxor xmm2, xmm1) AS2( psrldq xmm1, 14) AS2( movd eax, xmm1) AS2( mov al, BYTE PTR [WORD_REG(si)+15]) AS2( MOVD MM(2), eax) #if CRYPTOPP_BOOL_X86 AS2( mov eax, 1) AS2( movd mm3, eax) #endif // partial first round, in: xmm2(15,14,13,12;11,10,9,8;7,6,5,4;3,2,1,0), out: mm1, ebx, ecx, edx AS2( movd eax, xmm2) AS2( psrldq xmm2, 4) AS2( movd edi, xmm2) AS2( psrldq xmm2, 4) MXOR( 1, al, 0) // 0 XOR( edx, ah, 1) // 1 AS2( shr eax, 16) XOR( ecx, al, 2) // 2 XOR( ebx, ah, 3) // 3 AS2( mov eax, edi) AS2( movd edi, xmm2) AS2( psrldq xmm2, 4) XOR( ebx, al, 0) // 4 MXOR( 1, ah, 1) // 5 AS2( shr eax, 16) XOR( edx, al, 2) // 6 XOR( ecx, ah, 3) // 7 AS2( mov eax, edi) AS2( movd edi, xmm2) XOR( ecx, al, 0) // 8 XOR( ebx, ah, 1) // 9 AS2( shr eax, 16) MXOR( 1, al, 2) // 10 XOR( edx, ah, 3) // 11 AS2( mov eax, edi) XOR( edx, al, 0) // 12 XOR( ecx, ah, 1) // 13 AS2( shr eax, 16) XOR( ebx, al, 2) // 14 AS2( psrldq xmm2, 3) // partial second round, in: ebx(4,5,6,7), ecx(8,9,10,11), edx(12,13,14,15), out: eax, ebx, edi, mm0 AS2( mov eax, [L_KEY12+0*4]) AS2( mov edi, [L_KEY12+2*4]) AS2( MOVD MM(0), [L_KEY12+3*4]) MXOR( 0, cl, 3) /* 11 */ XOR( edi, bl, 3) /* 7 */ MXOR( 0, bh, 2) /* 6 */ AS2( shr ebx, 16) /* 4,5 */ XOR( eax, bl, 1) /* 5 */ MOV( ebx, bh, 0) /* 4 */ AS2( xor ebx, [L_KEY12+1*4]) XOR( eax, ch, 2) /* 10 */ AS2( shr ecx, 16) /* 8,9 */ XOR( eax, dl, 3) /* 15 */ XOR( ebx, dh, 2) /* 14 */ AS2( shr edx, 16) /* 12,13 */ XOR( edi, ch, 0) /* 8 */ XOR( ebx, cl, 1) /* 9 */ XOR( edi, dl, 1) /* 13 */ MXOR( 0, dh, 0) /* 12 */ AS2( movd ecx, xmm2) AS2( MOVD edx, MM(1)) AS2( MOVD [L_SAVED_X+3*4], MM(0)) AS2( mov [L_SAVED_X+0*4], eax) AS2( mov [L_SAVED_X+1*4], ebx) AS2( mov [L_SAVED_X+2*4], edi) ATT_NOPREFIX ASJ( jmp, 5, f) INTEL_NOPREFIX ASL(3) // non-counter mode per-block setup AS2( MOVD MM(1), [L_KEY12+0*4]) // 0,1,2,3 AS2( mov ebx, [L_KEY12+1*4]) // 4,5,6,7 AS2( mov ecx, [L_KEY12+2*4]) // 8,9,10,11 AS2( mov edx, [L_KEY12+3*4]) // 12,13,14,15 ASL(8) AS2( mov WORD_REG(ax), [L_INBLOCKS]) AS2( movdqu xmm2, [WORD_REG(ax)]) AS2( mov WORD_REG(si), [L_INXORBLOCKS]) AS2( movdqu xmm5, [WORD_REG(si)]) AS2( pxor xmm2, xmm1) AS2( pxor xmm2, xmm5) // first round, in: xmm2(15,14,13,12;11,10,9,8;7,6,5,4;3,2,1,0), out: eax, ebx, ecx, edx AS2( movd eax, xmm2) AS2( psrldq xmm2, 4) AS2( movd edi, xmm2) AS2( psrldq xmm2, 4) MXOR( 1, al, 0) // 0 XOR( edx, ah, 1) // 1 AS2( shr eax, 16) XOR( ecx, al, 2) // 2 XOR( ebx, ah, 3) // 3 AS2( mov eax, edi) AS2( movd edi, xmm2) AS2( psrldq xmm2, 4) XOR( ebx, al, 0) // 4 MXOR( 1, ah, 1) // 5 AS2( shr eax, 16) XOR( edx, al, 2) // 6 XOR( ecx, ah, 3) // 7 AS2( mov eax, edi) AS2( movd edi, xmm2) XOR( ecx, al, 0) // 8 XOR( ebx, ah, 1) // 9 AS2( shr eax, 16) MXOR( 1, al, 2) // 10 XOR( edx, ah, 3) // 11 AS2( mov eax, edi) XOR( edx, al, 0) // 12 XOR( ecx, ah, 1) // 13 AS2( shr eax, 16) XOR( ebx, al, 2) // 14 MXOR( 1, ah, 3) // 15 AS2( MOVD eax, MM(1)) AS2( add L_REG, [L_KEYS_BEGIN]) AS2( add L_REG, 4*16) ATT_NOPREFIX ASJ( jmp, 2, f) INTEL_NOPREFIX ASL(1) // counter-mode per-block setup AS2( MOVD ecx, MM(2)) AS2( MOVD edx, MM(1)) AS2( mov eax, [L_SAVED_X+0*4]) AS2( mov ebx, [L_SAVED_X+1*4]) AS2( xor cl, ch) AS2( and WORD_REG(cx), 255) ASL(5) #if CRYPTOPP_BOOL_X86 AS2( paddb MM(2), mm3) #else AS2( add MM(2), 1) #endif // remaining part of second round, in: edx(previous round),esi(keyed counter byte) eax,ebx,[L_SAVED_X+2*4],[L_SAVED_X+3*4], out: eax,ebx,ecx,edx AS2( xor edx, DWORD PTR [AS_REG_7+WORD_REG(cx)*8+3]) XOR( ebx, dl, 3) MOV( ecx, dh, 2) AS2( shr edx, 16) AS2( xor ecx, [L_SAVED_X+2*4]) XOR( eax, dh, 0) MOV( edx, dl, 1) AS2( xor edx, [L_SAVED_X+3*4]) AS2( add L_REG, [L_KEYS_BEGIN]) AS2( add L_REG, 3*16) ATT_NOPREFIX ASJ( jmp, 4, f) INTEL_NOPREFIX // in: eax(0,1,2,3), ebx(4,5,6,7), ecx(8,9,10,11), edx(12,13,14,15) // out: eax, ebx, edi, mm0 #define ROUND() \\ MXOR( 0, cl, 3) /* 11 */\\ AS2( mov cl, al) /* 8,9,10,3 */\\ XOR( edi, ah, 2) /* 2 */\\ AS2( shr eax, 16) /* 0,1 */\\ XOR( edi, bl, 3) /* 7 */\\ MXOR( 0, bh, 2) /* 6 */\\ AS2( shr ebx, 16) /* 4,5 */\\ MXOR( 0, al, 1) /* 1 */\\ MOV( eax, ah, 0) /* 0 */\\ XOR( eax, bl, 1) /* 5 */\\ MOV( ebx, bh, 0) /* 4 */\\ XOR( eax, ch, 2) /* 10 */\\ XOR( ebx, cl, 3) /* 3 */\\ AS2( shr ecx, 16) /* 8,9 */\\ XOR( eax, dl, 3) /* 15 */\\ XOR( ebx, dh, 2) /* 14 */\\ AS2( shr edx, 16) /* 12,13 */\\ XOR( edi, ch, 0) /* 8 */\\ XOR( ebx, cl, 1) /* 9 */\\ XOR( edi, dl, 1) /* 13 */\\ MXOR( 0, dh, 0) /* 12 */\\ ASL(2) // 2-round loop AS2( MOVD MM(0), [L_SUBKEYS-4*16+3*4]) AS2( mov edi, [L_SUBKEYS-4*16+2*4]) ROUND() AS2( mov ecx, edi) AS2( xor eax, [L_SUBKEYS-4*16+0*4]) AS2( xor ebx, [L_SUBKEYS-4*16+1*4]) AS2( MOVD edx, MM(0)) ASL(4) AS2( MOVD MM(0), [L_SUBKEYS-4*16+7*4]) AS2( mov edi, [L_SUBKEYS-4*16+6*4]) ROUND() AS2( mov ecx, edi) AS2( xor eax, [L_SUBKEYS-4*16+4*4]) AS2( xor ebx, [L_SUBKEYS-4*16+5*4]) AS2( MOVD edx, MM(0)) AS2( add L_REG, 32) AS2( test L_REG, 255) ATT_NOPREFIX ASJ( jnz, 2, b) INTEL_NOPREFIX AS2( sub L_REG, 16*16) #define LAST(a, b, c) \\ AS2( movzx esi, a )\\ AS2( movzx edi, BYTE PTR [AS_REG_7+WORD_REG(si)*8+1] )\\ AS2( movzx esi, b )\\ AS2( xor edi, DWORD PTR [AS_REG_7+WORD_REG(si)*8+0] )\\ AS2( mov WORD PTR [L_LASTROUND+c], di )\\ // last round LAST(ch, dl, 2) LAST(dh, al, 6) AS2( shr edx, 16) LAST(ah, bl, 10) AS2( shr eax, 16) LAST(bh, cl, 14) AS2( shr ebx, 16) LAST(dh, al, 12) AS2( shr ecx, 16) LAST(ah, bl, 0) LAST(bh, cl, 4) LAST(ch, dl, 8) AS2( mov WORD_REG(ax), [L_OUTXORBLOCKS]) AS2( mov WORD_REG(bx), [L_OUTBLOCKS]) AS2( mov WORD_REG(cx), [L_LENGTH]) AS2( sub WORD_REG(cx), 16) AS2( movdqu xmm2, [WORD_REG(ax)]) AS2( pxor xmm2, xmm4) #if CRYPTOPP_BOOL_X86 AS2( movdqa xmm0, [L_INCREMENTS]) AS2( paddd xmm0, [L_INBLOCKS]) AS2( movdqa [L_INBLOCKS], xmm0) #else AS2( movdqa xmm0, [L_INCREMENTS+16]) AS2( paddq xmm0, [L_INBLOCKS+16]) AS2( movdqa [L_INBLOCKS+16], xmm0) #endif AS2( pxor xmm2, [L_LASTROUND]) AS2( movdqu [WORD_REG(bx)], xmm2) ATT_NOPREFIX ASJ( jle, 7, f) INTEL_NOPREFIX AS2( mov [L_LENGTH], WORD_REG(cx)) AS2( test WORD_REG(cx), 1) ATT_NOPREFIX ASJ( jnz, 1, b) INTEL_NOPREFIX #if CRYPTOPP_BOOL_X64 AS2( movdqa xmm0, [L_INCREMENTS]) AS2( paddq xmm0, [L_INBLOCKS]) AS2( movdqa [L_INBLOCKS], xmm0) #endif ATT_NOPREFIX ASJ( jmp, 3, b) INTEL_NOPREFIX ASL(7) // erase keys on stack AS2( xorps xmm0, xmm0) AS2( lea WORD_REG(ax), [L_SUBKEYS+7*16]) AS2( movaps [WORD_REG(ax)-7*16], xmm0) AS2( movaps [WORD_REG(ax)-6*16], xmm0) AS2( movaps [WORD_REG(ax)-5*16], xmm0) AS2( movaps [WORD_REG(ax)-4*16], xmm0) AS2( movaps [WORD_REG(ax)-3*16], xmm0) AS2( movaps [WORD_REG(ax)-2*16], xmm0) AS2( movaps [WORD_REG(ax)-1*16], xmm0) AS2( movaps [WORD_REG(ax)+0*16], xmm0) AS2( movaps [WORD_REG(ax)+1*16], xmm0) AS2( movaps [WORD_REG(ax)+2*16], xmm0) AS2( movaps [WORD_REG(ax)+3*16], xmm0) AS2( movaps [WORD_REG(ax)+4*16], xmm0) AS2( movaps [WORD_REG(ax)+5*16], xmm0) AS2( movaps [WORD_REG(ax)+6*16], xmm0) #if CRYPTOPP_BOOL_X86 AS2( mov esp, [L_SP]) AS1( emms) #endif AS_POP_IF86(bp) AS_POP_IF86(bx) #if defined(_MSC_VER) && CRYPTOPP_BOOL_X86 AS_POP_IF86(di) AS_POP_IF86(si) AS1(ret) #endif #ifdef CRYPTOPP_GENERATE_X64_MASM pop r12 pop rbx pop rdi pop rsi ret Rijndael_Enc_AdvancedProcessBlocks ENDP #endif #ifdef __GNUC__ ATT_PREFIX : : ""c"" (locals), ""d"" (k), ""S"" (Te), ""D"" (g_cacheLineSize) : ""memory"", ""cc"", ""%eax"" #if CRYPTOPP_BOOL_X64 , ""%rbx"", ""%r8"", ""%r9"", ""%r10"", ""%r11"", ""%r12"" #endif ); #endif } #endif #ifndef CRYPTOPP_GENERATE_X64_MASM #ifdef CRYPTOPP_X64_MASM_AVAILABLE extern ""C"" { void Rijndael_Enc_AdvancedProcessBlocks_SSE2(void *locals, const word32 *k); } #endif #if CRYPTOPP_RIJNDAEL_ADVANCED_PROCESS_BLOCKS size_t Rijndael::Enc::AdvancedProcessBlocks(const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags) const { #if CRYPTOPP_AESNI_AVAILABLE if (HasAESNI()) return Rijndael_Enc_AdvancedProcessBlocks_AESNI(m_key, m_rounds, inBlocks, xorBlocks, outBlocks, length, flags); #endif #if CRYPTOPP_ARM_AES_AVAILABLE if (HasAES()) return Rijndael_Enc_AdvancedProcessBlocks_ARMV8(m_key, m_rounds, inBlocks, xorBlocks, outBlocks, length, flags); #endif #if CRYPTOPP_POWER8_AES_AVAILABLE if (HasAES()) return Rijndael_Enc_AdvancedProcessBlocks128_6x1_ALTIVEC(m_key, m_rounds, inBlocks, xorBlocks, outBlocks, length, flags); #endif #if (CRYPTOPP_SSE2_ASM_AVAILABLE || defined(CRYPTOPP_X64_MASM_AVAILABLE)) && !defined(CRYPTOPP_DISABLE_RIJNDAEL_ASM) if (HasSSE2()) { if (length < BLOCKSIZE) return length; static const byte *zeros = (const byte*)(Te+256); m_aliasBlock.SetMark(m_aliasBlock.size()); byte *space = NULLPTR, *originalSpace = const_cast(m_aliasBlock.data()); // round up to nearest 256 byte boundary space = originalSpace + (s_aliasBlockSize - (uintptr_t)originalSpace % s_aliasBlockSize) % s_aliasBlockSize; while (AliasedWithTable(space, space + sizeof(Locals))) { space += 256; CRYPTOPP_ASSERT(space < (originalSpace + s_aliasPageSize)); } size_t increment = BLOCKSIZE; if (flags & BT_ReverseDirection) { CRYPTOPP_ASSERT(length % BLOCKSIZE == 0); inBlocks += length - BLOCKSIZE; xorBlocks += length - BLOCKSIZE; outBlocks += length - BLOCKSIZE; increment = 0-increment; } Locals &locals = *(Locals *)(void *)space; locals.inBlocks = inBlocks; locals.inXorBlocks = (flags & BT_XorInput) && xorBlocks ? xorBlocks : zeros; locals.outXorBlocks = (flags & BT_XorInput) || !xorBlocks ? zeros : xorBlocks; locals.outBlocks = outBlocks; locals.inIncrement = (flags & BT_DontIncrementInOutPointers) ? 0 : increment; locals.inXorIncrement = (flags & BT_XorInput) && xorBlocks ? increment : 0; locals.outXorIncrement = (flags & BT_XorInput) || !xorBlocks ? 0 : increment; locals.outIncrement = (flags & BT_DontIncrementInOutPointers) ? 0 : increment; locals.lengthAndCounterFlag = length - (length%16) - bool(flags & BT_InBlockIsCounter); int keysToCopy = m_rounds - (flags & BT_InBlockIsCounter ? 3 : 2); locals.keysBegin = (12-keysToCopy)*16; Rijndael_Enc_AdvancedProcessBlocks_SSE2(&locals, m_key); return length % BLOCKSIZE; } #endif return BlockTransformation::AdvancedProcessBlocks(inBlocks, xorBlocks, outBlocks, length, flags); } size_t Rijndael::Dec::AdvancedProcessBlocks(const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags) const { #if CRYPTOPP_AESNI_AVAILABLE if (HasAESNI()) return Rijndael_Dec_AdvancedProcessBlocks_AESNI(m_key, m_rounds, inBlocks, xorBlocks, outBlocks, length, flags); #endif #if CRYPTOPP_ARM_AES_AVAILABLE if (HasAES()) return Rijndael_Dec_AdvancedProcessBlocks_ARMV8(m_key, m_rounds, inBlocks, xorBlocks, outBlocks, length, flags); #endif #if CRYPTOPP_POWER8_AES_AVAILABLE if (HasAES()) return Rijndael_Dec_AdvancedProcessBlocks128_6x1_ALTIVEC(m_key, m_rounds, inBlocks, xorBlocks, outBlocks, length, flags); #endif return BlockTransformation::AdvancedProcessBlocks(inBlocks, xorBlocks, outBlocks, length, flags); } #endif // CRYPTOPP_RIJNDAEL_ADVANCED_PROCESS_BLOCKS NAMESPACE_END #endif #endif ",16231,True,2888.977113741853,median ".//============================================================================ .// This archetype file contains the functions for generating .// preexisting instances initialization code. .// .// Note: This archetype is not presently in the test cycle. .// It must be run with a schema that includes CSME_CIE, R2961 and R2962. .//============================================================================ .// .// .//============================================================================ .// Initialize the instance subsystem. .// Update the instance and link records with array index values .// and container counts. .// The mapping of the instances to a particular array index is .// arbitrary. .//============================================================================ .function PEIInstanceSubsystemInit .param inst_ref_set o_objs .// .for each o_obj in o_objs .select many i_inss related by o_obj->CSME_CIE[R2961]->I_INS[R2962] .// Check for preexisting instance population requirement. .// The class must have instances and also be colored. .assign i = cardinality i_inss .select one te_class related by o_obj->TE_CLASS[R2019] .if ( ( i > 0 ) and ( te_class.PEIsDefinedInData ) ) .assign te_class.PEIsDefinedInData = TRUE .else .assign te_class.PEIsDefinedInData = FALSE .end if .// .assign i = 0 .for each i_ins in i_inss .assign i_ins.Name = ""${i}"" .assign i = i + 1 .end for .end for .end function .// .// .//============================================================================ .// Count the preexisting instances of the given type. .// Return the number of preexisting instances for obj. .//============================================================================ .function PEINumberOfPreexistingInstances .param inst_ref o_obj .select many i_inss related by o_obj->CSME_CIE[R2961]->I_INS[R2962] .assign attr_result = cardinality i_inss .// .assign msg = ""PEINumberOfPreexistingInstances is ${attr_result} "" .// .assign msg = msg + ""for ${o_obj.Name} (${o_obj.Key_Lett})"" .// .print ""${msg}"" .end function .// .// .//============================================================================= .// Generate initializers for preexisting instances. .// We generate the initializers in array index order. C initializers .// will assume sequential ordering. .//============================================================================= .function PEIRenderInitializers .param inst_ref o_obj .assign attr_assset = """" .select any te_set from instances of TE_SET .select one te_class related by o_obj->TE_CLASS[R2019] .if ( te_class.PEIsDefinedInData ) .assign inst_count = 0 .select many i_inss related by o_obj->CSME_CIE[R2961]->I_INS[R2962] .assign i_inss_cardinality = cardinality i_inss .while ( inst_count < i_inss_cardinality ) .for each i_ins in i_inss .if ( i_ins.Name == ""$t{inst_count}"" ) .invoke initializercode = PEIRenderInitializerBody( i_ins, o_obj ) .assign attr_assset = attr_assset + initializercode.assset { ${initializercode.result} }\\ .if ( last i_inss ) .else , .end if .break for .end if .end for .assign inst_count = inst_count + 1 .end while .// inst_count .// If there is a need for relationship set containers, build them up. .if ( attr_assset != """" ) .invoke rel_set_name = PEIGetRelationshipSetContainerName( te_class ) .assign attr_assset = ""static ${te_set.element_type} ${rel_set_name.result}[] = {\\n"" + attr_assset .assign attr_assset = ""/* PEI relationship set containers. */\\n"" + attr_assset .assign attr_assset = attr_assset + ""\\n};\\n"" .end if .end if .end function .// .// .//============================================================================= .// Generate body of one preexisting instance initializer. .// First, the initial state initializer is output. .// The class instance attribute data variable values are generated .// in the same order in which they appear in the application analysis OIM. .// The relationship optimization initializers are then generated. .//============================================================================= .function PEIRenderInitializerBody .param inst_ref i_ins .param inst_ref o_obj .assign attr_result = """" .assign attr_assset = """" .// .// Generate state machine state (if needed). .// .invoke cs_init = PEIRenderInitializerBodyCurrentState( i_ins, o_obj ) .assign attr_result = attr_result + cs_init.result .if ( """" != attr_result ) .assign attr_result = attr_result + "", "" .end if .// .// Generate the attribute value initializers. .// .select any te_attr related by o_obj->TE_CLASS[R2019]->TE_ATTR[R2061] where ( selected.prevID == 0 ) .if ( not_empty te_attr ) .select one o_attr related by te_attr->O_ATTR[R2033] .while ( not_empty te_attr ) .if ( te_attr.translate ) .select any i_avl related by i_ins->I_AVL[R2909] where ( selected.Attr_ID == o_attr.Attr_ID ) .invoke avlcode = PEIRenderInitializerBodyAttribute( o_attr, i_avl ) .assign attr_result = attr_result + avlcode.result .end if .// .// Advance to the next object attribute, if any. .select one te_attr related by te_attr->TE_ATTR[R2087.'precedes'] .// .// Generate comma separator. .if ( not_empty te_attr ) .if ( te_attr.translate ) .assign attr_result = attr_result + "", "" .end if .end if .end while .end if .// .// Generate the association linkage (if needed). .// .invoke ass_init = PEIRenderInitializerBodyAssociation( i_ins, o_obj ) .assign attr_result = attr_result + ass_init.result .assign attr_assset = attr_assset + ass_init.assset .// .end function .// .// .//============================================================================= .// Generate initialization for a single attribute value. .// Return the value as a string quoted correctly (if needed). .//============================================================================= .function PEIRenderInitializerBodyAttribute .param inst_ref o_attr .param inst_ref i_avl .assign attr_result = ""0"" .// Get the attribute data type. Strings need to be quoted. .invoke r = GetAttributeCodeGenType( o_attr ) .assign te_dt = r.result .if ( 4 == te_dt.Core_Typ ) .// string .if ( empty i_avl ) .// In absence of a populated attribute, use the attribute default value. .if ( """" != o_attr.DefaultValue ) .assign attr_result = o_attr.DefaultValue .else .assign attr_result = """""""""""" .end if .else .assign attr_result = """"""${i_avl.Value}"""""" .end if .else .if ( empty i_avl ) .assign attr_result = ""0"" .else .assign attr_result = i_avl.Value .end if .end if .end function .// .// .//============================================================================= .// Generate the optimized association linkage for this instance. .// Select the relationship set for this object. Loop through each one .// generating linkage anywhere storage is provided (for pointer refs). .// Get the multiplicity so we know whether we need sets or simple .// pointers. .// Do the right thing for each flavor of association, simple, reflexive, .// associative and sub/super. .// Return the static initializer body material. .//============================================================================= .function PEIRenderInitializerBodyAssociation .param inst_ref i_ins .param inst_ref o_obj .// .assign multiplicity = 0 .assign attr_assset = """" .assign attr_result = """" .select many te_rels related by o_obj->R_OIR[R201]->R_REL[R201]->TE_REL[R2034] .if ( not_empty te_rels ) .// Pre-order the relationships ascending by their relationship number. .// Note: This decouples code generation from SQL table .// insertion ordering internals. .invoke SortSetAscendingByAttr_Numb( te_rels ) .assign rel_count = 0 .assign rel_cardinality = cardinality te_rels .// .while ( rel_count < rel_cardinality ) .for each te_rel in te_rels .if ( te_rel.Order == rel_count ) .select one rel related by te_rel->R_REL[R2034] .if ( not te_rel.storage_needed ) .break for .end if .// Simple relationship? .select one simple_rel related by rel->R_SIMP[R206] .if ( not_empty simple_rel ) .select any participant related by simple_rel->R_PART[R207] .select one formalizer related by simple_rel->R_FORM[R208] .if ( empty formalizer ) .print ""\\n\\tRelationship R${rel.Numb} is not formalized!\\n"" .exit 101 .end if .// Deal with reflexives. .if ( participant.Obj_ID == formalizer.Obj_ID ) .invoke s = PEIRelInitSimpleReflexive( i_ins, o_obj, rel, participant, formalizer ) .assign attr_result = attr_result + s.result .assign attr_assset = attr_assset + s.assset .else .// Get multiplicity to pass to the code generator. .if ( o_obj.Obj_ID == participant.Obj_ID ) .assign multiplicity = formalizer.Mult .else .assign multiplicity = participant.Mult .end if .invoke s = PEIRelInitSimple( i_ins, o_obj, rel, multiplicity ) .assign attr_result = attr_result + s.result .assign attr_assset = attr_assset + s.assset .end if .// reflexive .else .// elif Subtype-Supertype relationship? .select one r_subsup related by rel->R_SUBSUP[R206] .if ( not_empty r_subsup ) .invoke s = PEIRelInitSubSuper( i_ins, o_obj, rel, r_subsup ) .assign attr_result = attr_result + s.result .else .// elif Associative relationship? .select one assrel related by rel->R_ASSOC[R206] .if ( not_empty assrel ) .invoke s = PEIRelInitAssociative( i_ins, o_obj, rel, assrel ) .assign attr_result = attr_result + s.result .assign attr_assset = attr_assset + s.assset .else .// elif Composed relationship? .select one composed_rel related by rel->R_COMP[R206] .if ( not_empty composed_rel ) .print ""\\nWARNING: R${rel.Numb} is COMPOSITION - No code generated.\\n"" .invoke s = PEIRelInitComposed( o_obj, rel ) .assign attr_result = attr_result + s.result .else .// elif Error: New subtype of R_REL or a corrupted model SQL... .print ""ERROR: Unknown association type:R${rel.Numb} for class '${o_obj.Name}' (${o_obj.Key_Lett})"" .exit 101 .end if .// not_empty composed_rel .end if .// not_empty associative_rel .end if .// not_empty subtype_supertype_rel .end if .// not_empty simp_rel .break for .end if .end for .assign rel_count = rel_count + 1 .end while .// rel_count < rel_cardinality .end if .// not_empty rel_set .end function .// .// .//============================================================================= .// Generate the optimized relationship linkage for a simple association. .// of multiplicity ONE. .//============================================================================= .function PEIRelInitSimple .param inst_ref i_ins .param inst_ref o_obj .param inst_ref r_rel .param integer multiplicity .// .assign attr_result = """" .assign attr_assset = """" .select any related_i_ins from instances of I_INS .// .// Find related instance index. .// Traverse the instance to link to instance chain .// to get the instance ArrayIndex. .if ( multiplicity == 0 ) .// ONE .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .select one related_i_ins related by i_lnk->I_LIP[R2901]->I_INS[R2958] .if ( empty related_i_ins ) .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .select one related_i_ins related by i_lnk->I_LIP[R2902]->I_INS[R2958] .end if .if ( not_empty related_i_ins ) .select one related_o_obj related by related_i_ins->CSME_CIE[R2962]->O_OBJ[R2961] .select one related_te_class related by related_o_obj->TE_CLASS[R2019] .assign attr_result = "", &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}]"" .else .// not participating .assign attr_result = "", 0"" .end if .// not empty .else .// MANY .// Build linked list of containers pointing to related instances. .select many i_lnks related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .select many related1_i_ins related by i_lnks->I_LIP[R2901]->I_INS[R2958] .select many i_lnks related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .select many related2_i_inss related by i_lnks->I_LIP[R2902]->I_INS[R2958] .assign related_i_inss = related1_i_ins | related2_i_inss .invoke s = PEIRenderRelationshipManyOptimization( related_i_inss, o_obj ) .assign attr_result = attr_result + s.result .assign attr_assset = attr_assset + s.assset .end if .// .end function .// .// .//============================================================================= .// Generate the optimized relationship linkage for a simple reflexive .// association. .// In the reflexive case, the part and form are aligned with R2901 and R2902. .//============================================================================= .function PEIRelInitSimpleReflexive .param inst_ref i_ins .param inst_ref o_obj .param inst_ref r_rel .param inst_ref r_part .param inst_ref r_form .// .assign attr_result = """" .assign attr_assset = """" .select one related_te_class related by o_obj->TE_CLASS[R2019] .select any related_i_ins from instances of I_INS .// .// Link the formalizer to the participant. .// .if ( r_part.Mult == 0 ) .// ONE .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .select one related_i_ins related by i_lnk->I_LIP[R2901]->I_INS[R2958] .if ( not_empty related_i_ins ) .assign attr_result = attr_result + "", &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}]"" .else .// Not participating. .assign attr_result = attr_result + "", 0"" .end if .else .// MANY .// Build linked list of containers pointing to related instances. .select many i_lnks related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .select many related_i_inss related by i_lnks->I_LIP[R2901]->I_INS[R2958] .invoke s = PEIRenderRelationshipManyOptimization( related_i_inss, o_obj ) .assign attr_result = attr_result + s.result .assign attr_assset = attr_assset + s.assset .end if .// .// Now link the participant to the formalizer(s). .// .if ( r_form.Mult == 0 ) .// ONE .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .select one related_i_ins related by i_lnk->I_LIP[R2902]->I_INS[R2958] .if ( not_empty related_i_ins ) .assign attr_result = attr_result + "", &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}]"" .else .// Not participating. .assign attr_result = attr_result + "", 0"" .end if .else .// MANY .// Build linked list of containers pointing to related instances. .select many i_lnks related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .select many related_i_inss related by i_lnks->I_LIP[R2902]->I_INS[R2958] .invoke s = PEIRenderRelationshipManyOptimization( related_i_inss, o_obj ) .assign attr_result = attr_result + s.result .assign attr_assset = attr_assset + s.assset .end if .// .end function .// .// .//============================================================================= .// Generate the optimized relationship linkage for an associative .// relationship. .// In the reflexive case, R2901 and R2902 will jive with AONE and AOTH. .// In the non-reflexive, we compare the instance Obj_ID with the .// AONE/AOTH Obj_ID. .//============================================================================= .function PEIRelInitAssociative .param inst_ref i_ins .param inst_ref o_obj .param inst_ref r_rel .param inst_ref r_assoc .// .assign attr_result = """" .assign attr_assset = """" .select one aone related by r_assoc->R_AONE[R209] .select one aoth related by r_assoc->R_AOTH[R210] .select one assr related by r_assoc->R_ASSR[R211] .// .// The other associated instance. .// .if ( o_obj.Obj_ID == aoth.Obj_ID ) .// Optimize relationship to associator. .if ( ( aone.Mult == 0 ) and ( assr.Mult == 0 ) ) .// ONE .select any i_lnk from instances of I_LNK where ( false ) .if ( aone.Obj_ID == aoth.Obj_ID ) .// reflexive .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .else .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .if ( empty i_lnk ) .select one related_o_obj related by i_ins->CSME_CIE[R2962]->O_OBJ[R2961] .if ( related_o_obj.Obj_ID == aoth.Obj_ID ) .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .end if .end if .// not empty .end if .// reflexive .if ( not_empty i_lnk ) .select one related_i_ins related by i_lnk->I_LIP[R2903]->I_INS[R2958] .select one related_o_obj related by related_i_ins->CSME_CIE[R2962]->O_OBJ[R2961] .select one related_te_class related by related_o_obj->TE_CLASS[R2019] .assign attr_result = attr_result + "", &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}]"" .else .// not participating .assign attr_result = attr_result + "", 0"" .end if .// not empty .else .// MANY .// Build linked list of containers pointing to related instances. .select many i_lnks from instances of I_LNK where ( false ) .select many related_i_inss from instances of I_INS where ( false ) .if ( aone.Obj_ID == aoth.Obj_ID ) .// reflexive .select many i_lnks related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .else .select many one_i_lnks related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .select many two_i_lnks related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .assign i_lnks = one_i_lnks | two_i_lnks .end if .select many related_i_inss related by i_lnks->I_LIP[R2903]->I_INS[R2958] .invoke s = PEIRenderRelationshipManyOptimization( related_i_inss, o_obj ) .assign attr_result = attr_result + s.result .assign attr_assset = attr_assset + s.assset .end if .end if .// .// The one associated instance. .// .if ( o_obj.Obj_ID == aone.Obj_ID ) .// Optimize relationship to associator. .if ( ( aoth.Mult == 0 ) and ( assr.Mult == 0 ) ) .// ONE .select any i_lnk from instances of I_LNK where ( false ) .if ( aone.Obj_ID == aoth.Obj_ID ) .// reflexive .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .else .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .if ( empty i_lnk ) .select one related_o_obj related by i_ins->CSME_CIE[R2962]->O_OBJ[R2961] .if ( related_o_obj.Obj_ID == aone.Obj_ID ) .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .end if .end if .end if .// reflexive .if ( not_empty i_lnk ) .select one related_i_ins related by i_lnk->I_LIP[R2903]->I_INS[R2958] .select one related_o_obj related by related_i_ins->CSME_CIE[R2962]->O_OBJ[R2961] .select one related_te_class related by related_o_obj->TE_CLASS[R2019] .assign attr_result = attr_result + "", &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}]"" .else .// not participating .assign attr_result = attr_result + "", 0"" .end if .// not empty .else .// MANY .// Build linked list of containers pointing to related instances. .select many i_lnks from instances of I_LNK where ( false ) .select many related_i_inss from instances of I_INS where ( false ) .if ( aone.Obj_ID == aoth.Obj_ID ) .select many i_lnks related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .else .select many one_i_lnks related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .select many two_i_lnks related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .assign i_lnks = one_i_lnks | two_i_lnks .end if .select many related_i_inss related by i_lnks->I_LIP[R2903]->I_INS[R2958] .invoke s = PEIRenderRelationshipManyOptimization( related_i_inss, o_obj ) .assign attr_result = attr_result + s.result .assign attr_assset = attr_assset + s.assset .end if .end if .// .// The associative instance. .// .if ( o_obj.Obj_ID == assr.Obj_ID ) .// Optimize relationship to both associates. .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2903] where ( selected.Rel_ID == r_rel.Rel_ID ) .if ( not_empty i_lnk ) .select one related_i_ins related by i_lnk->I_LIP[R2901]->I_INS[R2958] .select one related_o_obj related by related_i_ins->CSME_CIE[R2962]->O_OBJ[R2961] .select one related_te_class related by related_o_obj->TE_CLASS[R2019] .select one related2_i_ins related by i_lnk->I_LIP[R2902]->I_INS[R2958] .select one related2_o_obj related by related2_i_ins->CSME_CIE[R2962]->O_OBJ[R2961] .select one related2_te_class related by related2_o_obj->TE_CLASS[R2019] .if ( ( aone.Obj_ID == aoth.Obj_ID ) or ( related2_o_obj.Obj_ID == aone.Obj_ID ) ) .assign attr_result = attr_result + "", &${related2_te_class.GeneratedName}_instances[${related2_i_ins.Name}]"" .assign attr_result = attr_result + "", &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}]"" .else .assign attr_result = attr_result + "", &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}]"" .assign attr_result = attr_result + "", &${related2_te_class.GeneratedName}_instances[${related2_i_ins.Name}]"" .end if .else .// not participating .assign attr_result = attr_result + "", 0, 0"" .end if .// not empty .end if .end function .// .// .//============================================================================= .// Generate the optimized relationship linkage for a Subtype/Supertype .// association. .//============================================================================= .function PEIRelInitSubSuper .param inst_ref i_ins .param inst_ref o_obj .param inst_ref r_rel .param inst_ref r_subsup .assign attr_result = """" .// .// Find related instance index. .// Traverse the instance to link to instance chain .// to get the instance ArrayIndex. .select one super related by r_subsup->R_SUPER[R212] .if ( o_obj.Obj_ID == super.Obj_ID ) .// Supertype .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .select one related_i_ins related by i_lnk->I_LIP[R2902]->I_INS[R2958] .if ( empty i_lnk ) .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .select one related_i_ins related by i_lnk->I_LIP[R2901]->I_INS[R2958] .end if .if ( not_empty i_lnk ) .select one related_o_obj related by related_i_ins->CSME_CIE[R2962]->O_OBJ[R2961] .select one related_te_class related by related_o_obj->TE_CLASS[R2019] .assign attr_result = "", (void *) &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}], ${related_te_class.system_class_number}"" .else .// not participating .assign attr_result = "", 0, 0"" .end if .else .// Subtype .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .if ( not_empty i_lnk ) .select one related_i_ins related by i_lnk->I_LIP[R2901]->I_INS[R2958] .select one related_o_obj related by related_i_ins->CSME_CIE[R2962]->O_OBJ[R2961] .select one related_te_class related by related_o_obj->TE_CLASS[R2019] .assign attr_result = "", &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}]"" .else .// not participating .assign attr_result = "", 0"" .end if .end if .end function .// .// .//============================================================================= .// Generate the optimized relationship linkage for a composed association. .//============================================================================= .function PEIRelInitComposed .param inst_ref o_obj .param inst_ref r_rel .assign attr_result = """" .end function .// .// .//============================================================================= .// Generate an initializer for the current state attribute if needed. .//============================================================================= .function PEIRenderInitializerBodyCurrentState .param inst_ref i_ins .param inst_ref o_obj .assign attr_result = """" .select one te_state related by i_ins->SM_STATE[R2915]->TE_STATE[R2037] .if ( not_empty te_state ) .assign attr_result = te_state.enumerator .end if .end function .// .// .//============================================================================= .// Render relationship MANY optimization. .// This helper is used to render the code used to optimize a relationship .// set. The set variable is generated for inside the instance structure. .// The linked list body pointing to related instances is also generated. .//============================================================================= .function PEIRenderRelationshipManyOptimization .param inst_ref_set i_inss .param inst_ref o_obj .// .assign attr_result = """" .assign attr_assset = """" .select any te_sys from instances of TE_SYS .// i_inss, o_obj .assign instance_count = cardinality i_inss .if ( instance_count > 0 ) .select one te_class related by o_obj->TE_CLASS[R2019] .assign ContainerIndex = te_class.ContainerIndex .// A container index starting greater than zero means we are not the .// first (instance) to be adding linked lists. Precede with comma. .if ( ContainerIndex > 0 ) .assign attr_assset = "",\\n"" .end if .invoke rel_set_name = PEIGetRelationshipSetContainerName( te_class ) .assign attr_result = "", { &${rel_set_name.result}[${ContainerIndex}] }"" .for each related_i_ins in i_inss .assign ContainerIndex = ContainerIndex + 1 .select one related_o_obj related by related_i_ins->CSME_CIE[R2962]->O_OBJ[R2961] .select one related_te_class related by related_o_obj->TE_CLASS[R2019] .if ( last i_inss ) .if ( te_sys.CollectionsFlavor == 20 ) .assign icount = cardinality i_inss .if ( icount > 1 ) .assign attr_assset = attr_assset + "" { 0, (void *) &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}], &${rel_set_name.result}[${ContainerIndex} - 2] }"" .else .assign attr_assset = attr_assset + "" { 0, (void *) &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}], 0 }"" .end if .// cardinality i_inss > 1 .else .assign attr_assset = attr_assset + "" { 0, (void *) &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}] }"" .end if .elif ( first i_inss ) .if ( te_sys.CollectionsFlavor == 20 ) .assign attr_assset = attr_assset + "" { &${rel_set_name.result}[${ContainerIndex}], (void *) &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}], 0 },\\n"" .else .assign attr_assset = attr_assset + "" { &${rel_set_name.result}[${ContainerIndex}], (void *) &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}] },\\n"" .end if .else .if ( te_sys.CollectionsFlavor == 20 ) .assign attr_assset = attr_assset + "" { &${rel_set_name.result}[${ContainerIndex}], (void *) &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}], &${rel_set_name.result}[${ContainerIndex} - 2] },\\n"" .else .assign attr_assset = attr_assset + "" { &${rel_set_name.result}[${ContainerIndex}], (void *) &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}] },\\n"" .end if .end if .end for .assign te_class.ContainerIndex = ContainerIndex .else .// Empty relationship set. .assign attr_result = "", { 0 }"" .end if .end function .// ",8102,False,1917.0470939180339,median ":spring-data-commons-ref: https://docs.spring.io/spring-data/data-commons/docs/current/reference/html == Spring Data Cloud Spanner https://projects.spring.io/spring-data/[Spring Data] is an abstraction for storing and retrieving POJOs in numerous storage technologies. Spring Cloud GCP adds Spring Data support for https://cloud.google.com/spanner/[Google Cloud Spanner]. Maven coordinates for this module only, using <>: [source,xml] ---- com.google.cloud spring-cloud-gcp-data-spanner ---- Gradle coordinates: [source] ---- dependencies { compile group: 'org.springframework.cloud', name: 'spring-cloud-gcp-data-spanner' } ---- We provide a link:../spring-cloud-gcp-starters/spring-cloud-gcp-starter-data-spanner[Spring Boot Starter for Spring Data Spanner], with which you can leverage our recommended auto-configuration setup. To use the starter, see the coordinates see below. Maven: [source,xml] ---- com.google.cloud spring-cloud-gcp-starter-data-spanner ---- Gradle: [source,subs=""normal""] ---- dependencies { compile group: 'org.springframework.cloud', name: 'spring-cloud-gcp-starter-data-spanner' } ---- This setup takes care of bringing in the latest compatible version of Cloud Java Cloud Spanner libraries as well. === Configuration To setup Spring Data Cloud Spanner, you have to configure the following: * Setup the connection details to Google Cloud Spanner. * Enable Spring Data Repositories (optional). ==== Cloud Spanner settings You can the use link:../spring-cloud-gcp-starters/spring-cloud-gcp-starter-data-spanner[Spring Boot Starter for Spring Data Spanner] to autoconfigure Google Cloud Spanner in your Spring application. It contains all the necessary setup that makes it easy to authenticate with your Google Cloud project. The following configuration options are available: |=== | Name | Description | Required | Default value | `spring.cloud.gcp.spanner.instance-id` | Cloud Spanner instance to use | Yes | | `spring.cloud.gcp.spanner.database` | Cloud Spanner database to use | Yes | | `spring.cloud.gcp.spanner.project-id` | GCP project ID where the Google Cloud Spanner API is hosted, if different from the one in the <> | No | | `spring.cloud.gcp.spanner.credentials.location` | OAuth2 credentials for authenticating with the Google Cloud Spanner API, if different from the ones in the <> | No | | `spring.cloud.gcp.spanner.credentials.encoded-key` | Base64-encoded OAuth2 credentials for authenticating with the Google Cloud Spanner API, if different from the ones in the <> | No | | `spring.cloud.gcp.spanner.credentials.scopes` | https://developers.google.com/identity/protocols/googlescopes[OAuth2 scope] for Spring Cloud GCP Cloud Spanner credentials | No | https://www.googleapis.com/auth/spanner.data | `spring.cloud.gcp.spanner.createInterleavedTableDdlOnDeleteCascade` | If `true`, then schema statements generated by `SpannerSchemaUtils` for tables with interleaved parent-child relationships will be ""ON DELETE CASCADE"". The schema for the tables will be ""ON DELETE NO ACTION"" if `false`. | No | `true` | `spring.cloud.gcp.spanner.numRpcChannels` | Number of gRPC channels used to connect to Cloud Spanner | No | 4 - Determined by Cloud Spanner client library | `spring.cloud.gcp.spanner.prefetchChunks` | Number of chunks prefetched by Cloud Spanner for read and query | No | 4 - Determined by Cloud Spanner client library | `spring.cloud.gcp.spanner.minSessions` | Minimum number of sessions maintained in the session pool | No | 0 - Determined by Cloud Spanner client library | `spring.cloud.gcp.spanner.maxSessions` | Maximum number of sessions session pool can have | No | 400 - Determined by Cloud Spanner client library | `spring.cloud.gcp.spanner.maxIdleSessions` | Maximum number of idle sessions session pool will maintain | No | 0 - Determined by Cloud Spanner client library | `spring.cloud.gcp.spanner.writeSessionsFraction` | Fraction of sessions to be kept prepared for write transactions | No | 0.2 - Determined by Cloud Spanner client library | `spring.cloud.gcp.spanner.keepAliveIntervalMinutes` | How long to keep idle sessions alive | No | 30 - Determined by Cloud Spanner client library | `spring.cloud.gcp.spanner.failIfPoolExhausted` | If all sessions are in use, fail the request by throwing an exception. Otherwise, by default, block until a session becomes available. | No | `false` | `spring.cloud.gcp.spanner.emulator.enabled` | Enables the usage of an emulator. If this is set to true, then you should set the `spring.cloud.gcp.spanner.emulator-host` to the host:port of your locally running emulator instance. | No | `false` | `spring.cloud.gcp.spanner.emulator-host` | The host and port of the Spanner emulator; can be overridden to specify connecting to an already-running https://cloud.google.com/spanner/docs/emulator#installing_and_running_the_emulator[Spanner emulator] instance. | No | `localhost:9010` |=== ==== Repository settings Spring Data Repositories can be configured via the `@EnableSpannerRepositories` annotation on your main `@Configuration` class. With our Spring Boot Starter for Spring Data Cloud Spanner, `@EnableSpannerRepositories` is automatically added. It is not required to add it to any other class, unless there is a need to override finer grain configuration parameters provided by https://github.com/spring-cloud/spring-cloud-gcp/blob/master/spring-cloud-gcp-data-spanner/src/main/java/org/springframework/cloud/gcp/data/spanner/repository/config/EnableSpannerRepositories.java[`@EnableSpannerRepositories`]. ==== Autoconfiguration Our Spring Boot autoconfiguration creates the following beans available in the Spring application context: - an instance of `SpannerTemplate` - an instance of `SpannerDatabaseAdminTemplate` for generating table schemas from object hierarchies and creating and deleting tables and databases - an instance of all user-defined repositories extending `SpannerRepository`, `CrudRepository`, `PagingAndSortingRepository`, when repositories are enabled - an instance of `DatabaseClient` from the Google Cloud Java Client for Spanner, for convenience and lower level API access === Object Mapping Spring Data Cloud Spanner allows you to map domain POJOs to Cloud Spanner tables via annotations: [source,java] ---- @Table(name = ""traders"") public class Trader { @PrimaryKey @Column(name = ""trader_id"") String traderId; String firstName; String lastName; @NotMapped Double temporaryNumber; } ---- Spring Data Cloud Spanner will ignore any property annotated with `@NotMapped`. These properties will not be written to or read from Spanner. ==== Constructors Simple constructors are supported on POJOs. The constructor arguments can be a subset of the persistent properties. Every constructor argument needs to have the same name and type as a persistent property on the entity and the constructor should set the property from the given argument. Arguments that are not directly set to properties are not supported. [source,java] ---- @Table(name = ""traders"") public class Trader { @PrimaryKey @Column(name = ""trader_id"") String traderId; String firstName; String lastName; @NotMapped Double temporaryNumber; public Trader(String traderId, String firstName) { this.traderId = traderId; this.firstName = firstName; } } ---- ==== Table The `@Table` annotation can provide the name of the Cloud Spanner table that stores instances of the annotated class, one per row. This annotation is optional, and if not given, the name of the table is inferred from the class name with the first character uncapitalized. ===== SpEL expressions for table names In some cases, you might want the `@Table` table name to be determined dynamically. To do that, you can use https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#expressions[Spring Expression Language]. For example: [source, java] ---- @Table(name = ""trades_#{tableNameSuffix}"") public class Trade { // ... } ---- The table name will be resolved only if the `tableNameSuffix` value/bean in the Spring application context is defined. For example, if `tableNameSuffix` has the value ""123"", the table name will resolve to `trades_123`. ==== Primary Keys For a simple table, you may only have a primary key consisting of a single column. Even in that case, the `@PrimaryKey` annotation is required. `@PrimaryKey` identifies the one or more ID properties corresponding to the primary key. Spanner has first class support for composite primary keys of multiple columns. You have to annotate all of your POJO's fields that the primary key consists of with `@PrimaryKey` as below: [source,java] ---- @Table(name = ""trades"") public class Trade { @PrimaryKey(keyOrder = 2) @Column(name = ""trade_id"") private String tradeId; @PrimaryKey(keyOrder = 1) @Column(name = ""trader_id"") private String traderId; private String action; private Double price; private Double shares; private String symbol; } ---- The `keyOrder` parameter of `@PrimaryKey` identifies the properties corresponding to the primary key columns in order, starting with 1 and increasing consecutively. Order is important and must reflect the order defined in the Cloud Spanner schema. In our example the DDL to create the table and its primary key is as follows: [source,sql] ---- CREATE TABLE trades ( trader_id STRING(MAX), trade_id STRING(MAX), action STRING(15), symbol STRING(10), price FLOAT64, shares FLOAT64 ) PRIMARY KEY (trader_id, trade_id) ---- Spanner does not have automatic ID generation. For most use-cases, sequential IDs should be used with caution to avoid creating data hotspots in the system. Read https://cloud.google.com/spanner/docs/schema-and-data-model#primary_keys[Spanner Primary Keys documentation] for a better understanding of primary keys and recommended practices. ==== Columns All accessible properties on POJOs are automatically recognized as a Cloud Spanner column. Column naming is generated by the `PropertyNameFieldNamingStrategy` by default defined on the `SpannerMappingContext` bean. The `@Column` annotation optionally provides a different column name than that of the property and some other settings: - `name` is the optional name of the column - `spannerTypeMaxLength` specifies for `STRING` and `BYTES` columns the maximum length. This setting is only used when generating DDL schema statements based on domain types. - `nullable` specifies if the column is created as `NOT NULL`. This setting is only used when generating DDL schema statements based on domain types. - `spannerType` is the Cloud Spanner column type you can optionally specify. If this is not specified then a compatible column type is inferred from the Java property type. - `spannerCommitTimestamp` is a boolean specifying if this property corresponds to an auto-populated commit timestamp column. Any value set in this property will be ignored when writing to Cloud Spanner. ==== Embedded Objects If an object of type `B` is embedded as a property of `A`, then the columns of `B` will be saved in the same Cloud Spanner table as those of `A`. If `B` has primary key columns, those columns will be included in the primary key of `A`. `B` can also have embedded properties. Embedding allows reuse of columns between multiple entities, and can be useful for implementing parent-child situations, because Cloud Spanner requires child tables to include the key columns of their parents. For example: [source,java] ---- class X { @PrimaryKey String grandParentId; long age; } class A { @PrimaryKey @Embedded X grandParent; @PrimaryKey(keyOrder = 2) String parentId; String value; } @Table(name = ""items"") class B { @PrimaryKey @Embedded A parent; @PrimaryKey(keyOrder = 2) String id; @Column(name = ""child_value"") String value; } ---- Entities of `B` can be stored in a table defined as: [source,sql] ---- CREATE TABLE items ( grandParentId STRING(MAX), parentId STRING(MAX), id STRING(MAX), value STRING(MAX), child_value STRING(MAX), age INT64 ) PRIMARY KEY (grandParentId, parentId, id) ---- Note that embedded properties' column names must all be unique. ==== Relationships Spring Data Cloud Spanner supports parent-child relationships using the Cloud Spanner https://cloud.google.com/spanner/docs/schema-and-data-model#creating-interleaved-tables[parent-child interleaved table mechanism]. Cloud Spanner interleaved tables enforce the one-to-many relationship and provide efficient queries and operations on entities of a single domain parent entity. These relationships can be up to 7 levels deep. Cloud Spanner also provides automatic cascading delete or enforces the deletion of child entities before parents. While one-to-one and many-to-many relationships can be implemented in Cloud Spanner and Spring Data Cloud Spanner using constructs of interleaved parent-child tables, only the parent-child relationship is natively supported. Cloud Spanner does not support the foreign key constraint, though the parent-child key constraint enforces a similar requirement when used with interleaved tables. For example, the following Java entities: [source,java] ---- @Table(name = ""Singers"") class Singer { @PrimaryKey long SingerId; String FirstName; String LastName; byte[] SingerInfo; @Interleaved List albums; } @Table(name = ""Albums"") class Album { @PrimaryKey long SingerId; @PrimaryKey(keyOrder = 2) long AlbumId; String AlbumTitle; } ---- These classes can correspond to an existing pair of interleaved tables. The `@Interleaved` annotation may be applied to `Collection` properties and the inner type is resolved as the child entity type. The schema needed to create them can also be generated using the `SpannerSchemaUtils` and run by using the `SpannerDatabaseAdminTemplate`: [source,java] ---- @Autowired SpannerSchemaUtils schemaUtils; @Autowired SpannerDatabaseAdminTemplate databaseAdmin; ... // Get the create statmenets for all tables in the table structure rooted at Singer List createStrings = this.schemaUtils.getCreateTableDdlStringsForInterleavedHierarchy(Singer.class); // Create the tables and also create the database if necessary this.databaseAdmin.executeDdlStrings(createStrings, true); ---- The `createStrings` list contains table schema statements using column names and types compatible with the provided Java type and any resolved child relationship types contained within based on the configured custom converters. [source,sql] ---- CREATE TABLE Singers ( SingerId INT64 NOT NULL, FirstName STRING(1024), LastName STRING(1024), SingerInfo BYTES(MAX), ) PRIMARY KEY (SingerId); CREATE TABLE Albums ( SingerId INT64 NOT NULL, AlbumId INT64 NOT NULL, AlbumTitle STRING(MAX), ) PRIMARY KEY (SingerId, AlbumId), INTERLEAVE IN PARENT Singers ON DELETE CASCADE; ---- The `ON DELETE CASCADE` clause indicates that Cloud Spanner will delete all Albums of a singer if the Singer is deleted. The alternative is `ON DELETE NO ACTION`, where a Singer cannot be deleted until all of its Albums have already been deleted. When using `SpannerSchemaUtils` to generate the schema strings, the `spring.cloud.gcp.spanner.createInterleavedTableDdlOnDeleteCascade` boolean setting determines if these schema are generated as `ON DELETE CASCADE` for `true` and `ON DELETE NO ACTION` for `false`. Cloud Spanner restricts these relationships to 7 child layers. A table may have multiple child tables. On updating or inserting an object to Cloud Spanner, all of its referenced children objects are also updated or inserted in the same request, respectively. On read, all of the interleaved child rows are also all read. ===== Lazy Fetch `@Interleaved` properties are retrieved eagerly by default, but can be fetched lazily for performance in both read and write: [source,java] ---- @Interleaved(lazy = true) List albums; ---- Lazily-fetched interleaved properties are retrieved upon the first interaction with the property. If a property marked for lazy fetching is never retrieved, then it is also skipped when saving the parent entity. If used inside a transaction, subsequent operations on lazily-fetched properties use the same transaction context as that of the original parent entity. ===== Declarative Filtering with `@Where` The `@Where` annotation could be applied to an entity class or to an interleaved property. This annotation provides an SQL where clause that will be applied at the fetching of interleaved collections or the entity itself. Let's say we have an `Agreement` with a list of `Participants` which could be assigned to it. We would like to fetch a list of currently active participants. For security reasons, all records should remain in the database forever, even if participants become inactive. That can be easily achieved with the `@Where` annotation, which is demonstrated by this example: [source, java] ---- @Table(name = ""participants"") public class Participant { //... boolean active; //... } @Table(name = ""agreements"") public class Agreement { //... @Interleaved @Where(""active = true"") List participants; Person person; //... } ---- ==== Supported Types Spring Data Cloud Spanner natively supports the following types for regular fields but also utilizes custom converters (detailed in following sections) and dozens of pre-defined Spring Data custom converters to handle other common Java types. Natively supported types: * `com.google.cloud.ByteArray` * `com.google.cloud.Date` * `com.google.cloud.Timestamp` * `java.lang.Boolean`, `boolean` * `java.lang.Double`, `double` * `java.lang.Long`, `long` * `java.lang.Integer`, `int` * `java.lang.String` * `double[]` * `long[]` * `boolean[]` * `java.util.Date` * `java.time.Instant` * `java.sql.Date` * `java.time.LocalDate` * `java.time.LocalDateTime` ==== Lists Spanner supports `ARRAY` types for columns. `ARRAY` columns are mapped to `List` fields in POJOS. Example: [source,java] ---- List curve; ---- The types inside the lists can be any singular property type. ==== Lists of Structs Cloud Spanner queries can https://cloud.google.com/spanner/docs/query-syntax#using-structs-with-select[construct STRUCT values] that appear as columns in the result. Cloud Spanner requires STRUCT values appear in ARRAYs at the root level: `SELECT ARRAY(SELECT STRUCT(1 as val1, 2 as val2)) as pair FROM Users`. Spring Data Cloud Spanner will attempt to read the column STRUCT values into a property that is an `Iterable` of an entity type compatible with the schema of the column STRUCT value. For the previous array-select example, the following property can be mapped with the constructed `ARRAY` column: `List pair;` where the `TwoInts` type is defined: [source, java] ---- class TwoInts { int val1; int val2; } ---- ==== Custom types Custom converters can be used to extend the type support for user defined types. . Converters need to implement the `org.springframework.core.convert.converter.Converter` interface in both directions. . The user defined type needs to be mapped to one of the basic types supported by Spanner: * `com.google.cloud.ByteArray` * `com.google.cloud.Date` * `com.google.cloud.Timestamp` * `java.lang.Boolean`, `boolean` * `java.lang.Double`, `double` * `java.lang.Long`, `long` * `java.lang.String` * `double[]` * `long[]` * `boolean[]` * `enum` types . An instance of both Converters needs to be passed to a `ConverterAwareMappingSpannerEntityProcessor`, which then has to be made available as a `@Bean` for `SpannerEntityProcessor`. For example: We would like to have a field of type `Person` on our `Trade` POJO: [source, java] ---- @Table(name = ""trades"") public class Trade { //... Person person; //... } ---- Where Person is a simple class: [source, java] ---- public class Person { public String firstName; public String lastName; } ---- We have to define the two converters: [source, java] ---- public class PersonWriteConverter implements Converter { @Override public String convert(Person person) { return person.firstName + "" "" + person.lastName; } } public class PersonReadConverter implements Converter { @Override public Person convert(String s) { Person person = new Person(); person.firstName = s.split("" "")[0]; person.lastName = s.split("" "")[1]; return person; } } ---- That will be configured in our `@Configuration` file: [source, java] ---- @Configuration public class ConverterConfiguration { @Bean public SpannerEntityProcessor spannerEntityProcessor(SpannerMappingContext spannerMappingContext) { return new ConverterAwareMappingSpannerEntityProcessor(spannerMappingContext, Arrays.asList(new PersonWriteConverter()), Arrays.asList(new PersonReadConverter())); } } ---- ==== Custom Converter for Struct Array Columns If a `Converter` is provided, then properties of type `List` can be used in your entity types. === Spanner Operations & Template `SpannerOperations` and its implementation, `SpannerTemplate`, provides the Template pattern familiar to Spring developers. It provides: - Resource management - One-stop-shop to Spanner operations with the Spring Data POJO mapping and conversion features - Exception conversion Using the `autoconfigure` provided by our Spring Boot Starter for Spanner, your Spring application context will contain a fully configured `SpannerTemplate` object that you can easily autowire in your application: [source,java] ---- @SpringBootApplication public class SpannerTemplateExample { @Autowired SpannerTemplate spannerTemplate; public void doSomething() { this.spannerTemplate.delete(Trade.class, KeySet.all()); //... Trade t = new Trade(); //... this.spannerTemplate.insert(t); //... List tradesByAction = spannerTemplate.findAll(Trade.class); //... } } ---- The Template API provides convenience methods for: - https://cloud.google.com/spanner/docs/reads[Reads], and by providing SpannerReadOptions and SpannerQueryOptions ** Stale read ** Read with secondary indices ** Read with limits and offsets ** Read with sorting - https://cloud.google.com/spanner/docs/reads#execute_a_query[Queries] - DML operations (delete, insert, update, upsert) - Partial reads ** You can define a set of columns to be read into your entity - Partial writes ** Persist only a few properties from your entity - Read-only transactions - Locking read-write transactions ==== SQL Query Cloud Spanner has SQL support for running read-only queries. All the query related methods start with `query` on `SpannerTemplate`. By using `SpannerTemplate`, you can run SQL queries that map to POJOs: [source,java] ---- List trades = this.spannerTemplate.query(Trade.class, Statement.of(""SELECT * FROM trades"")); ---- ==== Read Spanner exposes a https://cloud.google.com/spanner/docs/reads[Read API] for reading single row or multiple rows in a table or in a secondary index. Using `SpannerTemplate` you can run reads, as the following example shows: [source,java] ---- List trades = this.spannerTemplate.readAll(Trade.class); ---- Main benefit of reads over queries is reading multiple rows of a certain pattern of keys is much easier using the features of the https://github.com/GoogleCloudPlatform/google-cloud-java/blob/master/google-cloud-spanner/src/main/java/com/google/cloud/spanner/KeySet.java[`KeySet`] class. ==== Advanced reads ===== Stale read All reads and queries are *strong reads* by default. A *strong read* is a read at a current time and is guaranteed to see all data that has been committed up until the start of this read. An *exact staleness read* is read at a timestamp in the past. Cloud Spanner allows you to determine how current the data should be when you read data. With `SpannerTemplate` you can specify the `Timestamp` by setting it on `SpannerQueryOptions` or `SpannerReadOptions` to the appropriate read or query methods: Reads: [source,java] ---- // a read with options: SpannerReadOptions spannerReadOptions = new SpannerReadOptions().setTimestamp(myTimestamp); List trades = this.spannerTemplate.readAll(Trade.class, spannerReadOptions); ---- Queries: [source,java] ---- // a query with options: SpannerQueryOptions spannerQueryOptions = new SpannerQueryOptions().setTimestamp(myTimestamp); List trades = this.spannerTemplate.query(Trade.class, Statement.of(""SELECT * FROM trades""), spannerQueryOptions); ---- You can also read with https://cloud.google.com/spanner/docs/timestamp-bounds[*bounded staleness*] by setting `.setTimestampBound(TimestampBound.ofMinReadTimestamp(myTimestamp))` on the query and read options objects. Bounded staleness lets Cloud Spanner choose any point in time later than or equal to the given timestampBound, but it cannot be used inside transactions. ===== Read from a secondary index Using a https://cloud.google.com/spanner/docs/secondary-indexes[secondary index] is available for Reads via the Template API and it is also implicitly available via SQL for Queries. The following shows how to read rows from a table using a https://cloud.google.com/spanner/docs/secondary-indexes[secondary index] simply by setting `index` on `SpannerReadOptions`: [source,java] ---- SpannerReadOptions spannerReadOptions = new SpannerReadOptions().setIndex(""TradesByTrader""); List trades = this.spannerTemplate.readAll(Trade.class, spannerReadOptions); ---- ===== Read with offsets and limits Limits and offsets are only supported by Queries. The following will get only the first two rows of the query: [source,java] ---- SpannerQueryOptions spannerQueryOptions = new SpannerQueryOptions().setLimit(2).setOffset(3); List trades = this.spannerTemplate.query(Trade.class, Statement.of(""SELECT * FROM trades""), spannerQueryOptions); ---- Note that the above is equivalent of running `SELECT * FROM trades LIMIT 2 OFFSET 3`. ===== Sorting Reads by keys do not support sorting. However, queries on the Template API support sorting through standard SQL and also via Spring Data Sort API: [source,java] ---- List trades = this.spannerTemplate.queryAll(Trade.class, Sort.by(""action"")); ---- If the provided sorted field name is that of a property of the domain type, then the column name corresponding to that property will be used in the query. Otherwise, the given field name is assumed to be the name of the column in the Cloud Spanner table. Sorting on columns of Cloud Spanner types STRING and BYTES can be done while ignoring case: [source,java] ---- Sort.by(Order.desc(""action"").ignoreCase()) ---- ===== Partial read Partial read is only possible when using Queries. In case the rows returned by the query have fewer columns than the entity that it will be mapped to, Spring Data will map the returned columns only. This setting also applies to nested structs and their corresponding nested POJO properties. [source,java] ---- List trades = this.spannerTemplate.query(Trade.class, Statement.of(""SELECT action, symbol FROM trades""), new SpannerQueryOptions().setAllowMissingResultSetColumns(true)); ---- If the setting is set to `false`, then an exception will be thrown if there are missing columns in the query result. ===== Summary of options for Query vs Read |=== | Feature | Query supports it | Read supports it | SQL | yes | no | Partial read | yes | no | Limits | yes | no | Offsets | yes | no | Secondary index | yes | yes | Read using index range | no | yes | Sorting | yes | no |=== ==== Write / Update The write methods of `SpannerOperations` accept a POJO and writes all of its properties to Spanner. The corresponding Spanner table and entity metadata is obtained from the given object's actual type. If a POJO was retrieved from Spanner and its primary key properties values were changed and then written or updated, the operation will occur as if against a row with the new primary key values. The row with the original primary key values will not be affected. ===== Insert The `insert` method of `SpannerOperations` accepts a POJO and writes all of its properties to Spanner, which means the operation will fail if a row with the POJO's primary key already exists in the table. [source, java] ---- Trade t = new Trade(); this.spannerTemplate.insert(t); ---- ===== Update The `update` method of `SpannerOperations` accepts a POJO and writes all of its properties to Spanner, which means the operation will fail if the POJO's primary key does not already exist in the table. [source, java] ---- // t was retrieved from a previous operation this.spannerTemplate.update(t); ---- ===== Upsert The `upsert` method of `SpannerOperations` accepts a POJO and writes all of its properties to Spanner using update-or-insert. [source, java] ---- // t was retrieved from a previous operation or it's new this.spannerTemplate.upsert(t); ---- ===== Partial Update The update methods of `SpannerOperations` operate by default on all properties within the given object, but also accept `String[]` and `Optional>` of column names. If the `Optional` of set of column names is empty, then all columns are written to Spanner. However, if the Optional is occupied by an empty set, then no columns will be written. [source, java] ---- // t was retrieved from a previous operation or it's new this.spannerTemplate.update(t, ""symbol"", ""action""); ---- ==== DML DML statements can be run by using `SpannerOperations.executeDmlStatement`. Inserts, updates, and deletions can affect any number of rows and entities. You can run https://cloud.google.com/spanner/docs/dml-partitioned[partitioned DML] updates by using the `executePartitionedDmlStatement` method. Partitioned DML queries have performance benefits but also have restrictions and cannot be used inside transactions. ==== Transactions `SpannerOperations` provides methods to run `java.util.Function` objects within a single transaction while making available the read and write methods from `SpannerOperations`. ===== Read/Write Transaction Read and write transactions are provided by `SpannerOperations` via the `performReadWriteTransaction` method: [source,java] ---- @Autowired SpannerOperations mySpannerOperations; public String doWorkInsideTransaction() { return mySpannerOperations.performReadWriteTransaction( transActionSpannerOperations -> { // Work with transActionSpannerOperations here. // It is also a SpannerOperations object. return ""transaction completed""; } ); } ---- The `performReadWriteTransaction` method accepts a `Function` that is provided an instance of a `SpannerOperations` object. The final returned value and type of the function is determined by the user. You can use this object just as you would a regular `SpannerOperations` with a few exceptions: - Its read functionality cannot perform stale reads, because all reads and writes happen at the single point in time of the transaction. - It cannot perform sub-transactions via `performReadWriteTransaction` or `performReadOnlyTransaction`. As these read-write transactions are locking, it is recommended that you use the `performReadOnlyTransaction` if your function does not perform any writes. ===== Read-only Transaction The `performReadOnlyTransaction` method is used to perform read-only transactions using a `SpannerOperations`: [source,java] ---- @Autowired SpannerOperations mySpannerOperations; public String doWorkInsideTransaction() { return mySpannerOperations.performReadOnlyTransaction( transActionSpannerOperations -> { // Work with transActionSpannerOperations here. // It is also a SpannerOperations object. return ""transaction completed""; } ); } ---- The `performReadOnlyTransaction` method accepts a `Function` that is provided an instance of a `SpannerOperations` object. This method also accepts a `ReadOptions` object, but the only attribute used is the timestamp used to determine the snapshot in time to perform the reads in the transaction. If the timestamp is not set in the read options the transaction is run against the current state of the database. The final returned value and type of the function is determined by the user. You can use this object just as you would a regular `SpannerOperations` with a few exceptions: - Its read functionality cannot perform stale reads (other than the staleness set on the entire transaction), because all reads happen at the single point in time of the transaction. - It cannot perform sub-transactions via `performReadWriteTransaction` or `performReadOnlyTransaction` - It cannot perform any write operations. Because read-only transactions are non-locking and can be performed on points in time in the past, these are recommended for functions that do not perform write operations. ===== Declarative Transactions with @Transactional Annotation This feature requires a bean of `SpannerTransactionManager`, which is provided when using `spring-cloud-gcp-starter-data-spanner`. `SpannerTemplate` and `SpannerRepository` support running methods with the `@Transactional` https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#transaction-declarative[annotation] as transactions. If a method annotated with `@Transactional` calls another method also annotated, then both methods will work within the same transaction. `performReadOnlyTransaction` and `performReadWriteTransaction` cannot be used in `@Transactional` annotated methods because Cloud Spanner does not support transactions within transactions. ==== DML Statements `SpannerTemplate` supports https://cloud.google.com/spanner/docs/dml-tasks:[DML] `Statements`. DML statements can also be run in transactions by using `performReadWriteTransaction` or by using the `@Transactional` annotation. === Repositories {spring-data-commons-ref}/#repositories[Spring Data Repositories] are a powerful abstraction that can save you a lot of boilerplate code. For example: [source,java] ---- public interface TraderRepository extends SpannerRepository { } ---- Spring Data generates a working implementation of the specified interface, which can be conveniently autowired into an application. The `Trader` type parameter to `SpannerRepository` refers to the underlying domain type. The second type parameter, `String` in this case, refers to the type of the key of the domain type. For POJOs with a composite primary key, this ID type parameter can be any descendant of `Object[]` compatible with all primary key properties, any descendant of `Iterable`, or `com.google.cloud.spanner.Key`. If the domain POJO type only has a single primary key column, then the primary key property type can be used or the `Key` type. For example in case of Trades, that belong to a Trader, `TradeRepository` would look like this: [source,java] ---- public interface TradeRepository extends SpannerRepository { } ---- [source,java] ---- public class MyApplication { @Autowired SpannerTemplate spannerTemplate; @Autowired StudentRepository studentRepository; public void demo() { this.tradeRepository.deleteAll(); String traderId = ""demo_trader""; Trade t = new Trade(); t.symbol = stock; t.action = action; t.traderId = traderId; t.price = 100.0; t.shares = 12345.6; this.spannerTemplate.insert(t); Iterable allTrades = this.tradeRepository.findAll(); int count = this.tradeRepository.countByAction(""BUY""); } } ---- ==== CRUD Repository `CrudRepository` methods work as expected, with one thing Spanner specific: the `save` and `saveAll` methods work as update-or-insert. ==== Paging and Sorting Repository You can also use `PagingAndSortingRepository` with Spanner Spring Data. The sorting and pageable `findAll` methods available from this interface operate on the current state of the Spanner database. As a result, beware that the state of the database (and the results) might change when moving page to page. ==== Spanner Repository The `SpannerRepository` extends the `PagingAndSortingRepository`, but adds the read-only and the read-write transaction functionality provided by Spanner. These transactions work very similarly to those of `SpannerOperations`, but is specific to the repository's domain type and provides repository functions instead of template functions. For example, this is a read-only transaction: [source,java] ---- @Autowired SpannerRepository myRepo; public String doWorkInsideTransaction() { return myRepo.performReadOnlyTransaction( transactionSpannerRepo -> { // Work with the single-transaction transactionSpannerRepo here. // This is a SpannerRepository object. return ""transaction completed""; } ); } ---- When creating custom repositories for your own domain types and query methods, you can extend `SpannerRepository` to access Cloud Spanner-specific features as well as all features from `PagingAndSortingRepository` and `CrudRepository`. === Query Methods `SpannerRepository` supports Query Methods. Described in the following sections, these are methods residing in your custom repository interfaces of which implementations are generated based on their names and annotations. Query Methods can read, write, and delete entities in Cloud Spanner. Parameters to these methods can be any Cloud Spanner data type supported directly or via custom configured converters. Parameters can also be of type `Struct` or POJOs. If a POJO is given as a parameter, it will be converted to a `Struct` with the same type-conversion logic as used to create write mutations. Comparisons using Struct parameters are limited to https://cloud.google.com/spanner/docs/data-types#limited-comparisons-for-struct[what is available with Cloud Spanner]. ==== Query methods by convention [source, java] ---- public interface TradeRepository extends SpannerRepository { List findByAction(String action); int countByAction(String action); // Named methods are powerful, but can get unwieldy List findTop3DistinctByActionAndSymbolIgnoreCaseOrTraderIdOrderBySymbolDesc( String action, String symbol, String traderId); } ---- In the example above, the {spring-data-commons-ref}/#repositories.query-methods[query methods] in `TradeRepository` are generated based on the name of the methods, using the {spring-data-commons-ref}#repositories.query-methods.query-creation[Spring Data Query creation naming convention]. `List findByAction(String action)` would translate to a `SELECT * FROM trades WHERE action = ?`. The function `List findTop3DistinctByActionAndSymbolIgnoreCaseOrTraderIdOrderBySymbolDesc(String action, String symbol, String traderId);` will be translated as the equivalent of this SQL query: [source, sql] ---- SELECT DISTINCT * FROM trades WHERE ACTION = ? AND LOWER(SYMBOL) = LOWER(?) AND TRADER_ID = ? ORDER BY SYMBOL DESC LIMIT 3 ---- The following filter options are supported: * Equality * Greater than or equals * Greater than * Less than or equals * Less than * Is null * Is not null * Is true * Is false * Like a string * Not like a string * Contains a string * Not contains a string * In * Not in Note that the phrase `SymbolIgnoreCase` is translated to `LOWER(SYMBOL) = LOWER(?)` indicating a non-case-sensitive matching. The `IgnoreCase` phrase may only be appended to fields that correspond to columns of type STRING or BYTES. The Spring Data ""AllIgnoreCase"" phrase appended at the end of the method name is not supported. The `Like` or `NotLike` naming conventions: [source, java] ---- List findBySymbolLike(String symbolFragment); ---- The param `symbolFragment` can contain https://cloud.google.com/spanner/docs/functions-and-operators#comparison-operators[wildcard characters] for string matching such as `_` and `%`. The `Contains` and `NotContains` naming conventions: [source, java] ---- List findBySymbolContains(String symbolFragment); ---- The param `symbolFragment` is a https://cloud.google.com/spanner/docs/functions-and-operators#regexp_contains[regular expression] that is checked for occurrences. The `In` and `NotIn` keywords must be used with `Iterable` corresponding parameters. Delete queries are also supported. For example, query methods such as `deleteByAction` or `removeByAction` delete entities found by `findByAction`. The delete operation happens in a single transaction. Delete queries can have the following return types: * An integer type that is the number of entities deleted * A collection of entities that were deleted * `void` ==== Custom SQL/DML query methods The example above for `List fetchByActionNamedQuery(String action)` does not match the {spring-data-commons-ref}#repositories.query-methods.query-creation[Spring Data Query creation naming convention], so we have to map a parametrized Spanner SQL query to it. The SQL query for the method can be mapped to repository methods in one of two ways: * `namedQueries` properties file * using the `@Query` annotation The names of the tags of the SQL correspond to the `@Param` annotated names of the method parameters. Interleaved properties are loaded eagerly, unless they are annotated with `@Interleaved(lazy = true)`. Custom SQL query methods can accept a single `Sort` or `Pageable` parameter that is applied on top of the specified custom query. It is the recommended way to control the sort order of the results, which is not guaranteed by the `ORDER BY` clause in the SQL query. This is due to the fact that the user-provided query is used as a sub-query, and Cloud Spanner doesn't preserve order in subquery results. You might want to use `ORDER BY` with `LIMIT` to obtain the top records, according to a specified order. However, to ensure the correct sort order of the final result set, sort options have to be passed in with a `Pageable`. [source, java] ---- @Query(""SELECT * FROM trades"") List fetchTrades(Pageable pageable); @Query(""SELECT * FROM trades ORDER BY price DESC LIMIT 1"") Trade topTrade(Pageable pageable); ---- This can be used: [source, java] ---- List customSortedTrades = tradeRepository.fetchTrades(PageRequest .of(2, 2, org.springframework.data.domain.Sort.by(Order.asc(""id"")))); ---- The results would be sorted by ""id"" in ascending order. Your query method can also return non-entity types: [source, java] ---- @Query(""SELECT COUNT(1) FROM trades WHERE action = @action"") int countByActionQuery(String action); @Query(""SELECT EXISTS(SELECT COUNT(1) FROM trades WHERE action = @action)"") boolean existsByActionQuery(String action); @Query(""SELECT action FROM trades WHERE action = @action LIMIT 1"") String getFirstString(@Param(""action"") String action); @Query(""SELECT action FROM trades WHERE action = @action"") List getFirstStringList(@Param(""action"") String action); ---- DML statements can also be run by query methods, but the only possible return value is a `long` representing the number of affected rows. The `dmlStatement` boolean setting must be set on `@Query` to indicate that the query method is run as a DML statement. [source, java] ---- @Query(value = ""DELETE FROM trades WHERE action = @action"", dmlStatement = true) long deleteByActionQuery(String action); ---- ===== Query methods with named queries properties By default, the `namedQueriesLocation` attribute on `@EnableSpannerRepositories` points to the `META-INF/spanner-named-queries.properties` file. You can specify the query for a method in the properties file by providing the SQL as the value for the ""interface.method"" property: [source, properties] ---- Trade.fetchByActionNamedQuery=SELECT * FROM trades WHERE trades.action = @tag0 ---- [source, java] ---- public interface TradeRepository extends SpannerRepository { // This method uses the query from the properties file instead of one generated based on name. List fetchByActionNamedQuery(@Param(""tag0"") String action); } ---- ===== Query methods with annotation Using the `@Query` annotation: [source, java] ---- public interface TradeRepository extends SpannerRepository { @Query(""SELECT * FROM trades WHERE trades.action = @tag0"") List fetchByActionNamedQuery(@Param(""tag0"") String action); } ---- Table names can be used directly. For example, ""trades"" in the above example. Alternatively, table names can be resolved from the `@Table` annotation on domain classes as well. In this case, the query should refer to table names with fully qualified class names between `:` characters: `:fully.qualified.ClassName:`. A full example would look like: [source, java] ---- @Query(""SELECT * FROM :com.example.Trade: WHERE trades.action = @tag0"") List fetchByActionNamedQuery(String action); ---- This allows table names evaluated with SpEL to be used in custom queries. SpEL can also be used to provide SQL parameters: [source, java] ---- @Query(""SELECT * FROM :com.example.Trade: WHERE trades.action = @tag0 AND price > #{#priceRadius * -1} AND price < #{#priceRadius * 2}"") List fetchByActionNamedQuery(String action, Double priceRadius); ---- When using the `IN` SQL clause, remember to use `IN UNNEST(@iterableParam)` to specify a single `Iterable` parameter. You can also use a fixed number of singular parameters such as `IN (@stringParam1, @stringParam2)`. ==== Projections Spring Data Spanner supports {spring-data-commons-ref}/#projections[projections]. You can define projection interfaces based on domain types and add query methods that return them in your repository: [source, java] ---- public interface TradeProjection { String getAction(); @Value(""#{target.symbol + ' ' + target.action}"") String getSymbolAndAction(); } public interface TradeRepository extends SpannerRepository { List findByTraderId(String traderId); List findByAction(String action); @Query(""SELECT action, symbol FROM trades WHERE action = @action"") List findByQuery(String action); } ---- Projections can be provided by name-convention-based query methods as well as by custom SQL queries. If using custom SQL queries, you can further restrict the columns retrieved from Spanner to just those required by the projection to improve performance. Properties of projection types defined using SpEL use the fixed name `target` for the underlying domain object. As a result accessing underlying properties take the form `target.`. ==== Empty result handling in repository methods Java `java.util.Optional` can be used to indicate the potential absence of a return value. Alternatively, query methods can return the result without a wrapper. In that case the absence of a query result is indicated by returning `null`. Repository methods returning collections are guaranteed never to return `null` but rather the corresponding empty collection. NOTE: You can enable nullability checks. For more details please see https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#null-safety[Spring Framework’s nullability docs]. ==== REST Repositories When running with Spring Boot, repositories can be exposed as REST services by simply adding this dependency to your pom file: [source,xml] ---- org.springframework.boot spring-boot-starter-data-rest ---- If you prefer to configure parameters (such as path), you can use `@RepositoryRestResource` annotation: [source,java] ---- @RepositoryRestResource(collectionResourceRel = ""trades"", path = ""trades"") public interface TradeRepository extends SpannerRepository { } ---- NOTE: For classes that have composite keys (multiple `@PrimaryKey` fields), only the `Key` type is supported for the repository ID type. For example, you can retrieve all `Trade` objects in the repository by using `curl \\http://:/trades`, or any specific trade via `curl \\http://:/trades/,`. The separator between your primary key components, `id` and `trader_id` in this case, is a comma by default, but can be configured to any string not found in your key values by extending the `SpannerKeyIdConverter` class: [source,java] ---- @Component class MySpecialIdConverter extends SpannerKeyIdConverter { @Override protected String getUrlIdSeparator() { return "":""; } } ---- You can also write trades using `curl -XPOST -H""Content-Type: application/json"" -d@test.json \\http://:/trades/` where the file `test.json` holds the JSON representation of a `Trade` object. === Database and Schema Admin Databases and tables inside Spanner instances can be created automatically from `SpannerPersistentEntity` objects: [source,java] ---- @Autowired private SpannerSchemaUtils spannerSchemaUtils; @Autowired private SpannerDatabaseAdminTemplate spannerDatabaseAdminTemplate; public void createTable(SpannerPersistentEntity entity) { if(!spannerDatabaseAdminTemplate.tableExists(entity.tableName()){ // The boolean parameter indicates that the database will be created if it does not exist. spannerDatabaseAdminTemplate.executeDdlStrings(Arrays.asList( spannerSchemaUtils.getCreateTableDDLString(entity.getType())), true); } } ---- Schemas can be generated for entire object hierarchies with interleaved relationships and composite keys. === Events Spring Data Cloud Spanner publishes events extending the Spring Framework's `ApplicationEvent` to the context that can be received by `ApplicationListener` beans you register. [options=""header""] |=== | Type| Description | Contents | `AfterReadEvent`|Published immediately after entities are read by key from Cloud Spanner by `SpannerTemplate`| The entities loaded. The read options and key-set originally specified for the load operation. | `AfterQueryEvent`|Published immediately after entities are read by query from Cloud Spanner by `SpannerTemplate`| The entities loaded. The query options and query statement originally specified for the load operation. | `BeforeExecuteDmlEvent`|Published immediately before DML statements are executed by `SpannerTemplate`| The DML statement to execute. | `AfterExecuteDmlEvent`|Published immediately after DML statements are executed by `SpannerTemplate`| The DML statement to execute and the number of rows affected by the operation as reported by Cloud Spanner. | `BeforeSaveEvent`|Published immediately before upsert/update/insert operations are executed by `SpannerTemplate`| The mutations to be sent to Cloud Spanner, the entities to be saved, and optionally the properties in those entities to save. | `AfterSaveEvent`|Published immediately after upsert/update/insert operations are executed by `SpannerTemplate`| The mutations sent to Cloud Spanner, the entities to be saved, and optionally the properties in those entities to save. | `BeforeDeleteEvent`|Published immediately before delete operations are executed by `SpannerTemplate`| The mutations to be sent to Cloud Spanner. The target entities, keys, or entity type originally specified for the delete operation. | `AfterDeleteEvent`|Published immediately after delete operations are executed by `SpannerTemplate`| The mutations sent to Cloud Spanner. The target entities, keys, or entity type originally specified for the delete operation. |=== === Auditing Spring Data Cloud Spanner supports the `@LastModifiedDate` and `@LastModifiedBy` auditing annotations for properties: [source,java] ---- @Table public class SimpleEntity { @PrimaryKey String id; @LastModifiedBy String lastUser; @LastModifiedDate DateTime lastTouched; } ---- Upon insert, update, or save, these properties will be set automatically by the framework before mutations are generated and saved to Cloud Spanner. To take advantage of these features, add the `@EnableSpannerAuditing` annotation to your configuration class and provide a bean for an `AuditorAware` implementation where the type `A` is the desired property type annotated by `@LastModifiedBy`: [source,java] ---- @Configuration @EnableSpannerAuditing public class Config { @Bean public AuditorAware auditorProvider() { return () -> Optional.of(""YOUR_USERNAME_HERE""); } } ---- The `AuditorAware` interface contains a single method that supplies the value for fields annotated by `@LastModifiedBy` and can be of any type. One alternative is to use Spring Security's `User` type: [source,java] ---- class SpringSecurityAuditorAware implements AuditorAware { public Optional getCurrentAuditor() { return Optional.ofNullable(SecurityContextHolder.getContext()) .map(SecurityContext::getAuthentication) .filter(Authentication::isAuthenticated) .map(Authentication::getPrincipal) .map(User.class::cast); } } ---- You can also set a custom provider for properties annotated `@LastModifiedDate` by providing a bean for `DateTimeProvider` and providing the bean name to `@EnableSpannerAuditing(dateTimeProviderRef = ""customDateTimeProviderBean"")`. === Multi-Instance Usage Your application can be configured to use multiple Cloud Spanner instances or databases by providing a custom bean for `DatabaseIdProvider`. The default bean uses the instance ID, database name, and project ID options you configured in `application.properties`. [source,java] ---- @Bean public DatabaseIdProvider databaseIdProvider() { // return custom connection options provider } ---- The `DatabaseId` given by this provider is used as the target database name and instance of each operation Spring Data Cloud Spanner executes. By providing a custom implementation of this bean (for example, supplying a thread-local `DatabaseId`), you can direct your application to use multiple instances or databases. Database administrative operations, such as creating tables using `SpannerDatabaseAdminTemplate`, will also utilize the provided `DatabaseId`. If you would like to configure every aspect of each connection (such as pool size and retry settings), you can supply a bean for `Supplier`. === Cloud Spanner Emulator The https://cloud.google.com/sdk[Cloud SDK] provides a local, in-memory emulator for Cloud Spanner, which you can use to develop and test your application. As the emulator stores data only in memory, it will not persist data across runs. It is intended to help you use Cloud Spanner for local development and testing, not for production deployments. In order to set up and start the emulator, you can follow https://cloud.google.com/spanner/docs/emulator[these steps]. This command can be used to create Cloud Spanner instances: ---- $ gcloud spanner instances create --config=emulator-config --description="""" --nodes=1 ---- Once the Spanner emulator is running, ensure that the following properties are set in your `application.properties` of your Spring application: ---- spring.cloud.gcp.spanner.emulator.enabled=true spring.cloud.gcp.spanner.emulator-host=${EMULATOR_HOSTPORT} ---- === Sample A https://github.com/spring-cloud/spring-cloud-gcp/tree/master/spring-cloud-gcp-samples/spring-cloud-gcp-data-spanner-sample[sample application] is available. ",12213,False,2028.7241564577125,median "= Setting up idealo :lang: en include::{includedir}/_header.adoc[] :keywords: idealo, idealo, idealo.de, idealo.de, idealo Direktkauf, idealo Checkout, checkoutApproved :description: Multi-Channel in plentymarkets: Set up the interface to the market idealo Checkout in your plentymarkets system. :position: 10 :url: markets/idealo-checkout/idealo-setup :id: JFWN4QY :author: team-multi-channel On this page, you will find information about the settings you need to carry out in order to set up the market and price comparison portal idealo Checkout in plentymarkets. Learn how to set up the interface, how to export items to idealo Checkout and how to define sales prices. [#2300] == About idealo idealo started business in 2000 with the vision of helping users to make the right choices when buying products online and, now counting 50,000 sellers and 18 million users per month, has become one of Germany's most important e-commerce websites. With idealo Checkout, idealo offers a strong sales channel. The ""Zum Kauf"" (Buy now) button allows users to order a product directly on idealo.de, using a fully integrated checkout function. The sellers remain the contractual partners and take care of fulfilment as usual. With plentymarkets, you can both use the idealo price comparison and idealo Checkout. idealo Checkout enables your customers to buy items directly on the idealo website without having to enter your plentyShop. [#100] == Registering with idealo In order to set up idealo in your plentymarkets system, you have to register as an idealo seller first. [#3000] == Select a method for item data export Inform idealo about how item data should be transferred before setting up idealo in plentymarkets (creating, updating, and deleting items on idealo). You can either transfer item data to idealo with the automatic item export via an API (PWS 2.0 interface) or with a CSV file using the elastic export. <<#item-export-idealo-1>> shows the most important differences between these two methods of exporting item data. How to set up the different methods of data transfer in plentymarkets is described in the chapter <<#800, Setting up the item export>>. [[item-export-idealo-1]] .idealo data transfer [cols=""1,1""] |==== | Item data export via API (PWS 2.0) | Item data export via elastic export //tag::table-comparison[] |Item data export via interface |Item data export via CSV file | Unlimited number of items can be transferred | To transfer more than 9999 items to idealo, the option *Generate cache file* must be activated in the Elastic Export settings. If the option *Generate cache file* is activated, the output file will only be generated every 24 hours. This is to save resources. + *_Note:_* We recommend that you do not activate the option *Generate cache file* for more than 20 export formats. This is to ensure a high performance of the elastic export. |Items are created once a day |Retrieval of item data via URL that is saved at idealo |Price updates every 15 minutes |Time interval for retrieval of item data is defined by idealo |Stock updates every 15 minutes |Time interval for retrieval of item data is defined by idealo |Orders are imported to the selected client |Orders are always imported to the default client //end::table-comparison[] |==== [#2400] == Installing the necessary plugins To use idealo in plentymarkets, you need the following plugins: * idealo * Elastic Export + *_Note:_* You also need the Elastic Export plugin if you export your item data to idealo via the interface PWS 2.0. :plugin: idealo include::../_textblocks/instructions/plugin-installation.adoc[] :plugin: Elastic Export include::../_textblocks/instructions/plugin-installation.adoc[] [#200] == Completing the idealo assistant Use the assistant *Base settings - idealo* in the *Setup » Assistants » Plugins » [Open client]* menu to quickly and conveniently set up idealo in plentymarkets. Moreover, you set up the data transfer to OTTO Market. Keep the API access data at hand that you received from idealo. :menu-path: pass:quotes[*Setup » Assistants » Plugins » [Open client]*] :assistant-name: idealo Basic settings :number-of-boxes: info boxes include::../_textblocks/instructions/assistant-basic-instructions.adoc[] [.collapseBox] .Step *Basic settings* -- [[table-idealo-basic-settings]] [width=""100%""] [cols=""1,2a""] |====== |Setting |Explanation | *Enter the shop ID of the idealo shop that you would like to set up the user account for.* | Enter the shop ID of your idealo store. Go to the idealo Business Portal to find the shop ID. | *Select the platform that your idealo shop is set up for.* |Select the platform from the drop-down list. | *Select the client that should be used to export your items to idealo and to import your orders into plentymarkets.* a| From the drop-down list *Client*, select a client. |====== -- [.collapseBox] .Step *Automatic data transfer* -- [[table-idealo-data-export]] [width=""100%""] [cols=""1,2a""] |====== |Setting |Explanation | *Would you like to export your items to idealo via interface (Partner Web Service 2.0)?* |Items can be exported to idealo via interface or via CSV file with the elastic export. Check with idealo how item data should be transferred before the setup in plentymarkets. Via interface, prices and stock will be transferred every fifteen minutes. The interval of data transfer with CSV export is defined by idealo. | *Would you like to export your stock and prices?* | *Export stock and prices* activated = Prices and stock are updated every 15 minutes. | *Would you like to import your idealo Checkout orders into plentymarkets?* |Activate to import orders every 15 minutes automatically. + *_Note:_* You need to activate this option to export item data and stock information. | *What order status do you want to assign to idealo Checkout orders cancelled before the import?* | Some idealo Checkout orders are cancelled before they are first imported to your plentymarkets system. Select the order status that is to be assigned to such cancelled orders during the import. + *_Note:_* The import of these cancelled idealo Checkout orders triggers the event procedures set up for the selected status. As such, select a status that does not trigger any event procedures (such as cancellation confirmations being sent to customers). | *Do you want to continue processing open MOA 1.0 orders with this account?* | The idealo Merchant Order API is a REST API for retrieving and processing idealo Checkout orders. In January 2021, idealo updated this REST API from version 1.0 to version 2.0. Activate this setting if you used this account to import orders with the old MOA 1.0 interface. Any open orders will then be processed automatically as usual. Ignore this setting if you are setting up a new idealo account. | [#intable-status-cancellation-by-buyer]*What status should an order change to when customers request a cancellation?* | Customers might only request a cancellation after an idealo Checkout order is already imported into your plentymarkets system. Such cancellation requests are imported into plentymarkets every 15 minutes. Select an order status that is assigned to these orders. A separate status allows you to view and process these orders individually. + *_Tip:_* Set up the event procedure <<#1803, Accept cancellation by buyer>> to process cancellation requests automatically. | *Up to which status should requests for order cancellations by customers be considered?* | Which orders cancelled by customers should be moved to the order status that you selected above? Set a limit for accepting cancellation requests. + → Orders with this or a lower status are moved to the status you selected for *What status should an order change to when customers request a cancellation?* if customers request a cancellation. + → Orders with a higher order status remain in their original status, i.e. are not moved into the status for orders cancelled by customers. |====== -- [.collapseBox] .Step *Access data* -- [[table-idealo-credentials]] [width=""100%""] [cols=""1,2a""] |====== |Setting |Explanation | *Enter the access data of your Merchant Order API 2.0 API client.* a| The API client access data is required to allow plentymarkets access to your idealo account so that the data exchange can be activated. For the API key, enter the token for the Merchant Order API v2. Go to the idealo Business Portal and generate the API key. | *Enter the access data of your Partner Web Service 2.0 API client.* a| You need the API client access data so that plentymarkets can connect to your idealo account. This activates the exchange of item data. Generate the access data in the idealo Business Portal. |====== -- [.collapseBox] .Step *Item data* -- [[table-idealo-item-data]] [width=""100%""] [cols=""1,2a""] |====== |Setting |Explanation | *Select the item name that should be transferred to idealo.* | Select *Name 1*, *Name 2* or *Name 3* from the drop-down list. This item name is transferred. + *_Tip:_* Item names are entered in the <> tab of the item. | *Select the item description that should be transferred to idealo.* | Select *Item description*, *Preview text*, *Technical data* or *Item description and technical data* from the drop-down list. This item description is transferred to idealo. | *Select the URL that should be transferred to idealo.* | The URL is required so that customers can be redirected from the price search engine to your plentyShop. Variation URLs can only be transferred if you use plentyShop LTS. Item URL Variation URL | *Which price would you like to transfer to idealo as minimum price?* a| If you use the price range feature for idealo checkout sellers, you can specify a minimum price in addition to the regular sales price. Select the sales price form the drop-down list that you want to export as the minimum price. Visit the link:https://partner.idealo.com/de/magazin/repricing-bei-idealo-umsatzanstieg-durch-preisanpassung[idealo^]{nbsp}icon:external-link[] website to find out more about the price range feature. + *_Tip:_* You can only select sales prices from the drop-down list for which <<#600, the referrer idealo has been activated>>. * *Do not use minimum price* = The price range feature is deactivated. |====== -- [.collapseBox] .Step *Attributes* -- [[table-idealo-attributes]] [width=""100%""] [cols=""1,1a""] |====== |Setting |Explanation | *Select the attributes that you have created in plentymarkets to specify colours for your items.* | Activate the attributes that you use to create variations based on colour. | *Select the attributes that you have created in plentymarkets to specify sizes for your items.* | Activate the attributes that you use to create variations based on size. | *What plentymarkets property do you use for the idealo energy efficiency attribute ""Energy efficiency class""?* + (plugin versions 3.3.5 and higher) | This property is used to export the energy efficiency class of products that need to be labelled. *_Allowed values:_* * New energy efficiency scale (from 1st of March 2021): + ** `A`, `B`, `C`, `D`, `E`, `F`, `G` + *_Example:_* `C` * Old energy efficiency scale (up to 28th of February 2021): + ** `A+++`, `A++`, `A+`, `A`, `B`, `C`, `D`, `E`, `F`, `G` + *_Example:_* `A+++` *_Note:_* You specify the energy efficiency scale used with the idealo attribute *Version*. [cols=""1,3""] !=== ! *Create new property* ! Creates a property of the type *Character string* and links this property with the idealo attribute. When you link this property to a variation and save a value, this value is exported to idealo. + *_Tip:_* The property is saved in the property group *idealo*. ! *Link existing property* ! Select a property from the drop-down list. You can link a property of the types *Character string* or *Selection*. When you link this property to a variation and save a value, this value is exported to idealo. !=== *_Tip:_* Learn how to link properties to variations in the <> chapter. | *What plentymarkets property do you use for the idealo energy efficiency attribute ""Spectrum""?* + (plugin versions 3.3.5 and higher) | This property is used to export the spectrum of available energy efficiency classes of products that need to be labelled. Use a minus sign to specify a range. + *_Allowed values:_* * New energy efficiency scale (from 1st of March 2021): + ** `A`, `B`, `C`, `D`, `E`, `F`, `G` + *_Example:_* `A-G` * Old energy efficiency scale (up to 28th of February 2021): + ** `A+++`, `A++`, `A+`, `A`, `B`, `C`, `D`, `E`, `F`, `G` + *_Example:_* `A+++-G` *_Background:_* The spectrum depends on the device type. For example, a spectrum of A to D is used for household washing machines. However, for household refrigerating appliances, the spectrum range is A to G. [cols=""1,3""] !=== ! *Create new property* ! Creates a property of the type *Character string* and links this property with the idealo attribute. When you link this property to a variation and save a value, this value is exported to idealo. + *_Tip:_* The property is saved in the property group *idealo*. ! *Link existing property* ! Select a property from the drop-down list. You can link a property of the types *Character string* or *Selection*. When you link this property to a variation and save a value, this value is exported to idealo. !=== *_Tip:_* Learn how to link properties to variations in the <> chapter. | *What plentymarkets property do you use for the idealo energy efficiency attribute ""Link to label""?* + (plugin versions 3.3.5 and higher) | This property is used to export links to image files that contain the energy efficiency labels of products that need to be labelled. + *_Example:_* `http://www.link.to/label.jpg` + *_Important:_* Make sure that the image’s resolution is high enough to allow customers to scan the label’s QR code. [cols=""1,3""] !=== ! *Create new property* ! Creates a property of the type *File* and links this property with the idealo attribute. When you link this property to a variation and save a value, this value is exported to idealo. + *_Tip:_* The property is saved in the property group *idealo*. ! *Link existing property* ! From the drop-down list, select a property of the type *File*. When you link this property to a variation and save a value, this value is exported to idealo. !=== *_Tip:_* Learn how to link properties to variations in the <> chapter. | *What plentymarkets property do you use for the idealo energy efficiency attribute ""Link to data sheet""?* + (plugin versions 3.3.5 and higher) | This property is used to export links to PDF files that contain the EEK data sheets of products that need to be labelled. + *_Example:_* `http://www.example.com/datasheet.pdf` [cols=""1,3""] !=== ! *Create new property* ! Creates a property of the type *File* and links this property with the idealo attribute. When you link this property to a variation and save a value, this value is exported to idealo. + *_Tip:_* The property is saved in the property group *idealo*. ! *Link existing property* ! From the drop-down list, select a property of the type *File*. When you link this property to a variation and save a value, this value is exported to idealo. !=== *_Tip:_* Learn how to link properties to variations in the <> chapter. | *What plentymarkets property do you use for the idealo energy efficiency attribute ""Version""?* + (plugin versions 3.3.5 and higher) | This property is used to specify if the data that you export with the other idealo attributes is based on the old or the new energy efficiency scale. *_Allowed values:_* * `0` = Old energy efficiency scale (up to 28th of February 2021) * `1` = New energy efficiency scale (from 1st of March 2021) [cols=""1,3""] !=== ! *Create new property* ! Creates a property of the type *Whole number* and links this property with the idealo attribute. When you link this property to a variation and save a value, this value is exported to idealo. + *_Tip:_* The property is saved in the property group *idealo*. ! *Link existing property* ! Select a property from the drop-down list. You can link a property of the types *Character string*, *Whole number*, *Decimal number*, or *Selection*. When you link this property to a variation and save a value, this value is exported to idealo. !=== *_Tip:_* Learn how to link properties to variations in the <> chapter. |====== -- [.collapseBox] .Step *Payment methods* -- [[table-idealo-payment-methods]] [width=""100%""] [cols=""1,2a""] |====== |Setting |Explanation | *idealo payment methods* | Activate the payment methods that you want to offer for idealo orders. |====== -- [.collapseBox] .Step *Shipping methods* -- [[table-idealo-shipping]] [width=""100%""] [cols=""1,2a""] |====== |Setting |Explanation | *Link plentymarkets shipping service provider DHL with:* | For each of your shipping profiles, select an idealo shipping method from the drop-down list. + *_Tip:_* If no shipping profiles are displayed, then you have not set up any shipping profiles for the referrer idealo and the target shipping country in plentymarkets yet. You can create shipping profiles with the assistant *Shipping settings*. |====== -- [.collapseBox] .Step *Activate user account* -- [[table-idealo-account-activation]] [width=""100%""] [cols=""1,2a""] |====== |Setting |Explanation | *Would you like to activate your idealo user account now?* a| _Not activated_ = The settings are saved but the data exchange with idealo is not started. + _Activated_ = Data exchange with idealo is started once the assistant is completed. + *_Recommendation:_* Only activate the user account after you have checked all settings and are ready to start the data exchange with idealo. | *Would you like to copy existing SKUs from the old idealo interface to your new user account?* | Activate the option *Copy existing SKUs* if you already sell on idealo. This prevents duplicate items on idealo. + *_Note:_* Do not activate this option if you have just started selling on idealo. In this case, SKUs are newly generated based on variation IDs. |====== -- [#300] == Using idealo price comparison and idealo Checkout Depending on whether you only want to use the idealo price comparison or whether you want to enable your customers to buy items directly at idealo without having to enter your plentyShop, different settings must be carried out. The overview below lists the settings required for idealo Checkout. *Settings for idealo Checkout:* - *Basic settings:* Go through the assistant *Base settings - idealo* in the *Setup » Assistants » Plugins » [Open client]* menu. - *Item export:* Set up the <<#850, automatic item export>> or the <<#900, item data export via CSV file>>, depending on how you want to export your items to idealo. - *Order referrer:* In addition to the order referrer *idealo*, also activate the <<#400, order referrer>> *idealo Checkout* in the *Setup » Orders » Order referrer* menu. - *Variation availability:* In addition to the order referrer *idealo*, also activate the <<#500, order referrer>> *idealo Checkout* in the *Markets* area of the *Item » Edit item » [Open item] » [Open variation] » Tab: Availability* menu. - *Sales price:* Set up a <<#600, sales price>>. - *SKU:* Add <<#700, SKUs>> if needed. - *Characteristics:* Create <<#1200, characteristics>> for idealo Checkout. Item characteristics, shipping methods and fees are transferred to idealo Checkout with characteristics. - *Event procedures:* Set up <<#1600, event procedures>> to automatically inform idealo about changes in the order status. [#400] == Activating the order referrer :referrer: the idealo price comparison :referrer: idealo price comparison :referrer-option: pass:quotes[option *idealo*] :idealo-direkt: include::../_textblocks/instructions/activate-referrer.adoc[] [#500] == Setting the variation availability :market-availability: idealo :option-availability: idealo :web-api: :idealo-direkt: include::../_textblocks/instructions/variation-availability.adoc[] // Web API required! [#600] == Defining a sales price Proceed as described below to define a sales price for the order referrer idealo. This price is displayed on idealo. It is valid for the idealo price comparison and idealo Checkout. :referrer-price: idealo include::../_textblocks/instructions/define-sales-price.adoc[] [TIP] .Minimum price ==== If you want to use a minimum price for the ""price range"" feature for idealo, then you have to define at least two sales prices for idealo: a minimum price and a standard sales price. The minimum price must have the price type *Special offer* and must be linked to the referrer *idealo Checkout*. + Which price should be transferred to idealo as minimum price is defined with the setting *Which price would you like to transfer to idealo as minimum price?* in the *Item data* step of the idealo assistant. + The ""price range"" feature must also be activated at idealo. ==== [#700] == _Optional:_ Saving SKU :referrer-sku: idealo :referrer-id: 121 :sku-others: include::../_textblocks/instructions/sku-manually.adoc[] // Marketplace account not required! If you want to use idealo Checkout, also add SKUs with the referrer *idealo Checkout*. [#800] == Setting up the item export Items can be transferred to idealo with the automatic item data export via API (PWS 2.0 interface) or via a CSV file with the elastic export. Depending on how you want to transfer your items to idealo, different settings are required. [IMPORTANT] .Data transfer to idealo ==== Check with idealo how item data should be transferred before the setup in plentymarkets. ==== Information about the different types of data transfer is available in <<#item-export-idealo>>. [[item-export-idealo]] .idealo data transfer [cols=""1,1""] |==== | Item data export via API (PWS 2.0) | Item data export via elastic export include::idealo-setup.adoc[tag=table-comparison] |==== [#850] === Item data export via API (PWS 2.0) If you want to transfer your items to idealo via API, go through the *idealo Basic settings* assistant in the *Setup » Assistants » Plugins » [Open client]* menu and activate the automatic item data export. Apart from the assistant, no further settings are required to set up the automatic item export in plentymarkets. + If you transfer your items via API, items will be created at idealo once per day. Prices and stock are updated every 15 minutes. Items can also be deleted every 15 minutes. [#900] === Item data export via elastic export If you export items via the elastic export, you have to carry out a few settings in the *Data » Elastic export* menu to set up the export format. In order to use the elastic export, the link:https://marketplace.plentymarkets.com/en/plugins/sales/marktplaetze/elasticexport_4763[Elastic Export^]{nbsp}icon:external-link[] plugin must be installed in your plentymarkets system. First create the data format IdealoDE and afterwards transfer the URL to idealo so that idealo will be able to retrieve your item data. How to set up the elastic export to export your items to idealo is described in the following chapters <<#950, Setting up the data format IdealoDE plugin in plentymarkets>> and <<#1000, Available columns for the export file>>. [#950] ==== Setting up the data format idealo-Plugin in plentymarkets [TIP] .Settings only for elastic export ==== The settings described in this chapter only need to be carried out if you transfer your items to idealo with the elastic export. ==== [TIP] .Check idealo product CSV ==== Not all of the columns of idealo’s product CSV are available in plentymarkets at present. Check whether you need columns which are not yet available in plentymarkets prior to setting up idealo in plentymarkets. In this case, an integration of idealo is currently not possible. + An overview of the columns which are available in plentymarkets can be found in the <<#1000, Available columns for the export file>> chapter. ==== Set up the export format *IdealoDE* so that your items can be exported to idealo with the elastic export. For further information about the elastic export, refer to the <> page. It is required to install the *Elastic export* plugin from the plentyMarketplace first before you can use the format *IdealoDE* for the elastic export. [.instruction] Creating a new export format: . Go to *Data » Elastic export*. . Click on *New export*. . Carry out the desired settings. Pay attention to the explanations given in <<#format-settings-idealo>>. . Save (icon:save[set=plenty]) the settings. + → The export format *IdealoDE-Plugin* is given an ID and it appears in the overview within the *Exports* tab. The following table lists details for settings, format settings and recommended item filters for the format *IdealoDE plugin*. [[format-settings-idealo]] .Format settings for IdealoDE [cols=""1,3a""] |==== | Setting | Explanation 2+| *Settings* | *Name* |Enter a name. The export format is listed by this name in the overview within the *Exports* tab. | *Type* |Select the type *item* from the drop-down list. | *Format* | Select *IdealoDE-Plugin*. | *Limit* | Enter a number. This number determines how many items are exported at maximum. *_Note:_* Do you want to transmit more than 9999 items to idealo? * Then the output file will only be generated every 24 hours. This is to save resources. * Then also select the option *Generate cache file* further below. *_Tip:_* If you want to transfer more than 9999 items to idealo, you can also install version 2.0 of the idealo plugin. | *Generate cache file* | Activate if you want to transfer more than 9999 items to idealo. If the option is activated, the output file will only be generated every 24 hours. This is to save resources. + *_Note:_* We recommend that you do not activate this option for more than 20 export formats. This is to ensure a high performance of the elastic export. | *Provisioning* | Select *URL*. | *File name* |The file name must have the ending *.csv* or *.txt* for idealo.de to be able to import the file successfully. | *Token, URL* |If you selected the option *URL* under *Provisioning*, click on *Generate token*. The token is entered automatically. The URL is entered automatically if the token was generated under *Token*. 2+| *Item filters* | *Add item filters* a|Select an item filter from the drop-down list and click on *Add*. There are no filters set by default. It is possible to add multiple item filters from the drop-down list one after the other. + * *Variations* = *Transfer all* or *Only transfer main variations*. + * *Markets* = Select *idealo*. + * *Currency* = Select a currency. + * *Category* = Activate to transfer the item with its category link. Only items belonging to this category will be transmitted. + * *Image* = Activate to transfer the item with its image. Only items with images will be exported. + * *Client* = Select a client. + * *Stock* = Select which stocks you want to export. + * *Flag 1 - 2* = Select a flag. + * *Manufacturer* = Select one, several or *ALL* manufacturers. + * *Active* = Only active variations will be exported. 2+| *Format settings* | *Product URL* |Select the URL that you wish to transfer to the price search engine. You can either send the item’s URL or the variation’s URL. URLs of variations can only be transferred in combination with plentyShop LTS. | *Client* |Select a client. This setting is used for the URL structure. | *URL parameter* |Enter a suffix for the product URL if this is required for the export. If you activated the *transfer* option for the product URL further up, then this character string is added to the product URL. | *Order referrer* |Select the referrer *idealo*. The selected referrer is added to the product URL so that sales can be analysed later. | *Marketplace account* |Select the marketplace account from the drop-down list. | *Language* |Select the language from the drop-down list. | *Item name* | Select *Name 1*, *Name 2* or *Name 3*. The names are saved in the *Texts* tab of the item. Enter a number into the *Maximum number of characters (def. text)* field if desired. This specifies how many characters are exported for the item name. | *Preview text* |Select the text that you want to transfer as preview text. + Enter a number into the *Maximum number of characters (def. text)* field if desired. This specifies how many characters are exported for the preview text. + Activate the *Remove HTML tags* option if you want HTML tags to be removed during the export. + If you only want to allow specific HTML tags to be exported, then enter these tags into the * Permitted HTML tags, separated by comma (def. text)* field. Use commas to separate multiple tags. | *Description* |Select the text that you want to transfer as description. + Enter a number into the *Maximum number of characters (def. text)* field if desired. This specifies how many characters are exported for the description. + Activate the *Remove HTML tags* option if you want HTML tags to be removed during the export. + If you only want to allow specific HTML tags to be exported, then enter these tags into the * Permitted HTML tags, separated by comma (def. text)* field. Use commas to separate multiple tags. | *Target country* |Select the target country from the drop-down list. | *Barcode* |Select the ASIN, ISBN or an EAN from the drop-down list. The barcode has to be linked to the order referrer selected above. Otherwise, the barcode will not be exported. | *Image* a| Select *Position 0* or *First image* to export this image. + * *Position 0* = An image with position 0 is transferred. + * *First image* = The first image is transferred. | *Image position of the energy label* |Enter the position of the energy label. Every image that should be transferred as an energy label has to have this position. | *Stock buffer* |The stock buffer for variations with limitation to the net stock. | *Stock for variations without stock limitation* |The stock for variations without stock limitation. | *Stock for variations with no stock administration* |The stock for variations without stock administration. | *Live currency conversion* |Activate this option to convert the price into the currency of the selected country of delivery. The price has to be released for the corresponding currency. | *Sales price* |Select gross price or net price from the drop-down list. | *Offer price* |This option does not affect this format. | *RRP* |Activate to transfer the RRP. | *Shipping costs* |The chosen payment method does not affect this format. All payment methods of the selected configuration will be exported. + If no configuration has been selected, all configurations and payment methods will be exported. + If *Transfer flat rate shipping charge* has been selected, only prepayment will be exported as the payment method. | *VATNote* |This option does not affect this format. | *Item availability* |Activate the *overwrite* option and enter item availabilities into the fields *1* to *10*. The fields represent the IDs of the availabilities. This overwrites the item availabilities that are saved in the *Setup » Item » Availability* menu. |==== [#1000] ==== Available columns for the export file [[columns-export-file]] .Columns for the export file [cols=""1,3a""] |==== | Column header | Explanation | *article_id* | *Required* + The SKU of the item. For all items which are configured for idealo Checkout, a SKU will be generated for idealo Checkout. | *deeplink* | *Required* + The URL path of the item depending on the chosen client in the format settings. | *name* | *Required* + According to the format setting *Item name*. | *short_description* |According to the format setting *Preview text*. | *description* | *Limitation:* max. 1000 characters + According to the format setting *Description*. | *article_no* |The variation number as per *Item » Edit item » [Open item] » [Open variation] » Settings » Basic settings*. | *producer* |The name of the manufacturer of the item. The external name saved in the *Setup » Item » Manufacturers* menu is preferred if existing. | *model* |The model as per *Item » Edit item » [Open item] » [Open variation] » Settings » Basic settings*. | *availability* | *Required* + The name of the item availability saved in the *Setup » Item » Availability* menu or the translation according to the format setting *Overwrite item availability*. + For idealo, the delivery time must be indicated in days. | *ean* |According to the format setting *Barcode*. | *isbn* |According to the format setting *Barcode*. | *fedas* |The Amazon product type as per *Items » Edit item » [Open item] » Multi-Channel » Amazon*. | *warranty* |Currently not configured. | *price* | *Required* + The sales price of the variation. | *price_old* |The sales price of type RRP of the variation, if activated in the format settings. | *weight* |The gross weight in gram as per *Items » Edit item » [Open item] » [Open variation] » Settings » Measurements*. | *category1-6* |The name of the category level of the category path of the default category for the client which is configured in the format settings. | *category_concat* |The category path of the default category for the client which is configured in the format settings. | *image_url_preview* |The URL for the image which is scaled for preview according to the format setting *Image*. | *image_url* | *Required* + URL of the image according to the format setting *Image*. | *base_price* |The base price information in the format ""price / unit"". + *_Example:_* 10.00 EUR / kilogram | *free_text_field* |The value of a characteristic of the type *Text* or *Selection* with a link to idealo. | *checkoutApproved* |Is true if the order referrer idealo Checkout is activated in the *Items » Edit item » [Open item] » [Open variation] » Availability » Markets* menu or if a characteristic of the type *No* and the link to the idealo Checkout characteristic CheckoutApproved is configured. | *itemsInStock* | *Requirement*: checkoutApproved is true. + The net stock of the variation. For items which are not limited to the net stock, 999 will be exported. | *fulfillmentType* | *Requirement*: checkoutApproved is true. + Characteristic of type *No* with link to one of the options for the idealo Checkout characteristic *FulfillmentType > Spedition*, *FulfillmentType > Paketdienst*, *FulfillmentType > Brief* or *FulfillmentType > Download*. | *twoManHandlingPrice* | *Requirement*: checkoutApproved is true and fulfillmentType is “Spedition”. + Characteristic of type *Text*, *Selection* or *float* and the link to the idealo Checkout characteristic *twoManHandlingPrice*. | *disposalPrice* | *Requirement*: checkoutApproved is true and fulfillmentType is “Spedition”. + Characteristic of type *Text*, *Selection* or *float* and the link to the idealo Checkout characteristic *disposalPrice*. | *Payment methods* | *Requirement*: at least one payment method + All payment methods will be exported, according to the format setting *Shipping costs* in their own column. |==== [#1100] == Activating the payment method idealo Checkout :market: idealo :payment-method: idealo Checkout include::../_textblocks/instructions/activate-payment-method.adoc[] [IMPORTANT] .PayPal payment method ==== If you offer the payment method <>, it is mandatory to create and configure this payment method in your plentymarkets system. This is to ensure that the payment is imported and assigned to the order correctly. ==== [#1200] == Creating characteristics Use <> to link specific item details to your items which are required to set up idealo Checkout. Item details, shipping methods and fees are transferred to idealo Checkout with characteristics. [IMPORTANT] .Characteristics can only be used with the idealo plugin version 2.0 ==== The characteristics *DeliveryComment*, *DepositFee*, *DisposalPrice*, *EnergyClass*, *FreeReturnDays*, *Gender*, *Material*, and *Replica* can only be used if the idealo plugin version 2.0 is installed in your plentymarkets system. These characteristics can only be exported to idealo Checkout if you activate the automatic item export (data export via interface). The automatic item export is activated in the *Automatic data transfer* step of the idealo assistant. + If the automatic item export is activated, you can export all idealo characteristics. + If you transfer your items with via CSV file with the elastic export, you can only use the characteristic *FulfillmentType*. ==== [#1250] === Creating the characteristics material and gender Use the characteristics Material and Gender to transfer information about material and target group or gender to idealo Checkout. Proceed as described below to create the characteristic *Material*. Create the *Gender* characteristic in the same way, but select the characteristic type *Text* instead. [.instruction] Creating a characteristic for material: . Go to *Setup » Item » Characteristics » Tab: New characteristic*. . Enter the *Name (internal)*. . Select the characteristic type *No* from the characteristic type drop-down list. . Select the characteristic *Material* for *idealo Checkout characteristic*. . Save (icon:save[set=plenty]) the settings. Next, you have to link the characteristic to the item in the *Item » Edit item » [Open item] » [Open variation] » Variation tab: Characteristics* menu. [#1300] === Creating characteristics for shipping methods With idealo Checkout, the customer buys the items directly at idealo and you have to send shipping information to idealo Checkout. If you ship your items with a parcel service, a shipping company, via letter or via download, this mandatory information is transferred to idealo with a characteristic. If the order is carried out by a shipping company, the customer has to enter their phone number during the order process in order to arrange a delivery date. Proceed as described below to create the characteristic *FulfillmentType*. This characteristic indicates whether you use the shipping method *shipping company*, *parcel service*, *letter*, or *download*. [.instruction] Creating a characteristic for the shipping method: . Go to *Setup » Item » Characteristics » Tab: New characteristic*. . Enter the *Name (internal)*. . Select the characteristic type *No* from the characteristic type drop-down list. . Select the characteristic *FulfillmentType* for *idealo Checkout characteristic*. + → A drop-down list is shown. . Select a value from the drop-down list, depending on the shipping type. The values *Spedition* (shipping company), *Paketdienst* (parcel service), *Brief* (letter), and *Download* (download) are available. . Save (icon:save[set=plenty]) the settings. Next, you have to link the characteristic to the item in the *Item » Edit item » [Open item] » [Open variation] » Variation tab: Characteristics* menu. [discrete] ===== Further characteristics for shipping methods For items which have the shipping method *shipping company*, it is also possible to transfer the additional services *TwoManHandlingPrice* and *DisposalPrice* to idealo Checkout. Create characteristics to offer those services. In both cases, select *decimal number* as the characteristic type. Go to *Item » Edit item » [Open item] » [Open variation] » Variation tab: Characteristics* and enter the surcharge for the additional service with two decimal places behind the decimal separator. Use a period for the decimal separator (19.99). [#characteristic-weee] === Creating a characteristic for WEEE take back As of 1 January 2022, sellers will be legally obliged to offer collection of old electrical devices if customers buy a new electrical device. In plentymarkets, you can use the characteristic *DisposalPrice* to specify whether WEEE take back is possible for an item. Proceed as described below to create the characteristic *DisposalPrice*. [.instruction] Creating a characteristic for WEEE take back: . Go to *Setup » Item » Characteristics » Tab: New characteristic*. . Enter the *Name (internal)*. . Select the characteristic type *decimal number* from the drop-down list. . Select the characteristic *DisposalPrice* for *idealo Checkout characteristic*. . Save (icon:save[set=plenty]) the settings. Next, you have to link the characteristic to the item in the *Item » Edit item » [Open item] » [Open variation] » Variation tab: Characteristics* menu. [instruction] Linking the characteristic for WEEE take back to an item: . Go to *Item » Edit item*. . Open the item. . Click on the *Characteristics* tab. . Activate the DisposalPrice characteristic that you created. . Save (icon:save[set=plenty]) the settings. + → The characteristic is linked to the item and can be viewed in the *Characteristics* section. . Enter *0.00* as value for WEEE take back. . *Save* (icon:save[set=plenty]) the settings. [#1350] === Creating a characteristic for delivery comments Use the characteristic *DeliveryComment* to transfer further information about the delivery. Proceed as described below to create the characteristic *DeliveryComment*. [.instruction] Creating a characteristic to specify further information about the delivery: . Go to *Setup » Item » Characteristics » Tab: New characteristic*. . Enter the *Name (internal)*. . Select *Text* from the characteristic type drop-down list. . Select the characteristic *DeliveryComment* for *idealo Checkout characteristic*. . Save (icon:save[set=plenty]) the settings. Next, you have to link the characteristic to the item in the *Item » Edit item » [Open item] » [Open variation] » Variation tab: Characteristics* menu. [#1400] === Creating the characteristic energy efficiency class Use the characteristic *EnergyClass* to transfer information about the energy efficiency class to idealo Checkout. + TIP: For plugin versions 3.3.5 and higher, you only need the characteristic for the energy efficiency class if you export your item data using the elastic export. If you use the API (PWS 2.0) for exporting item data, you specify properties for exporting energy efficiency information in the assistant. Proceed as described below to create the characteristic *EnergyClass*. [.instruction] Creating the characteristic energy efficiency class: . Go to *Setup » Item » Characteristics » Tab: New characteristic*. . Enter the *Name (internal)*. . Select the characteristic type *No* from the characteristic type drop-down list. . Select the characteristic *EnergyClass* for *idealo Checkout characteristic*. + → A drop-down list is shown. . Select a value from the drop-down list, depending on the energy efficiency class. . Save (icon:save[set=plenty]) the settings. Next, you have to link the characteristic to the item in the *Item » Edit item » [Open item] » [Open variation] » Variation tab: Characteristics* menu. [#1450] === Creating the characteristic free return Use the characteristic *FreeReturnDays* to transfer information about the free return period to idealo Checkout. Proceed as described below to create the characteristic *FreeReturnDays*. [.instruction] Creating a characteristic for the free return period: . Go to *Setup » Item » Characteristics » Tab: New characteristic*. . Enter the *Name (internal)*. . Select the characteristic type *whole number* from the drop-down list. . Select the characteristic *FreeReturnDays* for *idealo Checkout characteristic*. . Save (icon:save[set=plenty]) the settings. Next, you have to link the characteristic to the item in the *Item » Edit item » [Open item] » [Open variation] » Variation tab: Characteristics* menu. [#1500] === Creating the characteristic deposit fee Use the characteristic *DepositFee* to transfer information about the deposit fee to idealo Checkout. This characteristic is required if a deposit fee must be paid for an item. Proceed as described below to create the characteristic *DepositFee*. [.instruction] Creating the characteristic deposit fee: . Go to *Setup » Item » Characteristics » Tab: New characteristic*. . Enter the *Name (internal)*. . Select the characteristic type *decimal number* from the drop-down list. . Select the characteristic *DepositFee* for *idealo Checkout characteristic*. . Save (icon:save[set=plenty]) the settings. Next, you have to link the characteristic to the item in the *Item » Edit item » [Open item] » [Open variation] » Variation tab: Characteristics* menu. [#1550] === Creating the characteristic replica Use the characteristic *Replica* to specify whether the item is a replica. Proceed as described below to create the characteristic *Replica*. [.instruction] Creating the characteristic replica: . Go to *Setup » Item » Characteristics » Tab: New characteristic*. . Enter the *Name (internal)*. . Select the characteristic type *No* from the characteristic type drop-down list. . Select the characteristic *Replica* for *idealo Checkout characteristic*. . Save (icon:save[set=plenty]) the settings. Next, you have to link the characteristic to the item in the *Item » Edit item » [Open item] » [Open variation] » Variation tab: Characteristics* menu. [#1600] == Creating event procedures for idealo Checkout Do you use idealo Checkout? Then set up event procedures to automatically inform idealo about changes in the order status. You can use event procedures to automatically send shipping confirmations, returns, and cancellations to idealo Checkout. [TIP] .Event procedures for idealo Checkout only ==== You only have to set up event procedures if you use idealo Checkout. ==== [#1700] === Automatically sending shipping confirmations Set up an <> to automatically send a shipping confirmation to idealo when the outgoing items have been booked. :table-event-procedure: <<#shipping-confirmation-idealo>> include::_includes:page$EA.adoc[] [[shipping-confirmation-idealo]] .Event procedure for automatically sending shipping confirmations to idealo [cols=""1,3,3""] |==== |Setting |Option |Selection | *Event* | Select an event, for example *Order change: Outgoing items booked* | | *Filter 1* | *Order > Order type* | *Order* | *Filter 2* | *Order > Referrer* | *idealo Checkout* | *Procedure* | *Plugins > Send shipping confirmation to idealo* | |==== [#1750] === Automatically sending returns Set up an <> to automatically inform idealo about returns. :table-event-procedure: <<#returns-idealo>> include::_includes:page$EA.adoc[] [[returns-idealo]] .Event procedure for automatically notifying idealo of returns [cols=""1,3,3""] |==== |Setting |Option |Selection | *Event* | Select an event, for example *Order generation: New return* | | *Filter 1* | *Order > Order type* | *Return* | *Filter 2* | *Order > Referrer* | *idealo Checkout* | *Procedure* | *Plugins > Send return notification to idealo* | |==== [#1800] === Automatically sending cancellations Set up an <> to automatically inform idealo of cancellations. The following actions are available for cancellations: * Send seller cancellation to idealo * Send buyer cancellation to idealo [#1801] ==== Automatically sending seller cancellations :table-event-procedure: <<#cancellations-seller-idealo>> include::_includes:page$EA.adoc[] [[cancellation-seller-idealo]] .Event procedure for automatically notifying idealo of cancellations by seller [cols=""1,3,3""] |==== |Setting |Option |Selection | *Event* | Select an event, for example *Status change: [8] Cancelled* | | *Filter 1* | *Order > Order type* | *Order* | *Filter 2* | *Order > Referrer* | *idealo Checkout* | *Procedure* | *Plugins > Send seller cancellation to idealo* | |==== [#1802] ==== Automatically sending buyer cancellations :table-event-procedure: <<#cancellations-buyer-idealo>> include::_includes:page$EA.adoc[] [[cancellation-buyer-idealo]] .Event procedure for automatically notifying idealo of cancellations by buyer [cols=""1,3,3""] |==== |Setting |Option |Selection | *Event* | Select an event, for example *Status change: [8.1] Cancelled by customer* | | *Filter 1* | *Order > Order type* | *Order* | *Filter 2* | *Order > Referrer* | *idealo Checkout* | *Procedure* | *Plugins > Send buyer cancellation to idealo* | |==== [#1803] ==== Automatically accepting cancellation by buyer :table-event-procedure: <<#accept-cancellations-buyer-idealo>> include::_includes:page$EA.adoc[] [[accept-cancellations-buyer-idealo]] .Event procedure for automatically accepting cancellations by buyer [cols=""1,3,3""] |==== |Setting |Option |Selection | *Event* | Select an event, for example *Status change*. Select the status that you <> for orders that customers want to cancel. | | *Filter 1* | *Order > Order type* | *Order* | *Filter 2* | *Order > Referrer* | *idealo Checkout* | *Procedure* | *Plugins > Accept cancellation by buyer* | |==== [#1755] === Automatically sending refund notifications Set up an <> to automatically inform idealo of refunds. [IMPORTANT] .Payment method *idealo Checkout Payments* only ==== The event procedure *Send refund notification to idealo* only is triggered for orders that were paid using the payment method *idealo Checkout Payments*. The event procedure cannot be used for orders that were paid for using PayPal. ==== :table-event-procedure: <<#refund-idealo>> include::_includes:page$EA.adoc[] [[refund-idealo]] .Event procedure for automatically notifying idealo of credit notes [cols=""1,3,3""] |==== |Setting |Option |Selection | *Event* | Select an event, for example *Order generation: New credit note*. | | *Filter 1* | *Order > Order type* | *Credit note* | *Filter 2* | *Order > Referrer* | *idealo Checkout* | *Procedure* | *Plugins > Send refund notification to idealo* | |==== [#1900] == Viewing the log :market: idealo include::partial$viewing_logs.adoc[tag=data-log-intro] * *Identifier* » *ElasticExportIdealoDE* include::partial$viewing_logs.adoc[tag=data-log-config] [#2000] == FAQ [#2100] === Item data export via API (PWS 2.0) [.collapseBox] .Not all of my items are exported to idealo. What can I do? -- If you transfer your items to idealo via API (PWS 2.0), but not all of your items have been exported, you can try to update the timestamp for market exports. Updating the timestamp might help because usually, only variations which have been updated within the last two days are exported to idealo. [.instruction] Updating the timestamp for market exports: . Go to *Item » Batch processing*. . In the *Procedures* area, activate the option *Update timestamp for market exports*. . Click on *Apply* (icon:execute[set=plenty]). + → All items which are configured for idealo will be exported to idealo with the next item export. -- ",12410,False,2364.991963888929,median ".//============================================================================ .// $RCSfile: m.component.arc,v $ .// .// Description: .// Component level marking functions are found here. .//============================================================================ .// .// .//============================================================================ .// Mark components as channels using package name and/or component .// name as the selection criteria. .//============================================================================ .function MarkAsChannel .param string package_name .param string component_name .param string inc_file .invoke MarkComponentAsChannel( package_name, component_name, inc_file ) .end function .function MarkComponentAsChannel .param string package_name .param string component_name .param string inc_file .select many c_cs from instances of C_C where ( false ) .if ( ( ( """" == package_name ) and ( """" == component_name ) ) or ( ( ""*"" == package_name ) and ( ""*"" == component_name ) ) ) .// all components .select many c_cs from instances of C_C .elif ( ( """" == package_name ) or ( ""*"" == package_name ) ) .// matches without respect to package .select many c_cs from instances of C_C where ( selected.Name == component_name ) .elif ( ( """" == component_name ) or ( ""*"" == component_name ) ) .// all components in packages with given name .select many ep_pkgs from instances of EP_PKG where ( selected.Name == package_name ) .select many c_cs related by ep_pkgs->PE_PE[R8000]->C_C[R8001] .else .// particular component in particular package(s) .select many ep_pkgs from instances of EP_PKG where ( selected.Name == package_name ) .select many c_cs related by ep_pkgs->PE_PE[R8000]->C_C[R8001] where ( selected.Name == component_name ) .end if .select many te_cs related by c_cs->TE_C[R2054] .if ( empty te_cs ) .print ""WARNING: MarkComponentAsChannel - Could not find component ${package_name}::${component_name}."" .end if .for each te_c in te_cs .select one tm_c related by te_c->TM_C[R2804] .if ( empty tm_c ) .create object instance tm_c of TM_C .assign tm_c.Package = package_name .assign tm_c.Name = component_name .relate te_c to tm_c across R2804 .end if .assign tm_c.isChannel = true .assign tm_c.include_file = inc_file .// Now that we have marked this component as a channel modify the message names .select many te_macts related by te_c->TE_MACT[R2002] .for each te_mact in te_macts .select one te_aba related by te_mact->TE_ABA[R2010] .assign te_mact.GeneratedName = te_mact.MessageName .assign te_mact.GeneratedName = ""$r{te_mact.GeneratedName}"" .assign te_aba.GeneratedName = te_mact.GeneratedName .end for .end for .end function .// .//============================================================================ .// Mark a component that has a C++ template. .//============================================================================ .function MarkComponentWithTemplate .param string package_name .param string component_name .select many c_cs from instances of C_C where ( false ) .if ( ( ( """" == package_name ) and ( """" == component_name ) ) or ( ( ""*"" == package_name ) and ( ""*"" == component_name ) ) ) .// all components .select many c_cs from instances of C_C .elif ( ( """" == package_name ) or ( ""*"" == package_name ) ) .// matches without respect to package .select many c_cs from instances of C_C where ( selected.Name == component_name ) .elif ( ( """" == component_name ) or ( ""*"" == component_name ) ) .// all components in packages with given name .select many ep_pkgs from instances of EP_PKG where ( selected.Name == package_name ) .select many c_cs related by ep_pkgs->PE_PE[R8000]->C_C[R8001] .else .// particular component in particular package(s) .select many ep_pkgs from instances of EP_PKG where ( selected.Name == package_name ) .select many c_cs related by ep_pkgs->PE_PE[R8000]->C_C[R8001] where ( selected.Name == component_name ) .end if .select many te_cs related by c_cs->TE_C[R2054] .if ( empty te_cs ) .print ""WARNING: MarkComponentWithTemplate - Could not find component ${package_name}::${component_name}."" .end if .for each te_c in te_cs .select one tm_c related by te_c->TM_C[R2804] .if ( empty tm_c ) .create object instance tm_c of TM_C .assign tm_c.Package = package_name .assign tm_c.Name = component_name .assign tm_c.isChannel = false .assign tm_c.include_file = """" .end if .if ( not_empty te_c ) .relate te_c to tm_c across R2804 .end if .// Make the new template the current one for follow-on markings. .select many tm_templates from instances of TM_TEMPLATE .for each tm_template in tm_templates .assign tm_template.current = false .end for .create object instance tm_template of TM_TEMPLATE .assign tm_template.current = true .relate tm_template to tm_c across R2800 .end for .end function .// .//============================================================================ .// Mark an interface that has a C++ template. .//============================================================================ .function MarkInterfaceWithTemplate .param string package_name .param string interface_name .select any c_i from instances of C_I where ( false ) .if ( ( """" == package_name ) or ( ""*"" == package_name ) ) .select any c_i from instances of C_I where ( selected.Name == interface_name ) .else .select many ep_pkgs from instances of EP_PKG where ( selected.Name == package_name ) .select any c_i related by ep_pkgs->PE_PE[R8000]->C_I[R8001] where ( selected.Name == interface_name ) .end if .if ( empty c_i ) .print ""WARNING: MarkInterfaceWithTemplate - Could not find interface ${package_name}::${interface_name}."" .end if .create object instance tm_if of TM_IF .assign tm_if.Package = package_name .assign tm_if.Name = interface_name .relate tm_if to c_i across R2807 .// Make the new template the current one for follow-on markings. .select many tm_templates from instances of TM_TEMPLATE .for each tm_template in tm_templates .assign tm_template.current = false .end for .create object instance tm_template of TM_TEMPLATE .assign tm_template.current = true .relate tm_template to tm_if across R2802 .end function .// .//============================================================================ .// Add a template parameter to a C++ template. .// The template is located based upon the associated component. .//============================================================================ .function AddTemplateParameter .param string package_name .param string component_name .param string type_name .param string variable_name .param string default_value .select any tm_template from instances of TM_TEMPLATE where ( selected.current ) .select any tm_c from instances of TM_C where ( ( selected.Package == package_name ) and ( selected.Name == component_name ) ) .if ( ( """" == package_name ) or ( ""*"" == package_name ) ) .select any tm_c from instances of TM_C where ( selected.Name == component_name ) .if ( empty tm_c ) .select one tm_c related by tm_template->TM_C[R2800] .end if .end if .if ( empty tm_c ) .select any tm_if from instances of TM_IF where ( ( selected.Package == package_name ) and ( selected.Name == component_name ) ) .if ( ( """" == package_name ) or ( ""*"" == package_name ) ) .select any tm_if from instances of TM_IF where ( selected.Name == component_name ) .if ( empty tm_if ) .select one tm_if related by tm_template->TM_IF[R2802] .end if .end if .if ( empty tm_if ) .print ""ERROR: AddTemplateParameter - Could not find element (component or interface) ${package_name}::${component_name}."" .else .select one tm_template related by tm_if->TM_TEMPLATE[R2802] .end if .else .select one tm_template related by tm_c->TM_TEMPLATE[R2800] .end if .if ( not_empty tm_template ) .create object instance tm_tp of TM_TP .relate tm_tp to tm_template across R2801 .assign tm_tp.typename = type_name .assign tm_tp.Name = variable_name .assign tm_tp.DefaultValue = default_value .else .print ""ERROR: AddTemplateParameter - Could not find template for element ${package_name}::${component_name}."" .end if .end function .// .//============================================================================ .// Set the template parameter for an instance of a component or interface .// class. The template is navigated based upon the associated package .// and instance. .//============================================================================ .function SetTemplateParameter .param string package_name .param string instance .param string variable_name .param string value .// Base selection upon the template that most recently got created. .select any tm_template from instances of TM_TEMPLATE where ( selected.current ) .select one tm_c related by tm_template->TM_C[R2800] .select one tm_if related by tm_template->TM_IF[R2802] .select any tm_tp related by tm_template->TM_TP[R2801] where ( selected.Name == variable_name ) .if ( ( ( """" == package_name ) or ( """" == instance ) ) or ( ( """" == variable_name ) or ( """" == value ) ) ) .print ""ERROR: SetTemplateParameter - Must provide valid strings for all arguments. ${package_name}::${instance}.${variable_name} to value ${value}."" .else .select any ep_pkg from instances of EP_PKG where ( selected.Name == package_name ) .if ( empty ep_pkg ) .print ""ERROR: SetTemplateParameter - Package, ${package_name}, not found for ${package_name}::${instance}.${variable_name} to value ${value}."" .end if .if ( not_empty tm_tp ) .if ( not_empty tm_c ) .select any te_ci related by ep_pkg->PE_PE[R8000]->CL_IC[R8001]->TE_CI[R2009] where ( selected.ClassifierName == instance ) .if ( empty te_ci ) .select any te_ci related by ep_pkg->PE_PE[R8000]->C_C[R8001]->PE_PE[R8003]->CL_IC[R8001]->TE_CI[R2009] where ( selected.ClassifierName == instance ) .end if .if ( not_empty te_ci ) .create object instance tm_tpv of TM_TPV .assign tm_tpv.instance = instance .assign tm_tpv.value = value .relate tm_tpv to tm_tp across R2808 .relate tm_tpv to te_ci across R2805 .else .print ""ERROR: SetTemplateParameter - no component instance for ${package_name}::${instance} with name ${variable_name}."" .end if .elif ( not_empty tm_if ) .select many te_iirs related by ep_pkg->PE_PE[R8000]->CL_IC[R8001]->CL_POR[R4707]->CL_IIR[R4708]->TE_IIR[R2013] where ( ( selected.port_name == instance ) and ( selected.interface_name == tm_if.Name ) ) .for each te_iir in te_iirs .create object instance tm_tpv of TM_TPV .assign tm_tpv.instance = instance .assign tm_tpv.value = value .relate tm_tpv to tm_tp across R2808 .relate tm_tpv to te_iir across R2806 .end for .select many te_iirs related by ep_pkg->PE_PE[R8000]->C_C[R8001]->PE_PE[R8003]->CL_IC[R8001]->CL_POR[R4707]->CL_IIR[R4708]->TE_IIR[R2013] where ( ( selected.port_name == instance ) and ( selected.interface_name == tm_if.Name ) ) .for each te_iir in te_iirs .create object instance tm_tpv of TM_TPV .assign tm_tpv.instance = instance .assign tm_tpv.value = value .relate tm_tpv to tm_tp across R2808 .relate tm_tpv to te_iir across R2806 .end for .select many te_iirs related by ep_pkg->PE_PE[R8000]->C_C[R8001]->C_PO[R4010]->C_IR[R4016]->TE_IIR[R2046] where ( ( selected.port_name == instance ) and ( selected.interface_name == tm_if.Name ) ) .for each te_iir in te_iirs .create object instance tm_tpv of TM_TPV .assign tm_tpv.instance = instance .assign tm_tpv.value = value .relate tm_tpv to tm_tp across R2808 .relate tm_tpv to te_iir across R2806 .end for .else .print ""ERROR: SetTemplateParameter - Found a template parameter for a template that is orphaned."" .end if .else .print ""WARNING: SetTemplateParameter - Did NOT find template parameter for package ${package_name}::${instance} with name ${variable_name}."" .end if .end if .end function .// .//============================================================================ .// Set Template Parameter Value .// Once components and interfaces have been marked with C++ templates .// and all template parameters added, the template parameter values can .// be set and associated with the appropriate component and interface .// instances (component references and ports). .// Set the template parameter for an instance of a component or interface .// class. The template is navigated based upon the associated package .// and instance. .//============================================================================ .function SetTPV .param string package_name .param string parent_component .param string component .param string classifier_name .param string port .param string variable_name .param string value .assign trace = ""${package_name}::${parent_component}::${component}:${classifier_name}.${variable_name} value ${value} (and port ${port})"" .if ( ( ( """" == package_name ) or ( """" == component ) ) or ( ( """" == classifier_name ) or ( ( ( """" == variable_name ) or ( """" == value ) ) ) ) ) .print ""ERROR: SetTPV - Must provide valid strings for all arguments except the optional port, ${package_name}::${parent_component}::${component}:${classifier_name}.${variable_name} to value ${value} (and port ${port})."" .else .select any ep_pkg from instances of EP_PKG where ( selected.Name == package_name ) .if ( empty ep_pkg ) .print ""ERROR: SetTPV - Package, ${package_name}, not found for ${package_name}::${parent_component}::${component}:${classifier_name}.${variable_name} to value ${value}."" .end if .select many te_cis related by ep_pkg->PE_PE[R8000]->CL_IC[R8001]->TE_CI[R2009] where ( ( selected.Name == component ) and ( selected.ClassifierName == classifier_name ) ) .if ( """" != parent_component ) .select many c_cs related by ep_pkg->PE_PE[R8000]->C_C[R8001] where ( selected.Name == parent_component ) .select many te_cis related by c_cs->PE_PE[R8003]->CL_IC[R8001]->TE_CI[R2009] where ( ( selected.Name == component ) and ( selected.ClassifierName == classifier_name ) ) .else .if ( empty te_cis ) .select many te_cis related by ep_pkg->PE_PE[R8000]->C_C[R8001]->PE_PE[R8003]->CL_IC[R8001]->TE_CI[R2009] where ( ( selected.Name == component ) and ( selected.ClassifierName == classifier_name ) ) .end if .end if .assign te_cis_count = cardinality te_cis .if ( te_cis_count > 1 ) .print ""WARNING: SetTPV - More than one instantiation found for ${package_name}::${parent_component}::${component}:${classifier_name}.${variable_name} to value ${value}."" .print "" All instantiations will be marked to receive the same template parameter value."" .elif ( 0 == te_cis_count ) .print ""ERROR: SetTPV - Component instance not found for ${package_name}::${parent_component}::${component}:${classifier_name}."" .end if .if ( """" == port ) .// We are setting values for component templates. .for each te_ci in te_cis .select one tm_template related by te_ci->TE_C[R2008]->TM_C[R2804]->TM_TEMPLATE[R2800] .select any tm_tp related by tm_template->TM_TP[R2801] where ( selected.Name == variable_name ) .if ( not_empty tm_tp ) .// Create the template parameter value and link it in. .create object instance tm_tpv of TM_TPV .assign tm_tpv.instance = component .assign tm_tpv.value = value .relate tm_tpv to tm_tp across R2808 .relate tm_tpv to te_ci across R2805 .else .print ""WARNING: SetTPV - Template parameter not found for ${package_name}::${parent_component}::${component}:${classifier_name}."" .end if .end for .else .// We are setting a value for an interface template. .for each te_ci in te_cis .select any te_iir related by te_ci->CL_IC[R2009]->CL_POR[R4707]->CL_IIR[R4708]->TE_IIR[R2013] where ( selected.port_name == port ) .invoke SetTPV_for_channel_connection( te_iir, variable_name, value, trace, 0 ) .end for .end if .end if .end function .// .// Rules .// Always start from IIR. .// On a first call, first try to cross a satisfaction from IIR. .// It is only possible to go upward on a delegation on the first call. .// After the first call, it is O.K. to cross a satisfaction after crossing .// a delegation. .// After traversing to an imported interface reference, consider marking .// the associated interface reference. (Mark both.) .// Gather all the delegated_te_iirs into a collection and then loop through. .// This is necessary for delegations only. .// Be smart and look for only the right types in the right direction. .function SetTPV_for_channel_connection .param inst_ref te_iir .param string variable_name .param string value .param string trace .param integer flavor .select many delegated_te_iirs from instances of TE_IIR where ( false ) .// flavors: 0:firstcall, 1:coming from satisfaction, 2:coming from delegation .select any tm_tp related by te_iir->C_IR[R2046]->C_I[R4012]->TM_IF[R2807]->TM_TEMPLATE[R2802]->TM_TP[R2801] where ( selected.Name == variable_name ) .if ( empty tm_tp ) .select any tm_tp related by te_iir->CL_IIR[R2013]->C_IR[R4701]->C_I[R4012]->TM_IF[R2807]->TM_TEMPLATE[R2802]->TM_TP[R2801] where ( selected.Name == variable_name ) .if ( empty tm_tp ) .print ""WARNING: SetTPV - Template parameter not found for ${trace}."" .end if .end if .// Determine whether we have an interface reference for a component marked .// as a channel. Process channel interface references on first call only. .select one tm_c related by te_iir->TE_PO[R2080]->TE_C[R2005]->TM_C[R2804] .assign isChannel = false .if ( not_empty tm_c ) .assign isChannel = tm_c.isChannel .end if .// See if this template parameter already has a value for this reference. .select any tm_tpv related by te_iir->TM_TPV[R2806] where ( ( selected.instance == te_iir.interface_name ) and ( selected.tm_tpID == tm_tp.ID ) ) .// If isChannel, then skip unless it is the first call. .if ( ( ( ( empty tm_tpv ) and ( not_empty tm_tp ) ) and ( not isChannel ) ) or ( 0 == flavor ) ) .//.select one te_c related by te_iir->TE_PO[R2080]->TE_C[R2005] .//.print ""${trace} ${te_iir.port_name} ${te_c.Name}"" .create object instance tm_tpv of TM_TPV .assign tm_tpv.instance = te_iir.interface_name .assign tm_tpv.value = value .relate tm_tpv to tm_tp across R2808 .relate tm_tpv to te_iir across R2806 .// .// Find a satisfaction or delegation. Recursively apply the same template parameter value to the connections. .select one satisfied_te_iir related by te_iir->TE_IIR[R2081.'requires or delegates'] where ( false ) .if ( ( 0 == flavor ) or ( 2 == flavor ) ) .// iir to iir .// Search from imported reference across satisfaction to imported reference provision to requirement. .select many satisfied_te_iirs related by te_iir->CL_IIR[R2013]->CL_IP[R4703]->CL_IPINS[R4705]->C_SF[R4705]->CL_IR[R4706]->CL_IIR[R4703]->TE_IIR[R2013] .if ( not_empty satisfied_te_iirs ) .for each satisfied_te_iir in satisfied_te_iirs .invoke SetTPV_for_channel_connection( satisfied_te_iir, variable_name, value, "" 1${trace}"", 1 ) .end for .else .// Search from imported reference across satisfaction to imported reference requirement to provision. .select one satisfied_te_iir related by te_iir->CL_IIR[R2013]->CL_IR[R4703]->C_SF[R4706]->CL_IPINS[R4705]->CL_IP[R4705]->CL_IIR[R4703]->TE_IIR[R2013] .if ( not_empty satisfied_te_iir ) .invoke SetTPV_for_channel_connection( satisfied_te_iir, variable_name, value, "" 2${trace}"", 1 ) .else .// mixed iir and ir .// Search from imported reference across satisfaction to reference imported provision to requirement. .select many satisfied_te_iirs related by te_iir->CL_IIR[R2013]->CL_IP[R4703]->CL_IPINS[R4705]->C_SF[R4705]->C_R[R4002]->C_IR[R4009]->TE_IIR[R2046] .if ( not_empty satisfied_te_iirs ) .for each satisfied_te_iir in satisfied_te_iirs .invoke SetTPV_for_channel_connection( satisfied_te_iir, variable_name, value, "" 3${trace}"", 1 ) .end for .else .// Search from imported reference across satisfaction to reference imported requirement to provision. .select one satisfied_te_iir related by te_iir->CL_IIR[R2013]->CL_IR[R4703]->C_SF[R4706]->C_P[R4002]->C_IR[R4009]->TE_IIR[R2046] .if ( not_empty satisfied_te_iir ) .invoke SetTPV_for_channel_connection( satisfied_te_iir, variable_name, value, "" 4${trace}"", 1 ) .else .// Search from reference across satisfaction to reference provision to requirement. .select any satisfied_te_iir related by te_iir->C_IR[R2046]->C_P[R4009]->C_SF[R4002]->C_R[R4002]->C_IR[R4009]->TE_IIR[R2046] .if ( not_empty satisfied_te_iir ) .invoke SetTPV_for_channel_connection( satisfied_te_iir, variable_name, value, "" 4a${trace}"", 1 ) .else .// Search from reference across satisfaction to reference requirement to provision. .select any satisfied_te_iir related by te_iir->C_IR[R2046]->C_R[R4009]->C_SF[R4002]->C_P[R4002]->C_IR[R4009]->TE_IIR[R2046] .if ( not_empty satisfied_te_iir ) .invoke SetTPV_for_channel_connection( satisfied_te_iir, variable_name, value, "" 4b${trace}"", 1 ) .else .// Search from reference across satisfaction to imported reference imported provision to requirement. .// CDS should not find these, because we already go the other mixed direction? .//.select one satisfied_te_iir related by te_iir->C_IR[R2046]->C_P[R4009]->C_SF[R4002]->CL_IR[R4706]->CL_IIR[R4703]->TE_IIR[R2013] .if ( not_empty satisfied_te_iir ) .invoke SetTPV_for_channel_connection( satisfied_te_iir, variable_name, value, "" 5${trace}"", 1 ) .else .// Search from reference across satisfaction to imported reference imported requirement to provision. .// CDS should not find these, because we already go the other mixed direction? .//.select one satisfied_te_iir related by te_iir->C_IR[R2046]->C_R[R4009]->C_SF[R4002]->CL_IPINS[R4705]->CL_IP[R4705]->CL_IIR[R4703]->TE_IIR[R2013] .if ( not_empty satisfied_te_iir ) .invoke SetTPV_for_channel_connection( satisfied_te_iir, variable_name, value, "" 6${trace}"", 1 ) .end if .end if .end if .end if .end if .end if .end if .end if .end if .// delegation .if ( empty satisfied_te_iir ) .select one delegated_te_iir related by satisfied_te_iir->TE_IIR[R2081.'requires or delegates'] where ( false ) .// IIR IR DG RID IR .select any delegated_te_iir related by te_iir->CL_IIR[R2013]->C_DG[R4704]->C_RID[R4013]->C_IR[R4013]->TE_IIR[R2046] .if ( not_empty delegated_te_iir ) .assign delegated_te_iirs = delegated_te_iirs | delegated_te_iir .assign trace = ""7a "" + trace .end if .select any delegated_te_iir related by te_iir->CL_IIR[R2013]->C_IR[R4701]->C_RID[R4013]->C_DG[R4013]->CL_IIR[R4704]->TE_IIR[R2013] .if ( not_empty delegated_te_iir ) .assign delegated_te_iirs = delegated_te_iirs | delegated_te_iir .assign trace = ""7b "" + trace .end if .// IR DG RID IR .select any delegated_te_iir related by te_iir->C_IR[R2046]->C_DG[R4014]->C_RID[R4013]->C_IR[R4013]->TE_IIR[R2046] .if ( not_empty delegated_te_iir ) .assign delegated_te_iirs = delegated_te_iirs | delegated_te_iir .assign trace = ""8a "" + trace .end if .// IR RID DG IR .select any delegated_te_iir related by te_iir->C_IR[R2046]->C_RID[R4013]->C_DG[R4013]->C_IR[R4014]->TE_IIR[R2046] .if ( not_empty delegated_te_iir ) .assign delegated_te_iirs = delegated_te_iirs | delegated_te_iir .assign trace = ""8b "" + trace .end if .// IIR IR DG RID IR .select any delegated_te_iir related by te_iir->CL_IIR[R2013]->C_IR[R4701]->C_DG[R4014]->C_RID[R4013]->C_IR[R4013]->TE_IIR[R2046] .if ( not_empty delegated_te_iir ) .assign delegated_te_iirs = delegated_te_iirs | delegated_te_iir .assign trace = ""8c "" + trace .end if .// IR DG RID IR IIR .select any delegated_te_iir related by te_iir->C_IR[R2046]->C_DG[R4014]->C_RID[R4013]->C_IR[R4013]->CL_IIR[R4701]->TE_IIR[R2013] .if ( not_empty delegated_te_iir ) .assign delegated_te_iirs = delegated_te_iirs | delegated_te_iir .assign trace = ""8d "" + trace .end if .// IIR IR RID DG IR .select many more_delegated_te_iirs related by te_iir->CL_IIR[R2013]->C_IR[R4701]->C_RID[R4013]->C_DG[R4013]->C_IR[R4014]->TE_IIR[R2046] .if ( not_empty more_delegated_te_iirs ) .assign delegated_te_iirs = delegated_te_iirs | more_delegated_te_iirs .assign trace = ""8e "" + trace .end if .// IR RID DG IR IIR .select many more_delegated_te_iirs related by te_iir->C_IR[R2046]->C_RID[R4013]->C_DG[R4013]->C_IR[R4014]->CL_IIR[R4701]->TE_IIR[R2013] .if ( not_empty more_delegated_te_iirs ) .assign delegated_te_iirs = delegated_te_iirs | more_delegated_te_iirs .assign trace = ""8f "" + trace .end if .// IIR IR DG RID IR IIR .select any delegated_te_iir related by te_iir->CL_IIR[R2013]->C_IR[R4701]->C_DG[R4014]->C_RID[R4013]->C_IR[R4013]->CL_IIR[R4701]->TE_IIR[R2013] .if ( not_empty delegated_te_iir ) .assign delegated_te_iirs = delegated_te_iirs | delegated_te_iir .assign trace = ""8g "" + trace .end if .// IIR IR RID DG IR IIR .select many more_delegated_te_iirs related by te_iir->CL_IIR[R2013]->C_IR[R4701]->C_RID[R4013]->C_DG[R4013]->C_IR[R4014]->CL_IIR[R4701]->TE_IIR[R2013] .if ( not_empty more_delegated_te_iirs ) .assign delegated_te_iirs = delegated_te_iirs | more_delegated_te_iirs .assign trace = ""8h "" + trace .end if .select any delegated_te_iir related by te_iir->CL_IIR[R2013]->C_IR[R4701]->C_RID[R4013]->C_DG[R4013]->C_IR[R4014]->TE_IIR[R2046] .if ( not_empty delegated_te_iir ) .assign delegated_te_iirs = delegated_te_iirs | delegated_te_iir .assign trace = ""B "" + trace .end if .for each delegated_te_iir in delegated_te_iirs .invoke SetTPV_for_channel_connection( delegated_te_iir, variable_name, value, ""${trace}"", 2 ) .end for .end if .else .if ( empty tm_tp ) .print ""SetTPV: warning - no variable ${te_iir.port_name} ${te_iir.interface_name}"" .end if .end if .end function .// .//============================================================================ .// Mark the prefixes for the interface naming. .//============================================================================ .function MarkInterfacePrefix .param string provided_port .param string required_port .param string channel .select any te_prefix from instances of TE_PREFIX .assign te_prefix.provided_port = provided_port .assign te_prefix.required_port = required_port .assign te_prefix.channel = channel .end function .// .//============================================================================ .// Mark components as realized using package name and/or component .// name as the selection criteria. .//============================================================================ .function MarkComponentAsRealized .param string package_name .param string component_name .param string inc_file .select many c_cs from instances of C_C where ( false ) .if ( ( ( """" == package_name ) and ( """" == component_name ) ) or ( ( ""*"" == package_name ) and ( ""*"" == component_name ) ) ) .// all components .select many c_cs from instances of C_C .elif ( ( """" == package_name ) or ( ""*"" == package_name ) ) .// matches without respect to package .select many c_cs from instances of C_C where ( selected.Name == component_name ) .elif ( ( """" == component_name ) or ( ""*"" == component_name ) ) .// all components in packages with given name .select many ep_pkgs from instances of EP_PKG where ( selected.Name == package_name ) .select many c_cs related by ep_pkgs->PE_PE[R8000]->C_C[R8001] .else .// particular component in particular package(s) .select many ep_pkgs from instances of EP_PKG where ( selected.Name == package_name ) .select many c_cs related by ep_pkgs->PE_PE[R8000]->C_C[R8001] where ( selected.Name == component_name ) .end if .if ( empty c_cs ) .print ""WARNING: MarkComponentAsRealized - Could not find component ${package_name}::${component_name}."" .end if .for each c_c in c_cs .select any tm_c from instances of TM_C where ( ( selected.Name == component_name ) and ( selected.Package == package_name ) ) .if ( empty tm_c ) .create object instance tm_c of TM_C .assign tm_c.Package = package_name .assign tm_c.Name = component_name .end if .assign tm_c.isRealized = true .assign tm_c.include_file = inc_file .end for .end function ",8432,False,1730.1647730330812,median "// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include #include #include ""ax_build/build_config.h"" #include ""gfx/test/gfx_util.h"" #include ""gtest/gtest.h"" #include ""rect.h"" #include ""rect_conversions.h"" #if defined(OS_WIN) #include #endif namespace gfx { template constexpr size_t size(const T (&array)[N]) noexcept { return N; } TEST(RectTest, Contains) { static const struct ContainsCase { int rect_x; int rect_y; int rect_width; int rect_height; int point_x; int point_y; bool contained; } contains_cases[] = { {0, 0, 10, 10, 0, 0, true}, {0, 0, 10, 10, 5, 5, true}, {0, 0, 10, 10, 9, 9, true}, {0, 0, 10, 10, 5, 10, false}, {0, 0, 10, 10, 10, 5, false}, {0, 0, 10, 10, -1, -1, false}, {0, 0, 10, 10, 50, 50, false}, #if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON) {0, 0, -10, -10, 0, 0, false}, #endif }; for (size_t i = 0; i < size(contains_cases); ++i) { const ContainsCase& value = contains_cases[i]; Rect rect(value.rect_x, value.rect_y, value.rect_width, value.rect_height); EXPECT_EQ(value.contained, rect.Contains(value.point_x, value.point_y)); } } TEST(RectTest, Intersects) { static const struct { int x1; // rect 1 int y1; int w1; int h1; int x2; // rect 2 int y2; int w2; int h2; bool intersects; } tests[] = {{0, 0, 0, 0, 0, 0, 0, 0, false}, {0, 0, 0, 0, -10, -10, 20, 20, false}, {-10, 0, 0, 20, 0, -10, 20, 0, false}, {0, 0, 10, 10, 0, 0, 10, 10, true}, {0, 0, 10, 10, 10, 10, 10, 10, false}, {10, 10, 10, 10, 0, 0, 10, 10, false}, {10, 10, 10, 10, 5, 5, 10, 10, true}, {10, 10, 10, 10, 15, 15, 10, 10, true}, {10, 10, 10, 10, 20, 15, 10, 10, false}, {10, 10, 10, 10, 21, 15, 10, 10, false}}; for (size_t i = 0; i < size(tests); ++i) { Rect r1(tests[i].x1, tests[i].y1, tests[i].w1, tests[i].h1); Rect r2(tests[i].x2, tests[i].y2, tests[i].w2, tests[i].h2); EXPECT_EQ(tests[i].intersects, r1.Intersects(r2)); EXPECT_EQ(tests[i].intersects, r2.Intersects(r1)); } } TEST(RectTest, Intersect) { static const struct { int x1; // rect 1 int y1; int w1; int h1; int x2; // rect 2 int y2; int w2; int h2; int x3; // rect 3: the union of rects 1 and 2 int y3; int w3; int h3; } tests[] = {{0, 0, 0, 0, // zeros 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 4, 4, // equal 0, 0, 4, 4, 0, 0, 4, 4}, {0, 0, 4, 4, // neighboring 4, 4, 4, 4, 0, 0, 0, 0}, {0, 0, 4, 4, // overlapping corners 2, 2, 4, 4, 2, 2, 2, 2}, {0, 0, 4, 4, // T junction 3, 1, 4, 2, 3, 1, 1, 2}, {3, 0, 2, 2, // gap 0, 0, 2, 2, 0, 0, 0, 0}}; for (size_t i = 0; i < size(tests); ++i) { Rect r1(tests[i].x1, tests[i].y1, tests[i].w1, tests[i].h1); Rect r2(tests[i].x2, tests[i].y2, tests[i].w2, tests[i].h2); Rect r3(tests[i].x3, tests[i].y3, tests[i].w3, tests[i].h3); Rect ir = IntersectRects(r1, r2); EXPECT_EQ(r3.x(), ir.x()); EXPECT_EQ(r3.y(), ir.y()); EXPECT_EQ(r3.width(), ir.width()); EXPECT_EQ(r3.height(), ir.height()); } } TEST(RectTest, Union) { static const struct Test { int x1; // rect 1 int y1; int w1; int h1; int x2; // rect 2 int y2; int w2; int h2; int x3; // rect 3: the union of rects 1 and 2 int y3; int w3; int h3; } tests[] = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 4, 4, 0, 0, 4, 4, 0, 0, 4, 4}, {0, 0, 4, 4, 4, 4, 4, 4, 0, 0, 8, 8}, {0, 0, 4, 4, 0, 5, 4, 4, 0, 0, 4, 9}, {0, 0, 2, 2, 3, 3, 2, 2, 0, 0, 5, 5}, {3, 3, 2, 2, // reverse r1 and r2 from previous test 0, 0, 2, 2, 0, 0, 5, 5}, {0, 0, 0, 0, // union with empty rect 2, 2, 2, 2, 2, 2, 2, 2}}; for (size_t i = 0; i < size(tests); ++i) { Rect r1(tests[i].x1, tests[i].y1, tests[i].w1, tests[i].h1); Rect r2(tests[i].x2, tests[i].y2, tests[i].w2, tests[i].h2); Rect r3(tests[i].x3, tests[i].y3, tests[i].w3, tests[i].h3); Rect u = UnionRects(r1, r2); EXPECT_EQ(r3.x(), u.x()); EXPECT_EQ(r3.y(), u.y()); EXPECT_EQ(r3.width(), u.width()); EXPECT_EQ(r3.height(), u.height()); } } TEST(RectTest, Equals) { ASSERT_TRUE(Rect(0, 0, 0, 0) == Rect(0, 0, 0, 0)); ASSERT_TRUE(Rect(1, 2, 3, 4) == Rect(1, 2, 3, 4)); ASSERT_FALSE(Rect(0, 0, 0, 0) == Rect(0, 0, 0, 1)); ASSERT_FALSE(Rect(0, 0, 0, 0) == Rect(0, 0, 1, 0)); ASSERT_FALSE(Rect(0, 0, 0, 0) == Rect(0, 1, 0, 0)); ASSERT_FALSE(Rect(0, 0, 0, 0) == Rect(1, 0, 0, 0)); } TEST(RectTest, AdjustToFit) { static const struct Test { int x1; // source int y1; int w1; int h1; int x2; // target int y2; int w2; int h2; int x3; // rect 3: results of invoking AdjustToFit int y3; int w3; int h3; } tests[] = {{0, 0, 2, 2, 0, 0, 2, 2, 0, 0, 2, 2}, {2, 2, 3, 3, 0, 0, 4, 4, 1, 1, 3, 3}, {-1, -1, 5, 5, 0, 0, 4, 4, 0, 0, 4, 4}, {2, 2, 4, 4, 0, 0, 3, 3, 0, 0, 3, 3}, {2, 2, 1, 1, 0, 0, 3, 3, 2, 2, 1, 1}}; for (size_t i = 0; i < size(tests); ++i) { Rect r1(tests[i].x1, tests[i].y1, tests[i].w1, tests[i].h1); Rect r2(tests[i].x2, tests[i].y2, tests[i].w2, tests[i].h2); Rect r3(tests[i].x3, tests[i].y3, tests[i].w3, tests[i].h3); Rect u = r1; u.AdjustToFit(r2); EXPECT_EQ(r3.x(), u.x()); EXPECT_EQ(r3.y(), u.y()); EXPECT_EQ(r3.width(), u.width()); EXPECT_EQ(r3.height(), u.height()); } } TEST(RectTest, Subtract) { Rect result; // Matching result = Rect(10, 10, 20, 20); result.Subtract(Rect(10, 10, 20, 20)); EXPECT_EQ(Rect(0, 0, 0, 0), result); // Contains result = Rect(10, 10, 20, 20); result.Subtract(Rect(5, 5, 30, 30)); EXPECT_EQ(Rect(0, 0, 0, 0), result); // No intersection result = Rect(10, 10, 20, 20); result.Subtract(Rect(30, 30, 30, 30)); EXPECT_EQ(Rect(10, 10, 20, 20), result); // Not a complete intersection in either direction result = Rect(10, 10, 20, 20); result.Subtract(Rect(15, 15, 20, 20)); EXPECT_EQ(Rect(10, 10, 20, 20), result); // Complete intersection in the x-direction, top edge is fully covered. result = Rect(10, 10, 20, 20); result.Subtract(Rect(10, 15, 20, 20)); EXPECT_EQ(Rect(10, 10, 20, 5), result); // Complete intersection in the x-direction, top edge is fully covered. result = Rect(10, 10, 20, 20); result.Subtract(Rect(5, 15, 30, 20)); EXPECT_EQ(Rect(10, 10, 20, 5), result); // Complete intersection in the x-direction, bottom edge is fully covered. result = Rect(10, 10, 20, 20); result.Subtract(Rect(5, 5, 30, 20)); EXPECT_EQ(Rect(10, 25, 20, 5), result); // Complete intersection in the x-direction, none of the edges is fully // covered. result = Rect(10, 10, 20, 20); result.Subtract(Rect(5, 15, 30, 1)); EXPECT_EQ(Rect(10, 10, 20, 20), result); // Complete intersection in the y-direction, left edge is fully covered. result = Rect(10, 10, 20, 20); result.Subtract(Rect(10, 10, 10, 30)); EXPECT_EQ(Rect(20, 10, 10, 20), result); // Complete intersection in the y-direction, left edge is fully covered. result = Rect(10, 10, 20, 20); result.Subtract(Rect(5, 5, 20, 30)); EXPECT_EQ(Rect(25, 10, 5, 20), result); // Complete intersection in the y-direction, right edge is fully covered. result = Rect(10, 10, 20, 20); result.Subtract(Rect(20, 5, 20, 30)); EXPECT_EQ(Rect(10, 10, 10, 20), result); // Complete intersection in the y-direction, none of the edges is fully // covered. result = Rect(10, 10, 20, 20); result.Subtract(Rect(15, 5, 1, 30)); EXPECT_EQ(Rect(10, 10, 20, 20), result); } TEST(RectTest, IsEmpty) { EXPECT_TRUE(Rect(0, 0, 0, 0).IsEmpty()); EXPECT_TRUE(Rect(0, 0, 0, 0).size().IsEmpty()); EXPECT_TRUE(Rect(0, 0, 10, 0).IsEmpty()); EXPECT_TRUE(Rect(0, 0, 10, 0).size().IsEmpty()); EXPECT_TRUE(Rect(0, 0, 0, 10).IsEmpty()); EXPECT_TRUE(Rect(0, 0, 0, 10).size().IsEmpty()); EXPECT_FALSE(Rect(0, 0, 10, 10).IsEmpty()); EXPECT_FALSE(Rect(0, 0, 10, 10).size().IsEmpty()); } TEST(RectTest, SplitVertically) { Rect left_half, right_half; // Splitting when origin is (0, 0). Rect(0, 0, 20, 20).SplitVertically(&left_half, &right_half); EXPECT_TRUE(left_half == Rect(0, 0, 10, 20)); EXPECT_TRUE(right_half == Rect(10, 0, 10, 20)); // Splitting when origin is arbitrary. Rect(10, 10, 20, 10).SplitVertically(&left_half, &right_half); EXPECT_TRUE(left_half == Rect(10, 10, 10, 10)); EXPECT_TRUE(right_half == Rect(20, 10, 10, 10)); // Splitting a rectangle of zero width. Rect(10, 10, 0, 10).SplitVertically(&left_half, &right_half); EXPECT_TRUE(left_half == Rect(10, 10, 0, 10)); EXPECT_TRUE(right_half == Rect(10, 10, 0, 10)); // Splitting a rectangle of odd width. Rect(10, 10, 5, 10).SplitVertically(&left_half, &right_half); EXPECT_TRUE(left_half == Rect(10, 10, 2, 10)); EXPECT_TRUE(right_half == Rect(12, 10, 3, 10)); } TEST(RectTest, CenterPoint) { Point center; // When origin is (0, 0). center = Rect(0, 0, 20, 20).CenterPoint(); EXPECT_TRUE(center == Point(10, 10)); // When origin is even. center = Rect(10, 10, 20, 20).CenterPoint(); EXPECT_TRUE(center == Point(20, 20)); // When origin is odd. center = Rect(11, 11, 20, 20).CenterPoint(); EXPECT_TRUE(center == Point(21, 21)); // When 0 width or height. center = Rect(10, 10, 0, 20).CenterPoint(); EXPECT_TRUE(center == Point(10, 20)); center = Rect(10, 10, 20, 0).CenterPoint(); EXPECT_TRUE(center == Point(20, 10)); // When an odd size. center = Rect(10, 10, 21, 21).CenterPoint(); EXPECT_TRUE(center == Point(20, 20)); // When an odd size and position. center = Rect(11, 11, 21, 21).CenterPoint(); EXPECT_TRUE(center == Point(21, 21)); } TEST(RectTest, CenterPointF) { PointF center; // When origin is (0, 0). center = RectF(0, 0, 20, 20).CenterPoint(); EXPECT_TRUE(center == PointF(10, 10)); // When origin is even. center = RectF(10, 10, 20, 20).CenterPoint(); EXPECT_TRUE(center == PointF(20, 20)); // When origin is odd. center = RectF(11, 11, 20, 20).CenterPoint(); EXPECT_TRUE(center == PointF(21, 21)); // When 0 width or height. center = RectF(10, 10, 0, 20).CenterPoint(); EXPECT_TRUE(center == PointF(10, 20)); center = RectF(10, 10, 20, 0).CenterPoint(); EXPECT_TRUE(center == PointF(20, 10)); // When an odd size. center = RectF(10, 10, 21, 21).CenterPoint(); EXPECT_TRUE(center == PointF(20.5f, 20.5f)); // When an odd size and position. center = RectF(11, 11, 21, 21).CenterPoint(); EXPECT_TRUE(center == PointF(21.5f, 21.5f)); } TEST(RectTest, SharesEdgeWith) { Rect r(2, 3, 4, 5); // Must be non-overlapping EXPECT_FALSE(r.SharesEdgeWith(r)); Rect just_above(2, 1, 4, 2); Rect just_below(2, 8, 4, 2); Rect just_left(0, 3, 2, 5); Rect just_right(6, 3, 2, 5); EXPECT_TRUE(r.SharesEdgeWith(just_above)); EXPECT_TRUE(r.SharesEdgeWith(just_below)); EXPECT_TRUE(r.SharesEdgeWith(just_left)); EXPECT_TRUE(r.SharesEdgeWith(just_right)); // Wrong placement Rect same_height_no_edge(0, 0, 1, 5); Rect same_width_no_edge(0, 0, 4, 1); EXPECT_FALSE(r.SharesEdgeWith(same_height_no_edge)); EXPECT_FALSE(r.SharesEdgeWith(same_width_no_edge)); Rect just_above_no_edge(2, 1, 5, 2); // too wide Rect just_below_no_edge(2, 8, 3, 2); // too narrow Rect just_left_no_edge(0, 3, 2, 6); // too tall Rect just_right_no_edge(6, 3, 2, 4); // too short EXPECT_FALSE(r.SharesEdgeWith(just_above_no_edge)); EXPECT_FALSE(r.SharesEdgeWith(just_below_no_edge)); EXPECT_FALSE(r.SharesEdgeWith(just_left_no_edge)); EXPECT_FALSE(r.SharesEdgeWith(just_right_no_edge)); } // Similar to EXPECT_FLOAT_EQ, but lets NaN equal NaN #define EXPECT_FLOAT_AND_NAN_EQ(a, b) \\ { \\ if (a == a || b == b) { \\ EXPECT_FLOAT_EQ(a, b); \\ } \\ } TEST(RectTest, ScaleRect) { static const struct Test { int x1; // source int y1; int w1; int h1; float scale; float x2; // target float y2; float w2; float h2; } tests[] = { {3, 3, 3, 3, 1.5f, 4.5f, 4.5f, 4.5f, 4.5f}, {3, 3, 3, 3, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, {3, 3, 3, 3, std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()}, {3, 3, 3, 3, std::numeric_limits::max(), std::numeric_limits::max(), std::numeric_limits::max(), std::numeric_limits::max(), std::numeric_limits::max()}}; for (size_t i = 0; i < size(tests); ++i) { RectF r1(tests[i].x1, tests[i].y1, tests[i].w1, tests[i].h1); RectF r2(tests[i].x2, tests[i].y2, tests[i].w2, tests[i].h2); RectF scaled = ScaleRect(r1, tests[i].scale); EXPECT_FLOAT_AND_NAN_EQ(r2.x(), scaled.x()); EXPECT_FLOAT_AND_NAN_EQ(r2.y(), scaled.y()); EXPECT_FLOAT_AND_NAN_EQ(r2.width(), scaled.width()); EXPECT_FLOAT_AND_NAN_EQ(r2.height(), scaled.height()); } } TEST(RectTest, ToEnclosedRect) { static const int max_int = std::numeric_limits::max(); static const int min_int = std::numeric_limits::min(); static const float max_float = std::numeric_limits::max(); static const float max_int_f = static_cast(max_int); static const float min_int_f = static_cast(min_int); static const struct Test { struct { float x; float y; float width; float height; } in; struct { int x; int y; int width; int height; } expected; } tests[] = { {{0.0f, 0.0f, 0.0f, 0.0f}, {0, 0, 0, 0}}, {{-1.5f, -1.5f, 3.0f, 3.0f}, {-1, -1, 2, 2}}, {{-1.5f, -1.5f, 3.5f, 3.5f}, {-1, -1, 3, 3}}, {{max_float, max_float, 2.0f, 2.0f}, {max_int, max_int, 0, 0}}, {{0.0f, 0.0f, max_float, max_float}, {0, 0, max_int, max_int}}, {{20000.5f, 20000.5f, 0.5f, 0.5f}, {20001, 20001, 0, 0}}, {{max_int_f, max_int_f, max_int_f, max_int_f}, {max_int, max_int, 0, 0}}, {{1.9999f, 2.0002f, 5.9998f, 6.0001f}, {2, 3, 5, 5}}, {{1.9999f, 2.0001f, 6.0002f, 5.9998f}, {2, 3, 6, 4}}, {{1.9998f, 2.0002f, 6.0001f, 5.9999f}, {2, 3, 5, 5}}}; for (size_t i = 0; i < size(tests); ++i) { RectF source(tests[i].in.x, tests[i].in.y, tests[i].in.width, tests[i].in.height); Rect enclosed = ToEnclosedRect(source); EXPECT_EQ(tests[i].expected.x, enclosed.x()); EXPECT_EQ(tests[i].expected.y, enclosed.y()); EXPECT_EQ(tests[i].expected.width, enclosed.width()); EXPECT_EQ(tests[i].expected.height, enclosed.height()); } { RectF source(min_int_f, min_int_f, max_int_f * 3.f, max_int_f * 3.f); Rect enclosed = ToEnclosedRect(source); // That rect can't be represented, but it should be big. EXPECT_EQ(max_int, enclosed.width()); EXPECT_EQ(max_int, enclosed.height()); // It should include some axis near the global origin. EXPECT_GT(1, enclosed.x()); EXPECT_GT(1, enclosed.y()); // And it should not cause computation issues for itself. EXPECT_LT(0, enclosed.right()); EXPECT_LT(0, enclosed.bottom()); } } TEST(RectTest, ToEnclosingRect) { static const int max_int = std::numeric_limits::max(); static const int min_int = std::numeric_limits::min(); static const float max_float = std::numeric_limits::max(); static const float epsilon_float = std::numeric_limits::epsilon(); static const float max_int_f = static_cast(max_int); static const float min_int_f = static_cast(min_int); static const struct Test { struct { float x; float y; float width; float height; } in; struct { int x; int y; int width; int height; } expected; } tests[] = { {{0.0f, 0.0f, 0.0f, 0.0f}, {0, 0, 0, 0}}, {{5.5f, 5.5f, 0.0f, 0.0f}, {5, 5, 0, 0}}, {{3.5f, 2.5f, epsilon_float, -0.0f}, {3, 2, 0, 0}}, {{3.5f, 2.5f, 0.f, 0.001f}, {3, 2, 0, 1}}, {{-1.5f, -1.5f, 3.0f, 3.0f}, {-2, -2, 4, 4}}, {{-1.5f, -1.5f, 3.5f, 3.5f}, {-2, -2, 4, 4}}, {{max_float, max_float, 2.0f, 2.0f}, {max_int, max_int, 0, 0}}, {{0.0f, 0.0f, max_float, max_float}, {0, 0, max_int, max_int}}, {{20000.5f, 20000.5f, 0.5f, 0.5f}, {20000, 20000, 1, 1}}, {{max_int_f, max_int_f, max_int_f, max_int_f}, {max_int, max_int, 0, 0}}, {{-0.5f, -0.5f, 22777712.f, 1.f}, {-1, -1, 22777713, 2}}, {{1.9999f, 2.0002f, 5.9998f, 6.0001f}, {1, 2, 7, 7}}, {{1.9999f, 2.0001f, 6.0002f, 5.9998f}, {1, 2, 8, 6}}, {{1.9998f, 2.0002f, 6.0001f, 5.9999f}, {1, 2, 7, 7}}}; for (size_t i = 0; i < size(tests); ++i) { RectF source(tests[i].in.x, tests[i].in.y, tests[i].in.width, tests[i].in.height); Rect enclosing = ToEnclosingRect(source); EXPECT_EQ(tests[i].expected.x, enclosing.x()); EXPECT_EQ(tests[i].expected.y, enclosing.y()); EXPECT_EQ(tests[i].expected.width, enclosing.width()); EXPECT_EQ(tests[i].expected.height, enclosing.height()); } { RectF source(min_int_f, min_int_f, max_int_f * 3.f, max_int_f * 3.f); Rect enclosing = ToEnclosingRect(source); // That rect can't be represented, but it should be big. EXPECT_EQ(max_int, enclosing.width()); EXPECT_EQ(max_int, enclosing.height()); // It should include some axis near the global origin. EXPECT_GT(1, enclosing.x()); EXPECT_GT(1, enclosing.y()); // And it should cause computation issues for itself. EXPECT_LT(0, enclosing.right()); EXPECT_LT(0, enclosing.bottom()); } } TEST(RectTest, ToEnclosingRectIgnoringError) { static const int max_int = std::numeric_limits::max(); static const float max_float = std::numeric_limits::max(); static const float epsilon_float = std::numeric_limits::epsilon(); static const float max_int_f = static_cast(max_int); static const float error = 0.001f; static const struct Test { struct { float x; float y; float width; float height; } in; struct { int x; int y; int width; int height; } expected; } tests[] = { {{0.0f, 0.0f, 0.0f, 0.0f}, {0, 0, 0, 0}}, {{5.5f, 5.5f, 0.0f, 0.0f}, {5, 5, 0, 0}}, {{3.5f, 2.5f, epsilon_float, -0.0f}, {3, 2, 0, 0}}, {{3.5f, 2.5f, 0.f, 0.001f}, {3, 2, 0, 1}}, {{-1.5f, -1.5f, 3.0f, 3.0f}, {-2, -2, 4, 4}}, {{-1.5f, -1.5f, 3.5f, 3.5f}, {-2, -2, 4, 4}}, {{max_float, max_float, 2.0f, 2.0f}, {max_int, max_int, 0, 0}}, {{0.0f, 0.0f, max_float, max_float}, {0, 0, max_int, max_int}}, {{20000.5f, 20000.5f, 0.5f, 0.5f}, {20000, 20000, 1, 1}}, {{max_int_f, max_int_f, max_int_f, max_int_f}, {max_int, max_int, 0, 0}}, {{-0.5f, -0.5f, 22777712.f, 1.f}, {-1, -1, 22777713, 2}}, {{1.9999f, 2.0002f, 5.9998f, 6.0001f}, {2, 2, 6, 6}}, {{1.9999f, 2.0001f, 6.0002f, 5.9998f}, {2, 2, 6, 6}}, {{1.9998f, 2.0002f, 6.0001f, 5.9999f}, {2, 2, 6, 6}}}; for (size_t i = 0; i < size(tests); ++i) { RectF source(tests[i].in.x, tests[i].in.y, tests[i].in.width, tests[i].in.height); Rect enclosing = ToEnclosingRectIgnoringError(source, error); EXPECT_EQ(tests[i].expected.x, enclosing.x()); EXPECT_EQ(tests[i].expected.y, enclosing.y()); EXPECT_EQ(tests[i].expected.width, enclosing.width()); EXPECT_EQ(tests[i].expected.height, enclosing.height()); } } TEST(RectTest, ToNearestRect) { Rect rect; EXPECT_EQ(rect, ToNearestRect(RectF(rect))); rect = Rect(-1, -1, 3, 3); EXPECT_EQ(rect, ToNearestRect(RectF(rect))); RectF rectf(-1.00001f, -0.999999f, 3.0000001f, 2.999999f); EXPECT_EQ(rect, ToNearestRect(rectf)); } TEST(RectTest, ToFlooredRect) { static const struct Test { float x1; // source float y1; float w1; float h1; int x2; // target int y2; int w2; int h2; } tests[] = { {0.0f, 0.0f, 0.0f, 0.0f, 0, 0, 0, 0}, {-1.5f, -1.5f, 3.0f, 3.0f, -2, -2, 3, 3}, {-1.5f, -1.5f, 3.5f, 3.5f, -2, -2, 3, 3}, {20000.5f, 20000.5f, 0.5f, 0.5f, 20000, 20000, 0, 0}, }; for (size_t i = 0; i < size(tests); ++i) { RectF r1(tests[i].x1, tests[i].y1, tests[i].w1, tests[i].h1); Rect r2(tests[i].x2, tests[i].y2, tests[i].w2, tests[i].h2); Rect floored = ToFlooredRectDeprecated(r1); EXPECT_FLOAT_EQ(r2.x(), floored.x()); EXPECT_FLOAT_EQ(r2.y(), floored.y()); EXPECT_FLOAT_EQ(r2.width(), floored.width()); EXPECT_FLOAT_EQ(r2.height(), floored.height()); } } TEST(RectTest, ScaleToEnclosedRect) { static const struct Test { Rect input_rect; float input_scale; Rect expected_rect; } tests[] = {{ Rect(), 5.f, Rect(), }, { Rect(1, 1, 1, 1), 5.f, Rect(5, 5, 5, 5), }, { Rect(-1, -1, 0, 0), 5.f, Rect(-5, -5, 0, 0), }, { Rect(1, -1, 0, 1), 5.f, Rect(5, -5, 0, 5), }, { Rect(-1, 1, 1, 0), 5.f, Rect(-5, 5, 5, 0), }, { Rect(1, 2, 3, 4), 1.5f, Rect(2, 3, 4, 6), }, { Rect(-1, -2, 0, 0), 1.5f, Rect(-1, -3, 0, 0), }}; for (size_t i = 0; i < size(tests); ++i) { Rect result = ScaleToEnclosedRect(tests[i].input_rect, tests[i].input_scale); EXPECT_EQ(tests[i].expected_rect, result); } } TEST(RectTest, ScaleToEnclosingRect) { static const struct Test { Rect input_rect; float input_scale; Rect expected_rect; } tests[] = {{ Rect(), 5.f, Rect(), }, { Rect(1, 1, 1, 1), 5.f, Rect(5, 5, 5, 5), }, { Rect(-1, -1, 0, 0), 5.f, Rect(-5, -5, 0, 0), }, { Rect(1, -1, 0, 1), 5.f, Rect(5, -5, 0, 5), }, { Rect(-1, 1, 1, 0), 5.f, Rect(-5, 5, 5, 0), }, { Rect(1, 2, 3, 4), 1.5f, Rect(1, 3, 5, 6), }, { Rect(-1, -2, 0, 0), 1.5f, Rect(-2, -3, 0, 0), }}; for (size_t i = 0; i < size(tests); ++i) { Rect result = ScaleToEnclosingRect(tests[i].input_rect, tests[i].input_scale); EXPECT_EQ(tests[i].expected_rect, result); Rect result_safe = ScaleToEnclosingRectSafe(tests[i].input_rect, tests[i].input_scale); EXPECT_EQ(tests[i].expected_rect, result_safe); } } #if defined(OS_WIN) TEST(RectTest, ConstructAndAssign) { const RECT rect_1 = {0, 0, 10, 10}; const RECT rect_2 = {0, 0, -10, -10}; Rect test1(rect_1); Rect test2(rect_2); } #endif TEST(RectTest, ToRectF) { // Check that explicit conversion from integer to float compiles. Rect a(10, 20, 30, 40); RectF b(10, 20, 30, 40); RectF c = RectF(a); EXPECT_EQ(b, c); } TEST(RectTest, BoundingRect) { struct { Point a; Point b; Rect expected; } int_tests[] = { // If point B dominates A, then A should be the origin. {Point(4, 6), Point(4, 6), Rect(4, 6, 0, 0)}, {Point(4, 6), Point(8, 6), Rect(4, 6, 4, 0)}, {Point(4, 6), Point(4, 9), Rect(4, 6, 0, 3)}, {Point(4, 6), Point(8, 9), Rect(4, 6, 4, 3)}, // If point A dominates B, then B should be the origin. {Point(4, 6), Point(4, 6), Rect(4, 6, 0, 0)}, {Point(8, 6), Point(4, 6), Rect(4, 6, 4, 0)}, {Point(4, 9), Point(4, 6), Rect(4, 6, 0, 3)}, {Point(8, 9), Point(4, 6), Rect(4, 6, 4, 3)}, // If neither point dominates, then the origin is a combination of the // two. {Point(4, 6), Point(6, 4), Rect(4, 4, 2, 2)}, {Point(-4, -6), Point(-6, -4), Rect(-6, -6, 2, 2)}, {Point(-4, 6), Point(6, -4), Rect(-4, -4, 10, 10)}, }; for (size_t i = 0; i < size(int_tests); ++i) { Rect actual = BoundingRect(int_tests[i].a, int_tests[i].b); EXPECT_EQ(int_tests[i].expected, actual); } struct { PointF a; PointF b; RectF expected; } float_tests[] = { // If point B dominates A, then A should be the origin. {PointF(4.2f, 6.8f), PointF(4.2f, 6.8f), RectF(4.2f, 6.8f, 0, 0)}, {PointF(4.2f, 6.8f), PointF(8.5f, 6.8f), RectF(4.2f, 6.8f, 4.3f, 0)}, {PointF(4.2f, 6.8f), PointF(4.2f, 9.3f), RectF(4.2f, 6.8f, 0, 2.5f)}, {PointF(4.2f, 6.8f), PointF(8.5f, 9.3f), RectF(4.2f, 6.8f, 4.3f, 2.5f)}, // If point A dominates B, then B should be the origin. {PointF(4.2f, 6.8f), PointF(4.2f, 6.8f), RectF(4.2f, 6.8f, 0, 0)}, {PointF(8.5f, 6.8f), PointF(4.2f, 6.8f), RectF(4.2f, 6.8f, 4.3f, 0)}, {PointF(4.2f, 9.3f), PointF(4.2f, 6.8f), RectF(4.2f, 6.8f, 0, 2.5f)}, {PointF(8.5f, 9.3f), PointF(4.2f, 6.8f), RectF(4.2f, 6.8f, 4.3f, 2.5f)}, // If neither point dominates, then the origin is a combination of the // two. {PointF(4.2f, 6.8f), PointF(6.8f, 4.2f), RectF(4.2f, 4.2f, 2.6f, 2.6f)}, {PointF(-4.2f, -6.8f), PointF(-6.8f, -4.2f), RectF(-6.8f, -6.8f, 2.6f, 2.6f)}, {PointF(-4.2f, 6.8f), PointF(6.8f, -4.2f), RectF(-4.2f, -4.2f, 11.0f, 11.0f)}}; for (size_t i = 0; i < size(float_tests); ++i) { RectF actual = BoundingRect(float_tests[i].a, float_tests[i].b); EXPECT_RECTF_EQ(float_tests[i].expected, actual); } } TEST(RectTest, IsExpressibleAsRect) { EXPECT_TRUE(RectF().IsExpressibleAsRect()); float min = static_cast(std::numeric_limits::min()); float max = static_cast(std::numeric_limits::max()); float infinity = std::numeric_limits::infinity(); EXPECT_TRUE( RectF(min + 200, min + 200, max - 200, max - 200).IsExpressibleAsRect()); EXPECT_FALSE( RectF(min - 200, min + 200, max + 200, max + 200).IsExpressibleAsRect()); EXPECT_FALSE( RectF(min + 200, min - 200, max + 200, max + 200).IsExpressibleAsRect()); EXPECT_FALSE( RectF(min + 200, min + 200, max + 200, max - 200).IsExpressibleAsRect()); EXPECT_FALSE( RectF(min + 200, min + 200, max - 200, max + 200).IsExpressibleAsRect()); EXPECT_TRUE(RectF(0, 0, max - 200, max - 200).IsExpressibleAsRect()); EXPECT_FALSE(RectF(200, 0, max + 200, max - 200).IsExpressibleAsRect()); EXPECT_FALSE(RectF(0, 200, max - 200, max + 200).IsExpressibleAsRect()); EXPECT_FALSE(RectF(0, 0, max + 200, max - 200).IsExpressibleAsRect()); EXPECT_FALSE(RectF(0, 0, max - 200, max + 200).IsExpressibleAsRect()); EXPECT_FALSE(RectF(infinity, 0, 1, 1).IsExpressibleAsRect()); EXPECT_FALSE(RectF(0, infinity, 1, 1).IsExpressibleAsRect()); EXPECT_FALSE(RectF(0, 0, infinity, 1).IsExpressibleAsRect()); EXPECT_FALSE(RectF(0, 0, 1, infinity).IsExpressibleAsRect()); } TEST(RectTest, Offset) { Rect i(1, 2, 3, 4); EXPECT_EQ(Rect(2, 1, 3, 4), (i + Vector2d(1, -1))); EXPECT_EQ(Rect(2, 1, 3, 4), (Vector2d(1, -1) + i)); i += Vector2d(1, -1); EXPECT_EQ(Rect(2, 1, 3, 4), i); EXPECT_EQ(Rect(1, 2, 3, 4), (i - Vector2d(1, -1))); i -= Vector2d(1, -1); EXPECT_EQ(Rect(1, 2, 3, 4), i); RectF f(1.1f, 2.2f, 3.3f, 4.4f); EXPECT_EQ(RectF(2.2f, 1.1f, 3.3f, 4.4f), (f + Vector2dF(1.1f, -1.1f))); EXPECT_EQ(RectF(2.2f, 1.1f, 3.3f, 4.4f), (Vector2dF(1.1f, -1.1f) + f)); f += Vector2dF(1.1f, -1.1f); EXPECT_EQ(RectF(2.2f, 1.1f, 3.3f, 4.4f), f); EXPECT_EQ(RectF(1.1f, 2.2f, 3.3f, 4.4f), (f - Vector2dF(1.1f, -1.1f))); f -= Vector2dF(1.1f, -1.1f); EXPECT_EQ(RectF(1.1f, 2.2f, 3.3f, 4.4f), f); } TEST(RectTest, Corners) { Rect i(1, 2, 3, 4); RectF f(1.1f, 2.1f, 3.1f, 4.1f); EXPECT_EQ(Point(1, 2), i.origin()); EXPECT_EQ(Point(4, 2), i.top_right()); EXPECT_EQ(Point(1, 6), i.bottom_left()); EXPECT_EQ(Point(4, 6), i.bottom_right()); EXPECT_EQ(PointF(1.1f, 2.1f), f.origin()); EXPECT_EQ(PointF(4.2f, 2.1f), f.top_right()); EXPECT_EQ(PointF(1.1f, 6.2f), f.bottom_left()); EXPECT_EQ(PointF(4.2f, 6.2f), f.bottom_right()); } TEST(RectTest, Centers) { Rect i(10, 20, 30, 40); EXPECT_EQ(Point(10, 40), i.left_center()); EXPECT_EQ(Point(25, 20), i.top_center()); EXPECT_EQ(Point(40, 40), i.right_center()); EXPECT_EQ(Point(25, 60), i.bottom_center()); RectF f(10.1f, 20.2f, 30.3f, 40.4f); EXPECT_EQ(PointF(10.1f, 40.4f), f.left_center()); EXPECT_EQ(PointF(25.25f, 20.2f), f.top_center()); EXPECT_EQ(PointF(40.4f, 40.4f), f.right_center()); EXPECT_EQ(25.25f, f.bottom_center().x()); EXPECT_NEAR(60.6f, f.bottom_center().y(), 0.001f); } TEST(RectTest, Transpose) { Rect i(10, 20, 30, 40); i.Transpose(); EXPECT_EQ(Rect(20, 10, 40, 30), i); RectF f(10.1f, 20.2f, 30.3f, 40.4f); f.Transpose(); EXPECT_EQ(RectF(20.2f, 10.1f, 40.4f, 30.3f), f); } TEST(RectTest, ManhattanDistanceToPoint) { Rect i(1, 2, 3, 4); EXPECT_EQ(0, i.ManhattanDistanceToPoint(Point(1, 2))); EXPECT_EQ(0, i.ManhattanDistanceToPoint(Point(4, 6))); EXPECT_EQ(0, i.ManhattanDistanceToPoint(Point(2, 4))); EXPECT_EQ(3, i.ManhattanDistanceToPoint(Point(0, 0))); EXPECT_EQ(2, i.ManhattanDistanceToPoint(Point(2, 0))); EXPECT_EQ(3, i.ManhattanDistanceToPoint(Point(5, 0))); EXPECT_EQ(1, i.ManhattanDistanceToPoint(Point(5, 4))); EXPECT_EQ(3, i.ManhattanDistanceToPoint(Point(5, 8))); EXPECT_EQ(2, i.ManhattanDistanceToPoint(Point(3, 8))); EXPECT_EQ(2, i.ManhattanDistanceToPoint(Point(0, 7))); EXPECT_EQ(1, i.ManhattanDistanceToPoint(Point(0, 3))); RectF f(1.1f, 2.1f, 3.1f, 4.1f); EXPECT_FLOAT_EQ(0.f, f.ManhattanDistanceToPoint(PointF(1.1f, 2.1f))); EXPECT_FLOAT_EQ(0.f, f.ManhattanDistanceToPoint(PointF(4.2f, 6.f))); EXPECT_FLOAT_EQ(0.f, f.ManhattanDistanceToPoint(PointF(2.f, 4.f))); EXPECT_FLOAT_EQ(3.2f, f.ManhattanDistanceToPoint(PointF(0.f, 0.f))); EXPECT_FLOAT_EQ(2.1f, f.ManhattanDistanceToPoint(PointF(2.f, 0.f))); EXPECT_FLOAT_EQ(2.9f, f.ManhattanDistanceToPoint(PointF(5.f, 0.f))); EXPECT_FLOAT_EQ(.8f, f.ManhattanDistanceToPoint(PointF(5.f, 4.f))); EXPECT_FLOAT_EQ(2.6f, f.ManhattanDistanceToPoint(PointF(5.f, 8.f))); EXPECT_FLOAT_EQ(1.8f, f.ManhattanDistanceToPoint(PointF(3.f, 8.f))); EXPECT_FLOAT_EQ(1.9f, f.ManhattanDistanceToPoint(PointF(0.f, 7.f))); EXPECT_FLOAT_EQ(1.1f, f.ManhattanDistanceToPoint(PointF(0.f, 3.f))); } TEST(RectTest, ManhattanInternalDistance) { Rect i(0, 0, 400, 400); EXPECT_EQ(0, i.ManhattanInternalDistance(gfx::Rect(-1, 0, 2, 1))); EXPECT_EQ(1, i.ManhattanInternalDistance(gfx::Rect(400, 0, 1, 400))); EXPECT_EQ(2, i.ManhattanInternalDistance(gfx::Rect(-100, -100, 100, 100))); EXPECT_EQ(2, i.ManhattanInternalDistance(gfx::Rect(-101, 100, 100, 100))); EXPECT_EQ(4, i.ManhattanInternalDistance(gfx::Rect(-101, -101, 100, 100))); EXPECT_EQ(435, i.ManhattanInternalDistance(gfx::Rect(630, 603, 100, 100))); RectF f(0.0f, 0.0f, 400.0f, 400.0f); static const float kEpsilon = std::numeric_limits::epsilon(); EXPECT_FLOAT_EQ( 0.0f, f.ManhattanInternalDistance(gfx::RectF(-1.0f, 0.0f, 2.0f, 1.0f))); EXPECT_FLOAT_EQ(kEpsilon, f.ManhattanInternalDistance( gfx::RectF(400.0f, 0.0f, 1.0f, 400.0f))); EXPECT_FLOAT_EQ(2.0f * kEpsilon, f.ManhattanInternalDistance(gfx::RectF( -100.0f, -100.0f, 100.0f, 100.0f))); EXPECT_FLOAT_EQ(1.0f + kEpsilon, f.ManhattanInternalDistance(gfx::RectF( -101.0f, 100.0f, 100.0f, 100.0f))); EXPECT_FLOAT_EQ(2.0f + 2.0f * kEpsilon, f.ManhattanInternalDistance( gfx::RectF(-101.0f, -101.0f, 100.0f, 100.0f))); EXPECT_FLOAT_EQ( 433.0f + 2.0f * kEpsilon, f.ManhattanInternalDistance(gfx::RectF(630.0f, 603.0f, 100.0f, 100.0f))); EXPECT_FLOAT_EQ( 0.0f, f.ManhattanInternalDistance(gfx::RectF(-1.0f, 0.0f, 1.1f, 1.0f))); EXPECT_FLOAT_EQ(0.1f + kEpsilon, f.ManhattanInternalDistance( gfx::RectF(-1.5f, 0.0f, 1.4f, 1.0f))); EXPECT_FLOAT_EQ(kEpsilon, f.ManhattanInternalDistance( gfx::RectF(-1.5f, 0.0f, 1.5f, 1.0f))); } TEST(RectTest, IntegerOverflow) { int limit = std::numeric_limits::max(); int min_limit = std::numeric_limits::min(); int expected = 10; int large_number = limit - expected; Rect height_overflow(0, large_number, 100, 100); EXPECT_EQ(large_number, height_overflow.y()); EXPECT_EQ(expected, height_overflow.height()); Rect width_overflow(large_number, 0, 100, 100); EXPECT_EQ(large_number, width_overflow.x()); EXPECT_EQ(expected, width_overflow.width()); Rect size_height_overflow(Point(0, large_number), Size(100, 100)); EXPECT_EQ(large_number, size_height_overflow.y()); EXPECT_EQ(expected, size_height_overflow.height()); Rect size_width_overflow(Point(large_number, 0), Size(100, 100)); EXPECT_EQ(large_number, size_width_overflow.x()); EXPECT_EQ(expected, size_width_overflow.width()); Rect set_height_overflow(0, large_number, 100, 5); EXPECT_EQ(5, set_height_overflow.height()); set_height_overflow.set_height(100); EXPECT_EQ(expected, set_height_overflow.height()); Rect set_y_overflow(100, 100, 100, 100); EXPECT_EQ(100, set_y_overflow.height()); set_y_overflow.set_y(large_number); EXPECT_EQ(expected, set_y_overflow.height()); Rect set_width_overflow(large_number, 0, 5, 100); EXPECT_EQ(5, set_width_overflow.width()); set_width_overflow.set_width(100); EXPECT_EQ(expected, set_width_overflow.width()); Rect set_x_overflow(100, 100, 100, 100); EXPECT_EQ(100, set_x_overflow.width()); set_x_overflow.set_x(large_number); EXPECT_EQ(expected, set_x_overflow.width()); Point large_offset(large_number, large_number); Size size(100, 100); Size expected_size(10, 10); Rect set_origin_overflow(100, 100, 100, 100); EXPECT_EQ(size, set_origin_overflow.size()); set_origin_overflow.set_origin(large_offset); EXPECT_EQ(large_offset, set_origin_overflow.origin()); EXPECT_EQ(expected_size, set_origin_overflow.size()); Rect set_size_overflow(large_number, large_number, 5, 5); EXPECT_EQ(Size(5, 5), set_size_overflow.size()); set_size_overflow.set_size(size); EXPECT_EQ(large_offset, set_size_overflow.origin()); EXPECT_EQ(expected_size, set_size_overflow.size()); Rect set_rect_overflow; set_rect_overflow.SetRect(large_number, large_number, 100, 100); EXPECT_EQ(large_offset, set_rect_overflow.origin()); EXPECT_EQ(expected_size, set_rect_overflow.size()); // Insetting an empty rect, but the total inset (left + right) could overflow. Rect inset_overflow; inset_overflow.Inset(large_number, large_number, 100, 100); EXPECT_EQ(large_offset, inset_overflow.origin()); EXPECT_EQ(gfx::Size(), inset_overflow.size()); // Insetting where the total inset (width - left - right) could overflow. // Also, this insetting by the min limit in all directions cannot // represent width() without overflow, so that will also clamp. Rect inset_overflow2; inset_overflow2.Inset(min_limit, min_limit, min_limit, min_limit); EXPECT_EQ(inset_overflow2, gfx::Rect(min_limit, min_limit, limit, limit)); // Insetting where the width shouldn't change, but if the insets operations // clamped in the wrong order, e.g. ((width - left) - right) vs (width - (left // + right)) then this will not work properly. This is the proper order, // as if left + right overflows, the width cannot be decreased by more than // max int anyway. Additionally, if left + right underflows, it cannot be // increased by more then max int. Rect inset_overflow3(0, 0, limit, limit); inset_overflow3.Inset(-100, -100, 100, 100); EXPECT_EQ(inset_overflow3, gfx::Rect(-100, -100, limit, limit)); Rect inset_overflow4(-1000, -1000, limit, limit); inset_overflow4.Inset(100, 100, -100, -100); EXPECT_EQ(inset_overflow4, gfx::Rect(-900, -900, limit, limit)); Rect offset_overflow(0, 0, 100, 100); offset_overflow.Offset(large_number, large_number); EXPECT_EQ(large_offset, offset_overflow.origin()); EXPECT_EQ(expected_size, offset_overflow.size()); Rect operator_overflow(0, 0, 100, 100); operator_overflow += Vector2d(large_number, large_number); EXPECT_EQ(large_offset, operator_overflow.origin()); EXPECT_EQ(expected_size, operator_overflow.size()); Rect origin_maxint(limit, limit, limit, limit); EXPECT_EQ(origin_maxint, Rect(gfx::Point(limit, limit), gfx::Size())); // Expect a rect at the origin and a rect whose right/bottom is maxint // create a rect that extends from 0..maxint in both extents. { Rect origin_small(0, 0, 100, 100); Rect big_clamped(50, 50, limit, limit); EXPECT_EQ(big_clamped.right(), limit); Rect unioned = UnionRects(origin_small, big_clamped); Rect rect_limit(0, 0, limit, limit); EXPECT_EQ(unioned, rect_limit); } // Expect a rect that would overflow width (but not right) to be clamped // and to have maxint extents after unioning. { Rect small(-500, -400, 100, 100); Rect big(-400, -500, limit, limit); // Technically, this should be limit + 100 width, but will clamp to maxint. EXPECT_EQ(UnionRects(small, big), Rect(-500, -500, limit, limit)); } // Expect a rect that would overflow right *and* width to be clamped. { Rect clamped(500, 500, limit, limit); Rect positive_origin(100, 100, 500, 500); // Ideally, this should be (100, 100, limit + 400, limit + 400). // However, width overflows and would be clamped to limit, but right // overflows too and so will be clamped to limit - 100. Rect expected(100, 100, limit - 100, limit - 100); EXPECT_EQ(UnionRects(clamped, positive_origin), expected); } // Unioning a left=minint rect with a right=maxint rect. // We can't represent both ends of the spectrum in the same rect. // Make sure we keep the most useful area. { int part_limit = min_limit / 3; Rect left_minint(min_limit, min_limit, 1, 1); Rect right_maxint(limit - 1, limit - 1, limit, limit); Rect expected(part_limit, part_limit, 2 * part_limit, 2 * part_limit); Rect result = UnionRects(left_minint, right_maxint); // The result should be maximally big. EXPECT_EQ(limit, result.height()); EXPECT_EQ(limit, result.width()); // The result should include the area near the origin. EXPECT_GT(-part_limit, result.x()); EXPECT_LT(part_limit, result.right()); EXPECT_GT(-part_limit, result.y()); EXPECT_LT(part_limit, result.bottom()); // More succinctly, but harder to read in the results. EXPECT_TRUE(UnionRects(left_minint, right_maxint).Contains(expected)); } } TEST(RectTest, ScaleToEnclosingRectSafe) { const int max_int = std::numeric_limits::max(); const int min_int = std::numeric_limits::min(); const float max_float = std::numeric_limits::max(); Rect xy_underflow(-100000, -123456, 10, 20); EXPECT_EQ(ScaleToEnclosingRectSafe(xy_underflow, 100000, 100000), Rect(min_int, min_int, 1000000, 2000000)); // A location overflow means that width/right and bottom/top also // overflow so need to be clamped. Rect xy_overflow(100000, 123456, 10, 20); EXPECT_EQ(ScaleToEnclosingRectSafe(xy_overflow, 100000, 100000), Rect(max_int, max_int, 0, 0)); // In practice all rects are clamped to 0 width / 0 height so // negative sizes don't matter, but try this for the sake of testing. Rect size_underflow(-1, -2, 100000, 100000); EXPECT_EQ(ScaleToEnclosingRectSafe(size_underflow, -100000, -100000), Rect(100000, 200000, 0, 0)); Rect size_overflow(-1, -2, 123456, 234567); EXPECT_EQ(ScaleToEnclosingRectSafe(size_overflow, 100000, 100000), Rect(-100000, -200000, max_int, max_int)); // Verify width/right gets clamped properly too if x/y positive. Rect size_overflow2(1, 2, 123456, 234567); EXPECT_EQ(ScaleToEnclosingRectSafe(size_overflow2, 100000, 100000), Rect(100000, 200000, max_int - 100000, max_int - 200000)); Rect max_rect(max_int, max_int, max_int, max_int); EXPECT_EQ(ScaleToEnclosingRectSafe(max_rect, max_float, max_float), Rect(max_int, max_int, 0, 0)); Rect min_rect(min_int, min_int, max_int, max_int); // Min rect can't be scaled up any further in any dimension. EXPECT_EQ(ScaleToEnclosingRectSafe(min_rect, 2, 3.5), min_rect); EXPECT_EQ(ScaleToEnclosingRectSafe(min_rect, max_float, max_float), min_rect); // Min rect scaled by min is an empty rect at (max, max) EXPECT_EQ(ScaleToEnclosingRectSafe(min_rect, min_int, min_int), max_rect); } } // namespace gfx ",16130,True,2656.7258715095354,median "filedesc://BnF-elec2007-20070524113301-00040-heritrix1.arc 0.0.0.0 20070524113301 text/plain 22566 1 1 InternetArchive URL IP-address Archive-date Content-type Archive-length Heritrix 1.10.1 http://crawler.archive.org heritrix1 172.23.129.203 elec2007-20070521103628-f1.desirsdav Domain, deciding scope, excl-filter, delay-factor: 4->2, min-delay: 2000->500, max-delay: 20000->2000, pool-max-active: 5->1 Admin, ignore robots.txt !!! atlas0 f1.24 2007-05-21T12:22:23+00:00 Mozilla/5.0 (compatible; heritrix/1.10.1 +http://bibnum.bnf.fr/robot/) robot@bnf.fr ignore ARC file version 1.1 http://www.archive.org/web/researcher/ArcFileFormat.php http://www.desirsdavenir.org/debats/read.php?52,36115,36115 217.174.222.107 20070524113300 text/html 20844 HTTP/1.0 200 OK Date: Thu, 24 May 2007 11:37:38 GMT Server: Apache/1.3.33 (Debian GNU/Linux) PHP/4.4.6-0.dotdeb.2 with Suhosin-Patch X-Powered-By: PHP/4.4.6-0.dotdeb.2 Content-Type: text/html; charset=iso-8859-1 X-Cache: MISS from proxy1-2.bnf.fr Proxy-Connection: close Désirs d'avenir :: Soutiens :: carte scolaired et mixité sociale
 
Accueil  >  S'informer >  Forums





Soutiens
 
Si vous souhaitez écrire un message de soutien à Ségolène Royal et à son équipe




carte scolaired et mixité sociale
Message de essertois le Date à 10/09/06 20:21

LAISSER LE CHOIX ENTRE PLUSIEURS ETABLISSEMENTS ( élargir la sectorisation).
ATTENTION!POINT DE VUE D'UN EX PRINCIPAL DE ZEP
"" Elargir la sectorisation me paraît être une proposition dangereuse:
* On n'empêchera pas la RUMEUR de classer les établissements: pour avoir exercé des responsabilités dans un collège ""bourgeois"", puis dans un collège ZEP, je me suis aperçu que, dans le cas d'un collège ZEP, avec une équipe motivée, les enseignements étaient beaucoup mieux adaptés et les solutions souvent très positives: mais la population ne le sait pas, et c'est très difficile de la convaincre(il y faut de l'énergie et du temps).
* le problème des transports scolaires est aussi lié à ces choix, et, en élargissant les sectorisations, on devra tôt ou tard multiplier les transport en fonction de nouveaux besoins ou laisser la place à l'initiative privée, donc à l'argent.
QUELQUES PISTES:
- nécessité de redéfinir les secteurs scolaires d'une manière moins ségrégative;
- définir de vrais moyens d'excellence pour les collèges en ZEP:calcul du H/E en fonction de l'effectif total accueilli+bonification définie par commisssion paritaire;moyens matériels majorés; mise en place d'études dirigées; création de sections "" attirantes"" car réputées nobles. Parallèlement, pour les collèges non ZEP°, calcul du H/E en fonction du seul effectif relevant du secteur de recrutement de la 6ème à la 3ème, ce qui éviterait la "" chasse"" aux bons élèves hors du secteur de recrutement.
- éviter les collèges de plus de 600 élèves( voir la réfrorme ""Legrand"").



Sujet  

carte scolaired et mixité sociale

 
",8001,False,1487.5587275905812,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 //// = Testing Your Application include::./attributes.adoc[] :toc: macro :toclevels: 4 :doctype: book :icons: font :docinfo1: :numbered: :sectnums: :sectnumlevels: 4 Learn how to test your Quarkus Application. This guide covers: * Testing in JVM mode * Testing in native mode * Injection of resources into tests == Prerequisites include::{includes}/prerequisites.adoc[] * The completed greeter application from the xref:getting-started.adoc[Getting Started Guide] == Architecture In this guide, we expand on the initial test that was created as part of the Getting Started Guide. We cover injection into tests and also how to test native executables. NOTE: Quarkus supports Continuous testing, but this is covered by the xref:continuous-testing.adoc[Continuous Testing Guide]. == Solution We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example. Clone the Git repository: `git clone {quickstarts-clone-url}`, or download an {quickstarts-archive-url}[archive]. The solution is located in the `getting-started-testing` {quickstarts-tree-url}/getting-started-testing[directory]. This guide assumes you already have the completed application from the `getting-started` directory. == Recap of HTTP based Testing in JVM mode If you have started from the Getting Started example you should already have a completed test, including the correct tooling setup. In your build file you should see 2 test dependencies: [role=""primary asciidoc-tabs-sync-maven""] .Maven **** [source,xml,subs=attributes+] ---- io.quarkus quarkus-junit5 test io.rest-assured rest-assured test ---- **** [role=""secondary asciidoc-tabs-sync-gradle""] .Gradle **** [source,groovy,subs=attributes+] ---- dependencies { testImplementation(""io.quarkus:quarkus-junit5"") testImplementation(""io.rest-assured:rest-assured"") } ---- **** `quarkus-junit5` is required for testing, as it provides the `@QuarkusTest` annotation that controls the testing framework. `rest-assured` is not required but is a convenient way to test HTTP endpoints, we also provide integration that automatically sets the correct URL so no configuration is required. Because we are using JUnit 5, the version of the https://maven.apache.org/surefire/maven-surefire-plugin/[Surefire Maven Plugin] must be set, as the default version does not support Junit 5: [source,xml,subs=attributes+] ---- maven-surefire-plugin ${surefire-plugin.version} org.jboss.logmanager.LogManager ${maven.home} ---- We also set the `java.util.logging.manager` system property to make sure tests will use the correct logmanager and `maven.home` to ensure that custom configuration from `${maven.home}/conf/settings.xml` is applied (if any). The project should also contain a simple test: [source,java] ---- package org.acme.getting.started.testing; import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.Test; import java.util.UUID; import static io.restassured.RestAssured.given; import static org.hamcrest.CoreMatchers.is; @QuarkusTest public class GreetingResourceTest { @Test public void testHelloEndpoint() { given() .when().get(""/hello"") .then() .statusCode(200) .body(is(""hello"")); } @Test public void testGreetingEndpoint() { String uuid = UUID.randomUUID().toString(); given() .pathParam(""name"", uuid) .when().get(""/hello/greeting/{name}"") .then() .statusCode(200) .body(is(""hello "" + uuid)); } } ---- This test uses HTTP to directly test our REST endpoint. When the test is run the application will be started before the test is run. === Controlling the test port While Quarkus will listen on port `8080` by default, when running tests it defaults to `8081`. This allows you to run tests while having the application running in parallel. [TIP] .Changing the test port ==== You can configure the ports used by tests by configuring `quarkus.http.test-port` for HTTP and `quarkus.http.test-ssl-port` for HTTPS in your `application.properties`: [source] ---- quarkus.http.test-port=8083 quarkus.http.test-ssl-port=8446 ---- `0` will result in the use of a random port (assigned by the operating system). ==== Quarkus also provides RestAssured integration that updates the default port used by RestAssured before the tests are run, so no additional configuration should be required. === Controlling HTTP interaction timeout When using REST Assured in your test, the connection and response timeouts are set to 30 seconds. You can override this setting with the `quarkus.http.test-timeout` property: [source] ---- quarkus.http.test-timeout=10s ---- === Injecting a URI It is also possible to directly inject the URL into the test which can make is easy to use a different client. This is done via the `@TestHTTPResource` annotation. Let's write a simple test that shows this off to load some static resources. First create a simple HTML file in `src/main/resources/META-INF/resources/index.html` : [source,xml] ---- Testing Guide Information about testing ---- We will create a simple test to ensure that this is being served correctly: [source,java] ---- package org.acme.getting.started.testing; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import io.quarkus.test.common.http.TestHTTPResource; import io.quarkus.test.junit.QuarkusTest; @QuarkusTest public class StaticContentTest { @TestHTTPResource(""index.html"") // <1> URL url; @Test public void testIndexHtml() throws IOException { try (InputStream in = url.openStream()) { String contents = new String(in.readAllBytes(), StandardCharsets.UTF_8); Assertions.assertTrue(contents.contains(""Testing Guide"")); } } } ---- <1> This annotation allows you to directly inject the URL of the Quarkus instance, the value of the annotation will be the path component of the URL For now `@TestHTTPResource` allows you to inject `URI`, `URL` and `String` representations of the URL. == Testing a specific endpoint Both RESTassured and `@TestHTTPResource` allow you to specify the endpoint class you are testing rather than hard coding a path. This currently supports both JAX-RS endpoints, Servlets and Reactive Routes. This makes it a lot easier to see exactly which endpoints a given test is testing. For the purposes of these examples I am going to assume we have an endpoint that looks like the following: [source,java] ---- @Path(""/hello"") public class GreetingResource { @GET @Produces(MediaType.TEXT_PLAIN) public String hello() { return ""hello""; } } ---- NOTE: This currently does not support the `@ApplicationPath()` annotation to set the JAX-RS context path. Use the `quarkus.resteasy.path` config value instead if you want a custom context path. === TestHTTPResource You can the use the `io.quarkus.test.common.http.TestHTTPEndpoint` annotation to specify the endpoint path, and the path will be extracted from the provided endpoint. If you also specify a value for the `TestHTTPResource` endpoint it will be appended to the end of the endpoint path. [source,java] ---- package org.acme.getting.started.testing; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import io.quarkus.test.common.http.TestHTTPEndpoint; import io.quarkus.test.common.http.TestHTTPResource; import io.quarkus.test.junit.QuarkusTest; @QuarkusTest public class StaticContentTest { @TestHTTPEndpoint(GreetingResource.class) // <1> @TestHTTPResource URL url; @Test public void testIndexHtml() throws IOException { try (InputStream in = url.openStream()) { String contents = new String(in.readAllBytes(), StandardCharsets.UTF_8); Assertions.assertEquals(""hello"", contents); } } } ---- <1> Because `GreetingResource` is annotated with `@Path(""/hello"")` the injected URL will end with `/hello`. === RESTassured To control the RESTassured base path (i.e. the default path that serves as the root for every request) you can use the `io.quarkus.test.common.http.TestHTTPEndpoint` annotation. This can be applied at the class or method level. To test out greeting resource we would do: [source,java] ---- package org.acme.getting.started.testing; import io.quarkus.test.junit.QuarkusTest; import io.quarkus.test.common.http.TestHTTPEndpoint; import org.junit.jupiter.api.Test; import java.util.UUID; import static io.restassured.RestAssured.when; import static org.hamcrest.CoreMatchers.is; @QuarkusTest @TestHTTPEndpoint(GreetingResource.class) //<1> public class GreetingResourceTest { @Test public void testHelloEndpoint() { when().get() //<2> .then() .statusCode(200) .body(is(""hello"")); } } ---- <1> This tells RESTAssured to prefix all requests with `/hello`. <2> Note we don't need to specify a path here, as `/hello` is the default for this test == Injection into tests So far we have only covered integration style tests that test the app via HTTP endpoints, but what if we want to do unit testing and test our beans directly? Quarkus supports this by allowing you to inject CDI beans into your tests via the `@Inject` annotation (in fact, tests in Quarkus are full CDI beans, so you can use all CDI functionality). Let's create a simple test that tests the greeting service directly without using HTTP: [source,java] ---- package org.acme.getting.started.testing; import javax.inject.Inject; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import io.quarkus.test.junit.QuarkusTest; @QuarkusTest public class GreetingServiceTest { @Inject // <1> GreetingService service; @Test public void testGreetingService() { Assertions.assertEquals(""hello Quarkus"", service.greeting(""Quarkus"")); } } ---- <1> The `GreetingService` bean will be injected into the test == Applying Interceptors to Tests As mentioned above Quarkus tests are actually full CDI beans, and as such you can apply CDI interceptors as you would normally. As an example, if you want a test method to run within the context of a transaction you can simply apply the `@Transactional` annotation to the method and the transaction interceptor will handle it. In addition to this you can also create your own test stereotypes. For example we could create a `@TransactionalQuarkusTest` as follows: [source,java] ---- @QuarkusTest @Stereotype @Transactional @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface TransactionalQuarkusTest { } ---- If we then apply this annotation to a test class it will act as if we had applied both the `@QuarkusTest` and `@Transactional` annotations, e.g.: [source,java] ---- @TransactionalQuarkusTest public class TestStereotypeTestCase { @Inject UserTransaction userTransaction; @Test public void testUserTransaction() throws Exception { Assertions.assertEquals(Status.STATUS_ACTIVE, userTransaction.getStatus()); } } ---- == Tests and Transactions You can use the standard Quarkus `@Transactional` annotation on tests, but this means that the changes your test makes to the database will be persistent. If you want any changes made to be rolled back at the end of the test you can use the `io.quarkus.test.TestTransaction` annotation. This will run the test method in a transaction, but roll it back once the test method is complete to revert any database changes. == Enrichment via QuarkusTest*Callback Alternatively or additionally to an interceptor, you can enrich *all* your `@QuarkusTest` classes by implementing the following callback interfaces: * `io.quarkus.test.junit.callback.QuarkusTestBeforeClassCallback` * `io.quarkus.test.junit.callback.QuarkusTestAfterConstructCallback` * `io.quarkus.test.junit.callback.QuarkusTestBeforeEachCallback` * `io.quarkus.test.junit.callback.QuarkusTestAfterEachCallback` Such a callback implementation has to be registered as a ""service provider"" as defined by `java.util.ServiceLoader`. E.g. the following sample callback: [source,java] ---- package org.acme.getting.started.testing; import io.quarkus.test.junit.callback.QuarkusTestBeforeEachCallback; import io.quarkus.test.junit.callback.QuarkusTestMethodContext; public class MyQuarkusTestBeforeEachCallback implements QuarkusTestBeforeEachCallback { @Override public void beforeEach(QuarkusTestMethodContext context) { System.out.println(""Executing "" + context.getTestMethod()); } } ---- has to be registered via `src/main/resources/META-INF/services/io.quarkus.test.junit.callback.QuarkusTestBeforeEachCallback` as follows: [source] ---- org.acme.getting.started.testing.MyQuarkusTestBeforeEachCallback ---- TIP: It is possible to read annotations from the test class or method to control what the callback shall be doing. WARNING: While it is possible to use JUnit Jupiter callback interfaces like `BeforeEachCallback`, you might run into classloading issues because Quarkus has to run tests in a custom classloader which JUnit is not aware of. [[testing_different_profiles]] == Testing Different Profiles So far in all our examples we only start Quarkus once for all tests. Before the first test is run Quarkus will boot, then all tests will run, then Quarkus will shutdown at the end. This makes for a very fast testing experience however it is a bit limited as you can't test different configurations. To get around this Quarkus supports the idea of a test profile. If a test has a different profile to the previously run test then Quarkus will be shut down and started with the new profile before running the tests. This is obviously a bit slower, as it adds a shutdown/startup cycle to the test time, but gives a great deal of flexibility. To reduce the amount of times Quarkus needs to restart, `io.quarkus.test.junit.util.QuarkusTestProfileAwareClassOrderer` is registered as a global `ClassOrderer` as described in the link:https://junit.org/junit5/docs/current/user-guide/#writing-tests-test-execution-order-classes[JUnit 5 User Guide]. The behavior of this orderer is configurable via `junit-platform.properties` (see the source code or javadoc for more details). It can also be disabled entirely by setting another orderer that is provided by JUnit 5 or even your own custom one. + Please note that as of JUnit 5.8.2 link:https://github.com/junit-team/junit5/issues/2794[only a single `junit-platform.properties` is picked up and a warning is logged if more than one is found]. If you encounter such warnings, you can can get rid of them by removing the Quarkus-supplied `junit-platform.properties` from the classpath via an exclusion: [source,xml] ---- io.quarkus quarkus-junit5 test io.quarkus quarkus-junit5-properties ---- === Writing a Profile To implement a test profile we need to implement `io.quarkus.test.junit.QuarkusTestProfile`: [source,java] ---- package org.acme.getting.started.testing; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import io.quarkus.test.junit.QuarkusTestProfile; import io.quarkus.test.junit.QuarkusTestProfile.TestResourceEntry; public class MockGreetingProfile implements QuarkusTestProfile { <1> /** * Returns additional config to be applied to the test. This * will override any existing config (including in application.properties), * however existing config will be merged with this (i.e. application.properties * config will still take effect, unless a specific config key has been overridden). * * Here we are changing the JAX-RS root path. */ @Override public Map getConfigOverrides() { return Collections.singletonMap(""quarkus.resteasy.path"",""/api""); } /** * Returns enabled alternatives. * * This has the same effect as setting the 'quarkus.arc.selected-alternatives' config key, * however it may be more convenient. */ @Override public Set> getEnabledAlternatives() { return Collections.singleton(MockGreetingService.class); } /** * Allows the default config profile to be overridden. This basically just sets the quarkus.test.profile system * property before the test is run. * * Here we are setting the profile to test-mocked */ @Override public String getConfigProfile() { return ""test-mocked""; } /** * Additional {@link QuarkusTestResourceLifecycleManager} classes (along with their init params) to be used from this * specific test profile. * * If this method is not overridden, then only the {@link QuarkusTestResourceLifecycleManager} classes enabled via the {@link io.quarkus.test.common.QuarkusTestResource} class * annotation will be used for the tests using this profile (which is the same behavior as tests that don't use a profile at all). */ @Override public List testResources() { return Collections.singletonList(new TestResourceEntry(CustomWireMockServerManager.class)); } /** * If this returns true then only the test resources returned from {@link #testResources()} will be started, * global annotated test resources will be ignored. */ @Override public boolean disableGlobalTestResources() { return false; } /** * The tags this profile is associated with. * When the {@code quarkus.test.profile.tags} System property is set (its value is a comma separated list of strings) * then Quarkus will only execute tests that are annotated with a {@code @TestProfile} that has at least one of the * supplied (via the aforementioned system property) tags. */ @Override public Set tags() { return Collections.emptySet(); } /** * The command line parameters that are passed to the main method on startup. */ @Override public String[] commandLineParameters() { return new String[0]; } /** * If the main method should be run. */ @Override public boolean runMainMethod() { return false; } /** * If this method returns true then all {@code StartupEvent} and {@code ShutdownEvent} observers declared on application * beans should be disabled. */ @Override public boolean disableApplicationLifecycleObservers() { return false; } } ---- <1> All these methods have default implementations so just override the ones you need to override. Now we have defined our profile we need to include it on our test class. We do this by annotating the test class with `@TestProfile(MockGreetingProfile.class)`. All the test profile configuration is stored in a single class, which makes it easy to tell if the previous test ran with the same configuration. === Running specific tests Quarkus provides the ability to limit test execution to tests with specific `@TestProfile` annotations. This works by leveraging the `tags` method of `QuarkusTestProfile` in conjunction with the `quarkus.test.profile.tags` system property. Essentially, any `QuarkusTestProfile` with at least one matching tag matching the value of `quarkus.test.profile.tags` will be considered active and all the tests annotated with `@TestProfile` of active profiles, will be run while the rest will be skipped. This is best shown in the following example. First let's define a few `QuarkusTestProfile` implementations like so: [source,java] ---- public class Profiles { public static class NoTags implements QuarkusTestProfile { } public static class SingleTag implements QuarkusTestProfile { @Override public Set tags() { return Collections.singleton(""test1""); } } public static class MultipleTags implements QuarkusTestProfile { @Override public Set tags() { return new HashSet<>(Arrays.asList(""test1"", ""test2"")); } } } ---- Now let's assume that we have the following tests: [source,java] ---- @QuarkusTest public class NoQuarkusProfileTest { @Test public void test() { // test something } } ---- [source,java] ---- @QuarkusTest @TestProfile(Profiles.NoTags.class) public class NoTagsTest { @Test public void test() { // test something } } ---- [source,java] ---- @QuarkusTest @TestProfile(Profiles.SingleTag.class) public class SingleTagTest { @Test public void test() { // test something } } ---- [source,java] ---- @QuarkusTest @TestProfile(Profiles.MultipleTags.class) public class MultipleTagsTest { @Test public void test() { // test something } } ---- Let's consider the following scenarios: * `quarkus.test.profile.tags` is not set: All tests will be executed. * `quarkus.test.profile.tags=foo`: In this case none of tests will be executed because none of the tags defined on the `QuarkusTestProfile` implementations match the value of `quarkus.test.profile.tags`. Note that `NoQuarkusProfileTest` is not executed either because it is not annotated with `@TestProfile`. * `quarkus.test.profile.tags=test1`: In this case `SingleTagTest` and `MultipleTagsTest` will be run because the tags on their respective `QuarkusTestProfile` implementations match the value of `quarkus.test.profile.tags`. * `quarkus.test.profile.tags=test1,test3`: This case results in the same tests being executed as the previous case. * `quarkus.test.profile.tags=test2,test3`: In this case only `MultipleTagsTest` will be run because `MultipleTagsTest` is the only `QuarkusTestProfile` implementation whose `tags` method matches the value of `quarkus.test.profile.tags`. == Mock Support Quarkus supports the use of mock objects using two different approaches. You can either use CDI alternatives to mock out a bean for all test classes, or use `QuarkusMock` to mock out beans on a per test basis. === CDI `@Alternative` mechanism. To use this simply override the bean you wish to mock with a class in the `src/test/java` directory, and put the `@Alternative` and `@Priority(1)` annotations on the bean. Alternatively, a convenient `io.quarkus.test.Mock` stereotype annotation could be used. This built-in stereotype declares `@Alternative`, `@Priority(1)` and `@Dependent`. For example if I have the following service: [source,java] ---- @ApplicationScoped public class ExternalService { public String service() { return ""external""; } } ---- I could mock it with the following class in `src/test/java`: [source,java] ---- @Mock @ApplicationScoped // <1> public class MockExternalService extends ExternalService { @Override public String service() { return ""mock""; } } ---- <1> Overrides the `@Dependent` scope declared on the `@Mock` stereotype. It is important that the alternative be present in the `src/test/java` directory rather than `src/main/java`, as otherwise it will take effect all the time, not just when testing. Note that at present this approach does not work with native image testing, as this would required the test alternatives to be baked into the native image. [[quarkus_mock]] === Mocking using QuarkusMock The `io.quarkus.test.junit.QuarkusMock` class can be used to temporarily mock out any normal scoped bean. If you use this method in a `@BeforeAll` method the mock will take effect for all tests on the current class, while if you use this in a test method the mock will only take effect for the duration of the current test. This method can be used for any normal scoped CDI bean (e.g. `@ApplicationScoped`, `@RequestScoped` etc, basically every scope except `@Singleton` and `@Dependent`). An example usage could look like: [source,java] ---- @QuarkusTest public class MockTestCase { @Inject MockableBean1 mockableBean1; @Inject MockableBean2 mockableBean2; @BeforeAll public static void setup() { MockableBean1 mock = Mockito.mock(MockableBean1.class); Mockito.when(mock.greet(""Stuart"")).thenReturn(""A mock for Stuart""); QuarkusMock.installMockForType(mock, MockableBean1.class); // <1> } @Test public void testBeforeAll() { Assertions.assertEquals(""A mock for Stuart"", mockableBean1.greet(""Stuart"")); Assertions.assertEquals(""Hello Stuart"", mockableBean2.greet(""Stuart"")); } @Test public void testPerTestMock() { QuarkusMock.installMockForInstance(new BonjourGreeter(), mockableBean2); // <2> Assertions.assertEquals(""A mock for Stuart"", mockableBean1.greet(""Stuart"")); Assertions.assertEquals(""Bonjour Stuart"", mockableBean2.greet(""Stuart"")); } @ApplicationScoped public static class MockableBean1 { public String greet(String name) { return ""Hello "" + name; } } @ApplicationScoped public static class MockableBean2 { public String greet(String name) { return ""Hello "" + name; } } public static class BonjourGreeter extends MockableBean2 { @Override public String greet(String name) { return ""Bonjour "" + name; } } } ---- <1> As the injected instance is not available here we use `installMockForType`, this mock is used for both test methods <2> We use `installMockForInstance` to replace the injected bean, this takes effect for the duration of the test method. Note that there is no dependency on Mockito, you can use any mocking library you like, or even manually override the objects to provide the behaviour you require. NOTE: Using `@Inject` will get you a CDI proxy to the mock instance you install, which is not suitable for passing to methods such as `Mockito.verify` which want the mock instance itself. So if you need to call methods such as `verify` you need to hang on to the mock instance in your test, or use `@InjectMock` as shown below. ==== Further simplification with `@InjectMock` Building on the features provided by `QuarkusMock`, Quarkus also allows users to effortlessly take advantage of link:https://site.mockito.org/[Mockito] for mocking the beans supported by `QuarkusMock`. This functionality is available via the `@io.quarkus.test.junit.mockito.InjectMock` annotation which is available in the `quarkus-junit5-mockito` dependency. Using `@InjectMock`, the previous example could be written as follows: [source,java] ---- @QuarkusTest public class MockTestCase { @InjectMock MockableBean1 mockableBean1; // <1> @InjectMock MockableBean2 mockableBean2; @BeforeEach public void setup() { Mockito.when(mockableBean1.greet(""Stuart"")).thenReturn(""A mock for Stuart""); // <2> } @Test public void firstTest() { Assertions.assertEquals(""A mock for Stuart"", mockableBean1.greet(""Stuart"")); Assertions.assertEquals(null, mockableBean2.greet(""Stuart"")); // <3> } @Test public void secondTest() { Mockito.when(mockableBean2.greet(""Stuart"")).thenReturn(""Bonjour Stuart""); // <4> Assertions.assertEquals(""A mock for Stuart"", mockableBean1.greet(""Stuart"")); Assertions.assertEquals(""Bonjour Stuart"", mockableBean2.greet(""Stuart"")); } @ApplicationScoped public static class MockableBean1 { public String greet(String name) { return ""Hello "" + name; } } @ApplicationScoped public static class MockableBean2 { public String greet(String name) { return ""Hello "" + name; } } } ---- <1> `@InjectMock` results in a mock being and is available in test methods of the test class (other test classes are *not* affected by this) <2> The `mockableBean1` is configured here for every test method of the class <3> Since the `mockableBean2` mock has not been configured, it will return the default Mockito response. <4> In this test the `mockableBean2` is configured, so it returns the configured response. Although the test above is good for showing the capabilities of `@InjectMock`, it is not a good representation of a real test. In a real test we would most likely configure a mock, but then test a bean that uses the mocked bean. Here is an example: [source,java] ---- @QuarkusTest public class MockGreetingServiceTest { @InjectMock GreetingService greetingService; @Test public void testGreeting() { when(greetingService.greet()).thenReturn(""hi""); given() .when().get(""/greeting"") .then() .statusCode(200) .body(is(""hi"")); // <1> } @Path(""greeting"") public static class GreetingResource { final GreetingService greetingService; public GreetingResource(GreetingService greetingService) { this.greetingService = greetingService; } @GET @Produces(""text/plain"") public String greet() { return greetingService.greet(); } } @ApplicationScoped public static class GreetingService { public String greet(){ return ""hello""; } } } ---- <1> Since we configured `greetingService` as a mock, the `GreetingResource` which uses the `GreetingService` bean, we get the mocked response instead of the response of the regular `GreetingService` bean By default the `@InjectMock` annotation can be used for any normal CDI scoped bean (e.g. `@ApplicationScoped`, `@RequestScoped`). Mocking `@Singleton` beans can be performed by setting the `convertScopes` property to true (such as `@InjectMock(convertScopes = true`). This will convert the `@Singleton` bean to an `@ApplicationScoped` bean for the test. This is considered an advanced option and should only be performed if you fully understand the consequences of changing the scope of the bean. ==== Using Spies instead of Mocks with `@InjectSpy` Building on the features provided by `InjectMock`, Quarkus also allows users to effortlessly take advantage of link:https://site.mockito.org/[Mockito] for spying on the beans supported by `QuarkusMock`. This functionality is available via the `@io.quarkus.test.junit.mockito.InjectSpy` annotation which is available in the `quarkus-junit5-mockito` dependency. Sometimes when testing you only need to verify that a certain logical path was taken, or you only need to stub out a single method's response while still executing the rest of the methods on the Spied clone. Please see link:https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#spy-T-[Mockito documentation] for more details on Spy partial mocks. In either of those situations a Spy of the object is preferable. Using `@InjectSpy`, the previous example could be written as follows: [source,java] ---- @QuarkusTest public class SpyGreetingServiceTest { @InjectSpy GreetingService greetingService; @Test public void testDefaultGreeting() { given() .when().get(""/greeting"") .then() .statusCode(200) .body(is(""hello"")); Mockito.verify(greetingService, Mockito.times(1)).greet(); <1> } @Test public void testOverrideGreeting() { when(greetingService.greet()).thenReturn(""hi""); <2> given() .when().get(""/greeting"") .then() .statusCode(200) .body(is(""hi"")); <3> } @Path(""greeting"") public static class GreetingResource { final GreetingService greetingService; public GreetingResource(GreetingService greetingService) { this.greetingService = greetingService; } @GET @Produces(""text/plain"") public String greet() { return greetingService.greet(); } } @ApplicationScoped public static class GreetingService { public String greet(){ return ""hello""; } } } ---- <1> Instead of overriding the value, we just want to ensure that the greet method on our `GreetingService` was called by this test. <2> Here we are telling the Spy to return ""hi"" instead of ""hello"". When the `GreetingResource` requests the greeting from `GreetingService` we get the mocked response instead of the response of the regular `GreetingService` bean <3> We are verifying that we get the mocked response from the Spy. ==== Using `@InjectMock` with `@RestClient` The `@RegisterRestClient` registers the implementation of the rest-client at runtime, and because the bean needs to be a regular scope, you have to annotate your interface with `@ApplicationScoped`. [source,java] ---- @Path(""/"") @ApplicationScoped @RegisterRestClient public interface GreetingService { @GET @Path(""/hello"") @Produces(MediaType.TEXT_PLAIN) String hello(); } ---- For the test class here is an example: [source,java] ---- @QuarkusTest public class GreetingResourceTest { @InjectMock @RestClient // <1> GreetingService greetingService; @Test public void testHelloEndpoint() { Mockito.when(greetingService.hello()).thenReturn(""hello from mockito""); given() .when().get(""/hello"") .then() .statusCode(200) .body(is(""hello from mockito"")); } } ---- <1> Indicate that this injection point is meant to use an instance of `RestClient`. === Mocking with Panache If you are using the `quarkus-hibernate-orm-panache` or `quarkus-mongodb-panache` extensions, check out the xref:hibernate-orm-panache.adoc#mocking[Hibernate ORM with Panache Mocking] and xref:mongodb-panache.adoc#mocking[MongoDB with Panache Mocking] documentation for the easiest way to mock your data access. == Testing Security If you are using Quarkus Security, check out the xref:security-testing.adoc[Testing Security] section for information on how to easily test security features of the application. [#quarkus-test-resource] == Starting services before the Quarkus application starts A very common need is to start some services on which your Quarkus application depends, before the Quarkus application starts for testing. To address this need, Quarkus provides `@io.quarkus.test.common.QuarkusTestResource` and `io.quarkus.test.common.QuarkusTestResourceLifecycleManager`. By simply annotating any test in the test suite with `@QuarkusTestResource`, Quarkus will run the corresponding `QuarkusTestResourceLifecycleManager` before any tests are run. A test suite is also free to utilize multiple `@QuarkusTestResource` annotations, in which case all the corresponding `QuarkusTestResourceLifecycleManager` objects will be run before the tests. When using multiple test resources they can be started concurrently. For that you need to set `@QuarkusTestResource(parallel = true)`. NOTE: Test resources are global, even if they are defined on a test class or custom profile, which means they will all be activated for all tests, even though we do remove duplicates. If you want to only enable a test resource on a single test class or test profile, you can use `@QuarkusTestResource(restrictToAnnotatedClass = true)`. Quarkus provides a few implementations of `QuarkusTestResourceLifecycleManager` out of the box (see `io.quarkus.test.h2.H2DatabaseTestResource` which starts an H2 database, or `io.quarkus.test.kubernetes.client.KubernetesServerTestResource` which starts a mock Kubernetes API server), but it is common to create custom implementations to address specific application needs. Common cases include starting docker containers using https://www.testcontainers.org/[Testcontainers] (an example of which can be found https://github.com/quarkusio/quarkus/blob/main/test-framework/keycloak-server/src/main/java/io/quarkus/test/keycloak/server/KeycloakTestResourceLifecycleManager.java[here]), or starting a mock HTTP server using http://wiremock.org/[Wiremock] (an example of which can be found https://github.com/geoand/quarkus-test-demo/blob/main/src/test/java/org/acme/getting/started/country/WiremockCountries.java[here]). === Altering the test class When creating a custom `QuarkusTestResourceLifecycleManager` that needs to inject the something into the test class, the `inject` methods can be used. If for example you have a test like the following: [source,java] ---- @QuarkusTest @QuarkusTestResource(MyWireMockResource.class) public class MyTest { @InjectWireMock // this a custom annotation you are defining in your own application WireMockServer wireMockServer; @Test public someTest() { // control wiremock in some way and perform test } } ---- Making `MyWireMockResource` inject the `wireMockServer` field can be done as shown in the `inject` method of the following code snippet: [source,java] ---- public class MyWireMockResource implements QuarkusTestResourceLifecycleManager { WireMockServer wireMockServer; @Override public Map start() { wireMockServer = new WireMockServer(8090); wireMockServer.start(); // create some stubs return Map.of(""some.service.url"", ""localhost:"" + wireMockServer.port()); } @Override public synchronized void stop() { if (wireMockServer != null) { wireMockServer.stop(); wireMockServer = null; } } @Override public void inject(TestInjector testInjector) { testInjector.injectIntoFields(wireMockServer, new TestInjector.AnnotatedAndMatchesType(InjectWireMock.class, WireMockServer.class)); } } ---- IMPORTANT: It is worth mentioning that this injection into the test class is not under the control of CDI and happens after CDI has performed any necessary injections into the test class. === Annotation-based test resources It is possible to write test resources that are enabled and configured using annotations. This is enabled by placing the `@QuarkusTestResource` on an annotation which will be used to enable and configure the test resource. For example, this defines the `@WithKubernetesTestServer` annotation, which you can use on your tests to activate the `KubernetesServerTestResource`, but only for the annotated test class. You can also place them on your `QuarkusTestProfile` test profiles. [source,java] ---- @QuarkusTestResource(KubernetesServerTestResource.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface WithKubernetesTestServer { /** * Start it with HTTPS */ boolean https() default false; /** * Start it in CRUD mode */ boolean crud() default true; /** * Port to use, defaults to any available port */ int port() default 0; } ---- The `KubernetesServerTestResource` class has to implement the `QuarkusTestResourceConfigurableLifecycleManager` interface in order to be configured using the previous annotation: [source,java] ---- public class KubernetesServerTestResource implements QuarkusTestResourceConfigurableLifecycleManager { private boolean https = false; private boolean crud = true; private int port = 0; @Override public void init(WithKubernetesTestServer annotation) { this.https = annotation.https(); this.crud = annotation.crud(); this.port = annotation.port(); } // ... } ---- == Hang Detection `@QuarkusTest` has support for hang detection to help diagnose any unexpected hangs. If no progress is made for a specified time (i.e. no JUnit callbacks are invoked) then Quarkus will print a stack trace to the console to help diagnose the hang. The default value for this timeout is 10 minutes. No further action will be taken, and the tests will continue as normal (generally until CI times out), however the printed stack traces should help diagnose why the build has failed. You can control this timeout with the `quarkus.test.hang-detection-timeout` system property (you can also set this in application.properties, but this won't be read until Quarkus has started, so the timeout for Quarkus start will be the default of 10 minutes). == Native Executable Testing It is also possible to test native executables using `@QuarkusIntegrationTest`. This supports all the features mentioned in this guide except injecting into tests (and the native executable runs in a separate non-JVM process this is not really possible). This is covered in the xref:building-native-image.adoc[Native Executable Guide]. [#quarkus-integration-test] == Using `@QuarkusIntegrationTest` `@QuarkusIntegrationTest` should be used to launch and test the artifact produced by the Quarkus build, and supports testing a jar (of whichever type), a native image or container image. Put simply, this means that if the result of a Quarkus build (`mvn package` or `gradle build`) is a jar, that jar will be launched as `java -jar ...` and tests run against it. If instead a native image was built, then the application is launched as `./application ...` and again the tests run against the running application. Finally, if a container image was created during the build (by including the `quarkus-container-image-jib` or `quarkus-container-image-docker` extensions and having the `quarkus.container-image.build=true` property configured), then a container is created and run (this requires the `docker` executable being present). As is the case with `@NativeImageTest`, this is a black box test that supports the same set features and has the same limitations. [NOTE] ==== As a test annotated with `@QuarkusIntegrationTest` tests the result of the build, it should be run as part of the integration test suite - i.e. by setting `-DskipITs=false` if using Maven or the `quarkusIntTest` task if using Gradle. These tests will **not** work if run in the same phase as `@QuarkusTest` as Quarkus has not yet created the final artifact. ==== The `pom.xml` file contains: [source, xml] ---- org.apache.maven.plugins maven-failsafe-plugin ${surefire-plugin.version} integration-test verify ${project.build.directory}/${project.build.finalName}-runner org.jboss.logmanager.LogManager ${maven.home} ---- This instructs the failsafe-maven-plugin to run integration-test. Then, open the `src/test/java/org/acme/quickstart/GreetingResourceIT.java`. It contains: [source,java] ---- package org.acme.quickstart; import io.quarkus.test.junit.QuarkusIntegrationTest; @QuarkusIntegrationTest // <1> public class GreetingResourceIT extends GreetingResourceTest { // <2> // Run the same tests } ---- <1> Use another test runner that starts the application from the native file before the tests. The executable is retrieved by the _Failsafe Maven Plugin_. <2> We extend our previous tests as a convenience, but you can also implement your tests. More information can be found in the link:building-native-image#testing-the-native-executable[Testing the native executable Guide]. === Launching containers When `@QuarkusIntegrationTest` results in launching a container (because the application was built with `quarkus.container-image.build` set to `true`), the container is launched on a predictable container network. This facilitates writing integration tests that need to launch services to support the application. This means that `@QuarkusIntegrationTest` works out of the box with containers launched via xref:dev-services.adoc[Dev Services], but it also means that it enables using <> resources that launch additional containers. This can be achieved by having your `QuarkusTestLifecycleManager` implement `io.quarkus.test.common.DevServicesContext.ContextAware`. A simple example could be the following: The container running the resource to test against, for example PostgreSQL via Testcontainers, is assigned an IP address from the container's network. Use the container's ""public"" IP from its network and the ""unmapped"" port number to connect to the service. The Testcontainers library usually return connection strings without respecting the container network, so additional code is needed to provide Quarkus the ""correct"" connection string using the container's IP on the container network and the _unmapped_ port number. The following example illustrates the use with PostgreSQL, but the approach is applicable to all containers. [source,java] ---- import io.quarkus.test.common.DevServicesContext; import io.quarkus.test.common.QuarkusTestResourceLifecycleManager; import org.testcontainers.containers.JdbcDatabaseContainer; import org.testcontainers.containers.PostgreSQLContainer; import java.util.HashMap; import java.util.Map; import java.util.Optional; public class CustomResource implements QuarkusTestResourceLifecycleManager, DevServicesContext.ContextAware { private Optional containerNetworkId; private JdbcDatabaseContainer container; @Override public void setIntegrationTestContext(DevServicesContext context) { containerNetworkId = context.containerNetworkId(); } @Override public Map start() { // start a container making sure to call withNetworkMode() with the value of containerNetworkId if present container = new PostgreSQLContainer<>(""postgres:latest"").withLogConsumer(outputFrame -> {}); // apply the network to the container containerNetworkId.ifPresent(container::withNetworkMode); String jdbcUrl = container.getJdbcUrl(); if (containerNetworkId.isPresent()) { // Replace hostname + port in the provided JDBC URL with the hostname of the Docker container // running PostgreSQL and the listening port. jdbcUrl = fixJdbcUrl(jdbcUrl); } // return a map containing the configuration the application needs to use the service return ImmutableMap.of( ""quarkus.datasource.username"", container.getUsername(), ""quarkus.datasource.password"", container.getPassword(), ""quarkus.datasource.jdbc.url"", jdbcUrl); } private String fixJdbcUrl(String jdbcUrl) { // Part of the JDBC URL to replace String hostPort = container.getHost() + ':' + container.getMappedPort(PostgreSQLContainer.POSTGRESQL_PORT); // Host/IP on the container network plus the unmapped port String networkHostPort = container.getCurrentContainerInfo().getConfig().getHostName() + ':' + PostgreSQLContainer.POSTGRESQL_PORT; return jdbcUrl.replace(hostPort, networkHostPort); } @Override public void stop() { // close container } } ---- `CustomResource` would be activated on a `@QuarkusIntegrationTest` using `@QuarkusTestResource` as is described in the corresponding section of this doc. === Executing against a running application [WARNING] ==== This feature is considered experimental and is likely to change in future versions of Quarkus. ==== `@QuarkusIntegrationTest` supports executing tests against an already running instance of the application. This can be achieved by setting the `quarkus.http.test-host` system property when running the tests. An example use of this could be the following Maven command, that forces `@QuarkusIntegrationTest` to execute against that is accessible at `http://1.2.3.4:4321`: [source,bash] ---- ./mvnw verify -Dquarkus.http.test-host=1.2.3.4 -Dquarkus.http.test-port=4321 ---- == Mixing `@QuarkusTest` with other type of tests Mixing tests annotated with `@QuarkusTest` with tests annotated with either `@QuarkusDevModeTest`, `@QuarkusProdModeTest` or `@QuarkusUnitTest` is not allowed in a single execution run (in a single Maven Surefire Plugin execution, for instance), while the latter three can coexist. The reason of this restriction is that `@QuarkusTest` starts a Quarkus server for the whole lifetime of the tests execution run, thus preventing the other tests to start their own Quarkus server. To alleviate this restriction, the `@QuarkusTest` annotation defines a JUnit 5 `@Tag`: `io.quarkus.test.junit.QuarkusTest`. You can use this tag to isolate the `@QuarkusTest` test in a specific execution run, for example with the Maven Surefire Plugin: [source,xml] ---- maven-surefire-plugin ${surefire-plugin.version} default-test test io.quarkus.test.junit.QuarkusTest quarkus-test test io.quarkus.test.junit.QuarkusTest org.jboss.logmanager.LogManager ---- [[test-from-ide]] == Running `@QuarkusTest` from an IDE Most IDEs offer the possibility to run a selected class as a JUnit test directly. For this you should set a few properties in the settings of your chosen IDE: * `java.util.logging.manager` (see xref:logging.adoc[Logging Guide]) * `maven.home` (only if there are any custom settings in `${maven.home}/conf/settings.xml`, see xref:maven-tooling.adoc[Maven Guide]) * `maven.settings` (in case a custom version of `settings.xml` file should be used for the tests) === Eclipse separate JRE definition Copy your current ""Installed JRE"" definition into a new one, where you will add the properties as a new VM arguments: * `-Djava.util.logging.manager=org.jboss.logmanager.LogManager` * `-Dmaven.home=` Use this JRE definition as your Quarkus project targeted runtime and the workaround will be applied to any ""Run as JUnit"" configuration. === VSCode ""run with"" configuration The `settings.json` placed in the root of your project directory or in the workspace will need the following workaround in your test configuration: [source, json] ---- ""java.test.config"": [ { ""name"": ""quarkusConfiguration"", ""vmargs"": [ ""-Djava.util.logging.manager=org.jboss.logmanager.LogManager -Dmaven.home= ..."" ], ... }, ... ] ---- === IntelliJ JUnit template Nothing needed in IntelliJ because the IDE will pick the `systemPropertyVariables` from the surefire plugin configuration in `pom.xml`. == Testing Dev Services By default tests should just work with xref:dev-services.adoc[Dev Services], however from some use cases you may need access to the automatically configured properties in your tests. You can do this with `io.quarkus.test.common.DevServicesContext`, which can be injected directly into any `@QuarkusTest` or `@QuarkusIntegrationTest`. All you need to do is define a field of type `DevServicesContext` and it will be automatically injected. Using this you can retrieve any properties that have been set. Generally this is used to directly connect to a resource from the test itself, e.g. to connect to kafka to send messages to the application under test. Injection is also supported into objects that implement `io.quarkus.test.common.DevServicesContext.ContextAware`. If you have a field that implements `io.quarkus.test.common.DevServicesContext.ContextAware` Quarkus will call the `setIntegrationTestContext` method to pass the context into this object. This allows client logic to be encapsulated in a utility class. `QuarkusTestResourceLifecycleManager` implementations can also implement `ContextAware` to get access to these properties, which allows you to setup the resource before Quarkus starts (e.g. configure a KeyCloak instance, add data to a database etc). [NOTE] ==== For `@QuarkusIntegrationTest` tests that result in launcher the application as a container, `io.quarkus.test.common.DevServicesContext` also provides access to the id of the container network on which the application container was launched (via the `containerNetworkId` method). This can be used by `QuarkusTestResourceLifecycleManager` that need to launch additional containers that the application will communicate with. ==== ",12345,False,2134.181754970093,median " SUMMARY OF PM7 CALCULATION, Site No: 31305 MOPAC2016 (Version: 18.305L) Sat Apr 6 17:25:18 2019 No. of days remaining = 209 Empirical Formula: C50 H79 N O37 = 167 atoms AUX LARGE CHARGE=0 SINGLET PM7 Title HERBERTS TEST WAS SATISFIED IN BFGS SCF FIELD WAS ACHIEVED HEAT OF FORMATION = -1705.09886 KCAL/MOL = -7134.13363 KJ/MOL TOTAL ENERGY = -18321.83218 EV ELECTRONIC ENERGY = -321454.69008 EV CORE-CORE REPULSION = 303132.85790 EV GRADIENT NORM = 0.83238 = 0.06441 PER ATOM DIPOLE = 5.20957 DEBYE POINT GROUP: C1 NO. OF FILLED LEVELS = 253 IONIZATION POTENTIAL = 8.563106 EV HOMO LUMO ENERGIES (EV) = -8.563 0.055 MOLECULAR WEIGHT = 1286.1586 COSMO AREA = 729.18 SQUARE ANGSTROMS COSMO VOLUME = 1354.29 CUBIC ANGSTROMS MOLECULAR DIMENSIONS (Angstroms) Atom Atom Distance H 98 H 35 14.57195 H 55 H 139 14.06711 H 123 H 162 7.76513 SCF CALCULATIONS = 520 WALL-CLOCK TIME = 7 MINUTES AND 37.520 SECONDS COMPUTATION TIME = 6 MINUTES AND 33.956 SECONDS FINAL GEOMETRY OBTAINED AUX LARGE CHARGE=0 SINGLET PM7 Title H -32.62230725 +1 -30.56947112 +1 -12.34575683 +1 C -21.83829224 +1 -26.72571561 +1 -10.25661753 +1 C -22.01522231 +1 -27.55918156 +1 -8.96100748 +1 C -23.46044972 +1 -28.07045045 +1 -8.87133403 +1 C -24.40988855 +1 -26.86473734 +1 -9.05683191 +1 C -24.14359594 +1 -26.20961361 +1 -10.42273525 +1 C -25.00088607 +1 -24.97782476 +1 -10.72228185 +1 O -21.08728546 +1 -28.62248823 +1 -9.06686674 +1 O -23.61078687 +1 -28.60653812 +1 -7.58265505 +1 O -25.69167266 +1 -27.45111052 +1 -9.06820035 +1 O -22.80548547 +1 -25.71298502 +1 -10.35507137 +1 O -25.46051762 +1 -25.06667473 +1 -12.05446978 +1 H -20.87298347 +1 -26.18482724 +1 -10.31140972 +1 H -21.73054462 +1 -26.97412944 +1 -8.05721683 +1 H -23.66832433 +1 -28.87935991 +1 -9.61043900 +1 H -24.28554430 +1 -26.13694787 +1 -8.22641309 +1 H -24.23754779 +1 -26.95224015 +1 -11.25266409 +1 H -25.85914796 +1 -24.87459568 +1 -10.03464455 +1 H -24.39763358 +1 -24.04658187 +1 -10.71124236 +1 H -21.38437392 +1 -29.37430982 +1 -8.50040552 +1 H -24.56875389 +1 -28.67380646 +1 -7.34204509 +1 H -26.33382744 +1 -25.53215224 +1 -12.10562946 +1 C -20.51366549 +1 -28.64395217 +1 -14.94048128 +1 C -19.71267413 +1 -29.10607401 +1 -13.69541013 +1 C -20.62984977 +1 -29.02929875 +1 -12.47044745 +1 C -21.14729902 +1 -27.57820732 +1 -12.37278539 +1 C -21.91533851 +1 -27.19786346 +1 -13.65116375 +1 C -22.31709854 +1 -25.71653037 +1 -13.69365530 +1 O -19.30249231 +1 -30.43530969 +1 -13.94410349 +1 O -19.83501719 +1 -29.32920373 +1 -11.35247998 +1 O -22.06710604 +1 -27.63097705 +1 -11.30604272 +1 O -21.01238378 +1 -27.34790829 +1 -14.74699980 +1 O -23.68704378 +1 -25.61409137 +1 -13.99666930 +1 H -19.90092604 +1 -28.55594578 +1 -15.86006907 +1 H -18.78801432 +1 -28.50062169 +1 -13.56224779 +1 H -21.46301076 +1 -29.76923499 +1 -12.51818676 +1 H -20.31018335 +1 -26.87481722 +1 -12.17707872 +1 H -22.80405336 +1 -27.85401085 +1 -13.80423665 +1 H -22.10123265 +1 -25.18954136 +1 -12.74780233 +1 H -21.81903454 +1 -25.19338217 +1 -14.53843228 +1 H -19.04750769 +1 -30.85411440 +1 -13.08229942 +1 H -20.31764521 +1 -29.10391408 +1 -10.51735880 +1 H -24.25664533 +1 -25.45597401 +1 -13.19899343 +1 C -23.18952576 +1 -31.96001220 +1 -17.97811556 +1 C -22.15874036 +1 -32.60192666 +1 -17.01640499 +1 C -21.98405300 +1 -31.71840041 +1 -15.76925506 +1 C -21.65847401 +1 -30.28367211 +1 -16.24656651 +1 C -22.81349955 +1 -29.77987002 +1 -17.13422152 +1 C -22.61473263 +1 -28.37218032 +1 -17.70472043 +1 O -22.65537395 +1 -33.88526953 +1 -16.69801616 +1 O -20.91615047 +1 -32.27933192 +1 -15.05272144 +1 O -21.61436075 +1 -29.51601139 +1 -15.06155547 +1 O -22.83175841 +1 -30.63619354 +1 -18.27553619 +1 O -23.85962685 +1 -27.72887478 +1 -17.80836670 +1 H -23.24020279 +1 -32.45469278 +1 -18.96900561 +1 H -21.18487952 +1 -32.77312834 +1 -17.53083722 +1 H -22.87830859 +1 -31.74509019 +1 -15.10279198 +1 H -20.68933790 +1 -30.26266525 +1 -16.78878459 +1 H -23.79269579 +1 -29.84087354 +1 -16.59867525 +1 H -21.93034325 +1 -27.76415055 +1 -17.08533911 +1 H -22.25285535 +1 -28.40207759 +1 -18.75209223 +1 H -22.42687619 +1 -34.11428883 +1 -15.76521410 +1 H -20.37221270 +1 -31.57641451 +1 -14.61765718 +1 H -24.21772299 +1 -27.49075475 +1 -16.92147490 +1 C -28.32590957 +1 -32.90470508 +1 -18.06265837 +1 C -27.32293620 +1 -34.08315867 +1 -17.99031061 +1 C -26.03478845 +1 -33.61844393 +1 -17.29948698 +1 C -25.53370330 +1 -32.34738324 +1 -18.02192650 +1 C -26.61581529 +1 -31.25633284 +1 -17.92831255 +1 C -26.26420343 +1 -29.95922044 +1 -18.66219770 +1 O -27.96262430 +1 -35.10866152 +1 -17.25211640 +1 O -25.11511978 +1 -34.66535253 +1 -17.47047819 +1 O -24.40955116 +1 -31.93500726 +1 -17.27675198 +1 O -27.74388631 +1 -31.77224219 +1 -18.64422757 +1 O -26.78509919 +1 -28.88459044 +1 -17.90663437 +1 H -29.21165086 +1 -33.11015210 +1 -18.69535301 +1 H -27.11783604 +1 -34.50211019 +1 -19.00213483 +1 H -26.17550232 +1 -33.44341371 +1 -16.20718961 +1 H -25.28045248 +1 -32.56496021 +1 -19.08196264 +1 H -26.89807271 +1 -31.04150054 +1 -16.87090656 +1 H -25.17257082 +1 -29.83824622 +1 -18.80660250 +1 H -26.78243226 +1 -29.88946626 +1 -19.63903404 +1 H -27.27260236 +1 -35.70654385 +1 -16.87293531 +1 H -24.21332342 +1 -34.38256790 +1 -17.16707323 +1 H -26.05995115 +1 -28.41481755 +1 -17.43375979 +1 C -31.83876513 +1 -31.74083138 +1 -14.34562904 +1 C -31.51586706 +1 -33.23953594 +1 -14.55763233 +1 C -30.11866384 +1 -33.40339657 +1 -15.16304708 +1 C -29.99303938 +1 -32.48995107 +1 -16.40291346 +1 C -30.28933567 +1 -31.03578276 +1 -15.99912313 +1 C -30.26125797 +1 -30.02881454 +1 -17.15416148 +1 O -31.58471777 +1 -33.84320983 +1 -13.28052247 +1 O -30.00935356 +1 -34.75159251 +1 -15.53632292 +1 O -28.62569352 +1 -32.58722887 +1 -16.72455232 +1 O -31.63725057 +1 -31.01493292 +1 -15.52425158 +1 O -29.55764857 +1 -28.88619965 +1 -16.72083442 +1 H -32.90225475 +1 -31.55201873 +1 -14.09143097 +1 H -32.29293887 +1 -33.72540736 +1 -15.19328332 +1 H -29.31301884 +1 -33.18681006 +1 -14.42501146 +1 H -30.65416014 +1 -32.83541244 +1 -17.22411341 +1 H -29.59569140 +1 -30.69989765 +1 -15.19163635 +1 H -29.79244925 +1 -30.44574214 +1 -18.06421159 +1 H -31.27633041 +1 -29.65214041 +1 -17.39054285 +1 H -31.18007300 +1 -34.74244842 +1 -13.32463725 +1 H -29.22892258 +1 -34.87783156 +1 -16.14099238 +1 H -28.60506164 +1 -28.93221890 +1 -16.99626036 +1 C -31.08237921 +1 -28.98997598 +1 -9.96306024 +1 C -31.50425944 +1 -30.47394152 +1 -9.81775331 +1 C -31.00116074 +1 -31.26208982 +1 -11.03672746 +1 C -31.51105989 +1 -30.54744875 +1 -12.30712071 +1 C -30.98600877 +1 -29.09858372 +1 -12.33089056 +1 C -31.48441334 +1 -28.26672322 +1 -13.52031854 +1 O -30.90386355 +1 -30.93521408 +1 -8.62488216 +1 O -31.56894711 +1 -32.54017773 +1 -10.92277329 +1 O -30.92897058 +1 -31.25396457 +1 -13.37995659 +1 O -31.54430211 +1 -28.46372035 +1 -11.18014910 +1 O -30.36615453 +1 -27.63040086 +1 -14.09824227 +1 H -31.52009801 +1 -28.32188551 +1 -9.19490053 +1 H -32.60599009 +1 -30.57325404 +1 -9.68981764 +1 H -29.89278767 +1 -31.37073402 +1 -11.02787933 +1 H -29.87136877 +1 -29.06126515 +1 -12.27632233 +1 H -32.01825328 +1 -28.87596174 +1 -14.26992750 +1 H -32.13519019 +1 -27.43475164 +1 -13.18110074 +1 H -30.88050717 +1 -31.92255922 +1 -8.63234356 +1 H -31.53520548 +1 -33.02319061 +1 -11.78433336 +1 H -30.11089781 +1 -28.06176479 +1 -14.95355714 +1 C -26.64535963 +1 -26.82927675 +1 -8.24288423 +1 C -27.27479591 +1 -27.96738886 +1 -7.39898009 +1 C -28.07512760 +1 -28.91746070 +1 -8.30141143 +1 C -29.03722749 +1 -28.06720066 +1 -9.16169455 +1 C -28.20095737 +1 -27.10004567 +1 -10.01955553 +1 C -29.01592000 +1 -26.18892225 +1 -10.94262172 +1 O -26.18988753 +1 -28.63662992 +1 -6.78340020 +1 O -28.79669545 +1 -29.74978332 +1 -7.43120786 +1 O -29.67658050 +1 -29.00263866 +1 -10.00016650 +1 O -27.59057380 +1 -26.21434484 +1 -9.07656797 +1 O -28.37092788 +1 -26.15507095 +1 -12.19788661 +1 H -26.24979033 +1 -25.99379003 +1 -7.63003564 +1 H -27.90882012 +1 -27.55788493 +1 -6.57904560 +1 H -27.41503707 +1 -29.55820578 +1 -8.93087518 +1 H -29.75866653 +1 -27.51440799 +1 -8.52249651 +1 H -27.41850502 +1 -27.63805808 +1 -10.60665166 +1 H -30.06295490 +1 -26.52393506 +1 -11.05136577 +1 H -28.99524599 +1 -25.13637449 +1 -10.59427529 +1 H -26.48755730 +1 -29.53174934 +1 -6.49018669 +1 H -29.52338048 +1 -30.21575179 +1 -7.91399011 +1 H -28.82148935 +1 -26.75643075 +1 -12.83889543 +1 H -28.14754686 +1 -34.73515859 +1 -12.71021816 +1 C -27.08593754 +1 -28.33573574 +1 -14.69425030 +1 C -24.92833755 +1 -29.39658443 +1 -14.27797451 +1 C -25.69186515 +1 -28.34728835 +1 -14.78488531 +1 C -27.17548481 +1 -32.82322997 +1 -12.73135684 +1 C -28.14860510 +1 -33.79756275 +1 -12.12933234 +1 C -25.57101879 +1 -30.48055465 +1 -13.68810905 +1 C -26.97028552 +1 -30.50143105 +1 -13.60987282 +1 C -27.71945417 +1 -29.41624749 +1 -14.10134890 +1 N -27.70041535 +1 -31.56529146 +1 -13.02716977 +1 O -26.01479087 +1 -33.10221382 +1 -12.93085919 +1 O -25.12141917 +1 -27.31898662 +1 -15.47269500 +1 H -28.80622101 +1 -29.42123528 +1 -14.01942880 +1 H -24.97578148 +1 -31.30743979 +1 -13.29339536 +1 H -27.82755789 +1 -34.06394681 +1 -11.10899887 +1 H -28.70349421 +1 -31.42324461 +1 -12.92949731 +1 H -27.65028490 +1 -27.49056588 +1 -15.08929021 +1 H -23.84169778 +1 -29.37964925 +1 -14.34981917 +1 H -24.52220959 +1 -26.74134341 +1 -14.90238495 +1 H -29.18565424 +1 -33.44524175 +1 -12.06616632 +1 ",8286,True,2731.7243220548366,median "[[cluster-nodes-stats]] === Nodes stats API ++++ Nodes stats ++++ Returns cluster nodes statistics. [[cluster-nodes-stats-api-request]] ==== {api-request-title} `GET /_nodes/stats` + `GET /_nodes//stats` + `GET/_nodes/stats/` + `GET/_nodes//stats/` + `GET /_nodes/stats//` + `GET /_nodes//stats//` [[cluster-nodes-stats-api-prereqs]] ==== {api-prereq-title} * If the {es} {security-features} are enabled, you must have the `monitor` or `manage` <> to use this API. [[cluster-nodes-stats-api-desc]] ==== {api-description-title} You can use the cluster nodes stats API to retrieve statistics for nodes in a cluster. All the nodes selective options are explained <>. By default, all stats are returned. You can limit the returned information by using metrics. [[cluster-nodes-stats-api-path-params]] ==== {api-path-parms-title} ``:: (Optional, string) Limits the information returned to the specific metrics. A comma-separated list of the following options: + -- `adaptive_selection`:: Statistics about <>. `breaker`:: Statistics about the field data circuit breaker. `discovery`:: Statistics about the discovery. `fs`:: File system information, data path, free disk space, read/write stats. `http`:: HTTP connection information. `indexing_pressure`:: Statistics about the node's indexing load and related rejections. `indices`:: Indices stats about size, document count, indexing and deletion times, search times, field cache size, merges and flushes. `ingest`:: Statistics about ingest preprocessing. `jvm`:: JVM stats, memory pool information, garbage collection, buffer pools, number of loaded/unloaded classes. `os`:: Operating system stats, load average, mem, swap. `process`:: Process statistics, memory consumption, cpu usage, open file descriptors. `thread_pool`:: Statistics about each thread pool, including current size, queue and rejected tasks. `transport`:: Transport statistics about sent and received bytes in cluster communication. -- ``:: (Optional, string) Limit the information returned for `indices` metric to the specific index metrics. It can be used only if `indices` (or `all`) metric is specified. Supported metrics are: + -- * `completion` * `docs` * `fielddata` * `flush` * `get` * `indexing` * `merge` * `query_cache` * `recovery` * `refresh` * `request_cache` * `search` * `segments` * `store` * `translog` * `warmer` -- include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=node-id] [[cluster-nodes-stats-api-query-params]] ==== {api-query-parms-title} include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=completion-fields] include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=fielddata-fields] include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=fields] include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=groups] include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=level] `types`:: (Optional, string) A comma-separated list of document types for the `indexing` index metric. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=timeoutparms] include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=include-segment-file-sizes] [role=""child_attributes""] [[cluster-nodes-stats-api-response-body]] ==== {api-response-body-title} `_nodes`:: (object) Contains statistics about the number of nodes selected by the request. + .Properties of `_nodes` [%collapsible%open] ==== `total`:: (integer) Total number of nodes selected by the request. `successful`:: (integer) Number of nodes that responded successfully to the request. `failed`:: (integer) Number of nodes that rejected the request or failed to respond. If this value is not `0`, a reason for the rejection or failure is included in the response. ==== `cluster_name`:: (string) Name of the cluster. Based on the <> setting. `nodes`:: (object) Contains statistics for the nodes selected by the request. + .Properties of `nodes` [%collapsible%open] ==== ``:: (object) Contains statistics for the node. + .Properties of `` [%collapsible%open] ===== `timestamp`:: (integer) Time the node stats were collected for this response. Recorded in milliseconds since the {wikipedia}/Unix_time[Unix Epoch]. `name`:: (string) Human-readable identifier for the node. Based on the <> setting. `transport_address`:: (string) Host and port for the <>, used for internal communication between nodes in a cluster. `host`:: (string) Network host for the node, based on the <> setting. `ip`:: (string) IP address and port for the node. `roles`:: (array of strings) Roles assigned to the node. See <>. `attributes`:: (object) Contains a list of attributes for the node. [[cluster-nodes-stats-api-response-body-indices]] `indices`:: (object) Contains statistics about indices with shards assigned to the node. + .Properties of `indices` [%collapsible%open] ====== `docs`:: (object) Contains statistics about documents across all primary shards assigned to the node. + .Properties of `docs` [%collapsible%open] ======= `count`:: (integer) include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=docs-count] `deleted`:: (integer) include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=docs-deleted] ======= `store`:: (object) Contains statistics about the size of shards assigned to the node. + .Properties of `store` [%collapsible%open] ======= `size`:: (<>) Total size of all shards assigned to the node. `size_in_bytes`:: (integer) Total size, in bytes, of all shards assigned to the node. `reserved`:: (<>) A prediction of how much larger the shard stores on this node will eventually grow due to ongoing peer recoveries, restoring snapshots, and similar activities. A value of `-1b` indicates that this is not available. `reserved_in_bytes`:: (integer) A prediction, in bytes, of how much larger the shard stores on this node will eventually grow due to ongoing peer recoveries, restoring snapshots, and similar activities. A value of `-1` indicates that this is not available. ======= `indexing`:: (object) Contains statistics about indexing operations for the node. + .Properties of `indexing` [%collapsible%open] ======= `index_total`:: (integer) Total number of indexing operations. `index_time`:: (<>) Total time spent performing indexing operations. `index_time_in_millis`:: (integer) Total time in milliseconds spent performing indexing operations. `index_current`:: (integer) Number of indexing operations currently running. `index_failed`:: (integer) Number of failed indexing operations. `delete_total`:: (integer) Total number of deletion operations. `delete_time`:: (<>) Time spent performing deletion operations. `delete_time_in_millis`:: (integer) Time in milliseconds spent performing deletion operations. `delete_current`:: (integer) Number of deletion operations currently running. `noop_update_total`:: (integer) Total number of noop operations. `is_throttled`:: (Boolean) Number of times operations were throttled. `throttle_time`:: (<>) Total time spent throttling operations. `throttle_time_in_millis`:: (integer) Total time in milliseconds spent throttling operations. ======= `get`:: (object) Contains statistics about get operations for the node. + .Properties of `get` [%collapsible%open] ======= `total`:: (integer) Total number of get operations. `getTime`:: (<>) Time spent performing get operations. `time_in_millis`:: (integer) Time in milliseconds spent performing get operations. `exists_total`:: (integer) Total number of successful get operations. `exists_time`:: (<>) Time spent performing successful get operations. `exists_time_in_millis`:: (integer) Time in milliseconds spent performing successful get operations. `missing_total`:: (integer) Total number of failed get operations. `missing_time`:: (<>) Time spent performing failed get operations. `missing_time_in_millis`:: (integer) Time in milliseconds spent performing failed get operations. `current`:: (integer) Number of get operations currently running. ======= `search`:: (object) Contains statistics about search operations for the node. + .Properties of `search` [%collapsible%open] ======= `open_contexts`:: (integer) Number of open search contexts. `query_total`:: (integer) Total number of query operations. `query_time`:: (<>) Time spent performing query operations. `query_time_in_millis`:: (integer) Time in milliseconds spent performing query operations. `query_current`:: (integer) Number of query operations currently running. `fetch_total`:: (integer) Total number of fetch operations. `fetch_time`:: (<>) Time spent performing fetch operations. `fetch_time_in_millis`:: (integer) Time in milliseconds spent performing fetch operations. `fetch_current`:: (integer) Number of fetch operations currently running. `scroll_total`:: (integer) Total number of scroll operations. `scroll_time`:: (<>) Time spent performing scroll operations. `scroll_time_in_millis`:: (integer) Time in milliseconds spent performing scroll operations. `scroll_current`:: (integer) Number of scroll operations currently running. `suggest_total`:: (integer) Total number of suggest operations. `suggest_time`:: (<>) Time spent performing suggest operations. `suggest_time_in_millis`:: (integer) Time in milliseconds spent performing suggest operations. `suggest_current`:: (integer) Number of suggest operations currently running. ======= `merges`:: (object) Contains statistics about merge operations for the node. + .Properties of `merges` [%collapsible%open] ======= `current`:: (integer) Number of merge operations currently running. `current_docs`:: (integer) Number of document merges currently running. `current_size`:: (<>) Memory used performing current document merges. `current_size_in_bytes`:: (integer) Memory, in bytes, used performing current document merges. `total`:: (integer) Total number of merge operations. `total_time`:: (<>) Total time spent performing merge operations. `total_time_in_millis`:: (integer) Total time in milliseconds spent performing merge operations. `total_docs`:: (integer) Total number of merged documents. `total_size`:: (<>) Total size of document merges. `total_size_in_bytes`:: (integer) Total size of document merges in bytes. `total_stopped_time`:: (<>) Total time spent stopping merge operations. `total_stopped_time_in_millis`:: (integer) Total time in milliseconds spent stopping merge operations. `total_throttled_time`:: (<>) Total time spent throttling merge operations. `total_throttled_time_in_millis`:: (integer) Total time in milliseconds spent throttling merge operations. `total_auto_throttle`:: (<>) Size of automatically throttled merge operations. `total_auto_throttle_in_bytes`:: (integer) Size, in bytes, of automatically throttled merge operations. ======= `refresh`:: (object) Contains statistics about refresh operations for the node. + .Properties of `refresh` [%collapsible%open] ======= `total`:: (integer) Total number of refresh operations. `total_time`:: (<>) Total time spent performing refresh operations. `total_time_in_millis`:: (integer) Total time in milliseconds spent performing refresh operations. `external_total`:: (integer) Total number of external refresh operations. `external_total_time`:: (<>) Total time spent performing external operations. `external_total_time_in_millis`:: (integer) Total time in milliseconds spent performing external operations. `listeners`:: (integer) Number of refresh listeners. ======= `flush`:: (object) Contains statistics about flush operations for the node. + .Properties of `flush` [%collapsible%open] ======= `total`:: (integer) Number of flush operations. `periodic`:: (integer) Number of flush periodic operations. `total_time`:: (<>) Total time spent performing flush operations. `total_time_in_millis`:: (integer) Total time in milliseconds spent performing flush operations. ======= `warmer`:: (object) Contains statistics about index warming operations for the node. + .Properties of `warmer` [%collapsible%open] ======= `current`:: (integer) Number of active index warmers. `total`:: (integer) Total number of index warmers. `total_time`:: (<>) Total time spent performing index warming operations. `total_time_in_millis`:: (integer) Total time in milliseconds spent performing index warming operations. ======= `query_cache`:: (object) Contains statistics about the query cache across all shards assigned to the node. + .Properties of `query_cache` [%collapsible%open] ======= `memory_size`:: (<>) Total amount of memory used for the query cache across all shards assigned to the node. `memory_size_in_bytes`:: (integer) Total amount of memory, in bytes, used for the query cache across all shards assigned to the node. `total_count`:: (integer) Total count of hits, misses, and cached queries in the query cache. `hit_count`:: (integer) Number of query cache hits. `miss_count`:: (integer) Number of query cache misses. `cache_size`:: (integer) Size, in bytes, of the query cache. `cache_count`:: (integer) Count of queries in the query cache. `evictions`:: (integer) Number of query cache evictions. ======= `fielddata`:: (object) Contains statistics about the field data cache across all shards assigned to the node. + .Properties of `fielddata` [%collapsible%open] ======= `memory_size`:: (<>) Total amount of memory used for the field data cache across all shards assigned to the node. `memory_size_in_bytes`:: (integer) Total amount of memory, in bytes, used for the field data cache across all shards assigned to the node. `evictions`:: (integer) Number of fielddata evictions. ======= `completion`:: (object) Contains statistics about completions across all shards assigned to the node. + .Properties of `completion` [%collapsible%open] ======= `size`:: (<>) Total amount of memory used for completion across all shards assigned to the node. `size_in_bytes`:: (integer) Total amount of memory, in bytes, used for completion across all shards assigned to the node. ======= `segments`:: (object) Contains statistics about segments across all shards assigned to the node. + .Properties of `segments` [%collapsible%open] ======= `count`:: (integer) Number of segments. `memory`:: (<>) Total amount of memory used for segments across all shards assigned to the node. `memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for segments across all shards assigned to the node. `terms_memory`:: (<>) Total amount of memory used for terms across all shards assigned to the node. `terms_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for terms across all shards assigned to the node. `stored_fields_memory`:: (<>) Total amount of memory used for stored fields across all shards assigned to the node. `stored_fields_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for stored fields across all shards assigned to the node. `term_vectors_memory`:: (<>) Total amount of memory used for term vectors across all shards assigned to the node. `term_vectors_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for term vectors across all shards assigned to the node. `norms_memory`:: (<>) Total amount of memory used for normalization factors across all shards assigned to the node. `norms_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for normalization factors across all shards assigned to the node. `points_memory`:: (<>) Total amount of memory used for points across all shards assigned to the node. `points_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for points across all shards assigned to the node. `doc_values_memory`:: (<>) Total amount of memory used for doc values across all shards assigned to the node. `doc_values_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for doc values across all shards assigned to the node. `index_writer_memory`:: (<>) Total amount of memory used by all index writers across all shards assigned to the node. `index_writer_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used by all index writers across all shards assigned to the node. `version_map_memory`:: (<>) Total amount of memory used by all version maps across all shards assigned to the node. `version_map_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used by all version maps across all shards assigned to the node. `fixed_bit_set`:: (<>) Total amount of memory used by fixed bit sets across all shards assigned to the node. + Fixed bit sets are used for nested object field types and type filters for <> fields. `fixed_bit_set_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used by fixed bit sets across all shards assigned to the node. + Fixed bit sets are used for nested object field types and type filters for <> fields. `max_unsafe_auto_id_timestamp`:: (integer) Time of the most recently retried indexing request. Recorded in milliseconds since the {wikipedia}/Unix_time[Unix Epoch]. `file_sizes`:: (object) Contains statistics about the size of the segment file. + .Properties of `file_sizes` [%collapsible%open] ======== `size`:: (<>) Size of the segment file. `size_in_bytes`:: (integer) Size, in bytes, of the segment file. `description`:: (string) Description of the segment file. ======== ======= `translog`:: (object) Contains statistics about transaction log operations for the node. + .Properties of `translog` [%collapsible%open] ======= `operations`:: (integer) Number of transaction log operations. `size`:: (<>) Size of the transaction log. `size_in_bytes`:: (integer) Size, in bytes, of the transaction log. `uncommitted_operations`:: (integer) Number of uncommitted transaction log operations. `uncommitted_size`:: (<>) Size of uncommitted transaction log operations. `uncommitted_size_in_bytes`:: (integer) Size, in bytes, of uncommitted transaction log operations. `earliest_last_modified_age`:: (integer) Earliest last modified age for the transaction log. ======= `request_cache`:: (object) Contains statistics about the request cache across all shards assigned to the node. + .Properties of `request_cache` [%collapsible%open] ======= `memory_size`:: (<>) Memory used by the request cache. `memory_size_in_bytes`:: (integer) Memory, in bytes, used by the request cache. `evictions`:: (integer) Number of request cache operations. `hit_count`:: (integer) Number of request cache hits. `miss_count`:: (integer) Number of request cache misses. ======= `recovery`:: (object) Contains statistics about recovery operations for the node. + .Properties of `recovery` [%collapsible%open] ======= `current_as_source`:: (integer) Number of recoveries that used an index shard as a source. `current_as_target`:: (integer) Number of recoveries that used an index shard as a target. `throttle_time`:: (<>) Time by which recovery operations were delayed due to throttling. `throttle_time_in_millis`:: (integer) Time in milliseconds recovery operations were delayed due to throttling. ======= ====== [[cluster-nodes-stats-api-response-body-os]] `os`:: (object) Contains statistics about the operating system for the node. + .Properties of `os` [%collapsible%open] ====== `timestamp`:: (integer) Last time the operating system statistics were refreshed. Recorded in milliseconds since the {wikipedia}/Unix_time[Unix Epoch]. `cpu`:: (object) Contains statistics about CPU usage for the node. + .Properties of `cpu` [%collapsible%open] ======= `percent`:: (integer) Recent CPU usage for the whole system, or `-1` if not supported. `load_average`:: (object) Contains statistics about load averages on the system. + .Properties of `load_average` [%collapsible%open] ======== `1m`:: (float) One-minute load average on the system (field is not present if one-minute load average is not available). `5m`:: (float) Five-minute load average on the system (field is not present if five-minute load average is not available). `15m`:: (float) Fifteen-minute load average on the system (field is not present if fifteen-minute load average is not available). ======== ======= `mem`:: (object) Contains statistics about memory usage for the node. + .Properties of `mem` [%collapsible%open] ======= `total`:: (<>) Total amount of physical memory. `total_in_bytes`:: (integer) Total amount of physical memory in bytes. `free`:: (<>) Amount of free physical memory. `free_in_bytes`:: (integer) Amount of free physical memory in bytes. `used`:: (<>) Amount of used physical memory. `used_in_bytes`:: (integer) Amount of used physical memory in bytes. `free_percent`:: (integer) Percentage of free memory. `used_percent`:: (integer) Percentage of used memory. ======= `swap`:: (object) Contains statistics about swap space for the node. + .Properties of `swap` [%collapsible%open] ======= `total`:: (<>) Total amount of swap space. `total_in_bytes`:: (integer) Total amount of swap space in bytes. `free`:: (<>) Amount of free swap space. `free_in_bytes`:: (integer) Amount of free swap space in bytes. `used`:: (<>) Amount of used swap space. `used_in_bytes`:: (integer) Amount of used swap space in bytes. ======= `cgroup` (Linux only):: (object) Contains cgroup statistics for the node. + NOTE: For the cgroup stats to be visible, cgroups must be compiled into the kernel, the `cpu` and `cpuacct` cgroup subsystems must be configured and stats must be readable from `/sys/fs/cgroup/cpu` and `/sys/fs/cgroup/cpuacct`. + .Properties of `cgroup` [%collapsible%open] ======= `cpuacct` (Linux only):: (object) Contains statistics about `cpuacct` control group for the node. + .Properties of `cpuacct` [%collapsible%open] ======== `control_group` (Linux only):: (string) The `cpuacct` control group to which the {es} process belongs. `usage_nanos` (Linux only):: (integer) The total CPU time (in nanoseconds) consumed by all tasks in the same cgroup as the {es} process. ======== `cpu` (Linux only):: (object) Contains statistics about `cpu` control group for the node. + .Properties of `cpu` [%collapsible%open] ======== `control_group` (Linux only):: (string) The `cpu` control group to which the {es} process belongs. `cfs_period_micros` (Linux only):: (integer) The period of time (in microseconds) for how regularly all tasks in the same cgroup as the {es} process should have their access to CPU resources reallocated. `cfs_quota_micros` (Linux only):: (integer) The total amount of time (in microseconds) for which all tasks in the same cgroup as the {es} process can run during one period `cfs_period_micros`. `stat` (Linux only):: (object) Contains CPU statistics for the node. + .Properties of `stat` [%collapsible%open] ========= `number_of_elapsed_periods` (Linux only):: (integer) The number of reporting periods (as specified by `cfs_period_micros`) that have elapsed. `number_of_times_throttled` (Linux only):: (integer) The number of times all tasks in the same cgroup as the {es} process have been throttled. `time_throttled_nanos` (Linux only):: (integer) The total amount of time (in nanoseconds) for which all tasks in the same cgroup as the {es} process have been throttled. ========= ======== `memory` (Linux only):: (object) Contains statistics about the `memory` control group for the node. + .Properties of `memory` [%collapsible%open] ======== `control_group` (Linux only):: (string) The `memory` control group to which the {es} process belongs. `limit_in_bytes` (Linux only):: (string) The maximum amount of user memory (including file cache) allowed for all tasks in the same cgroup as the {es} process. This value can be too big to store in a `long`, so is returned as a string so that the value returned can exactly match what the underlying operating system interface returns. Any value that is too large to parse into a `long` almost certainly means no limit has been set for the cgroup. `usage_in_bytes` (Linux only):: (string) The total current memory usage by processes in the cgroup (in bytes) by all tasks in the same cgroup as the {es} process. This value is stored as a string for consistency with `limit_in_bytes`. ======== ======= ====== [[cluster-nodes-stats-api-response-body-process]] `process`:: (object) Contains process statistics for the node. + .Properties of `process` [%collapsible%open] ====== `timestamp`:: (integer) Last time the statistics were refreshed. Recorded in milliseconds since the {wikipedia}/Unix_time[Unix Epoch]. `open_file_descriptors`:: (integer) Number of opened file descriptors associated with the current or `-1` if not supported. `max_file_descriptors`:: (integer) Maximum number of file descriptors allowed on the system, or `-1` if not supported. `cpu`:: (object) Contains CPU statistics for the node. + .Properties of `cpu` [%collapsible%open] ======= `percent`:: (integer) CPU usage in percent, or `-1` if not known at the time the stats are computed. `total`:: (<>) CPU time used by the process on which the Java virtual machine is running. `total_in_millis`:: (integer) CPU time (in milliseconds) used by the process on which the Java virtual machine is running, or `-1` if not supported. ======= `mem`:: (object) Contains virtual memory statistics for the node. + .Properties of `mem` [%collapsible%open] ======= `total_virtual`:: (<>) Size of virtual memory that is guaranteed to be available to the running process. `total_virtual_in_bytes`:: (integer) Size in bytes of virtual memory that is guaranteed to be available to the running process. ======= ====== [[cluster-nodes-stats-api-response-body-jvm]] `jvm`:: (object) Contains Java Virtual Machine (JVM) statistics for the node. + .Properties of `jvm` [%collapsible%open] ====== `timestamp`:: (integer) Last time JVM statistics were refreshed. `uptime`:: (<>) JVM uptime. `uptime_in_millis`:: (integer) JVM uptime in milliseconds. `mem`:: (object) Contains JVM memory usage statistics for the node. + .Properties of `mem` [%collapsible%open] ======= `heap_used`:: (<>) Memory currently in use by the heap. `heap_used_in_bytes`:: (integer) Memory, in bytes, currently in use by the heap. `heap_used_percent`:: (integer) Percentage of memory currently in use by the heap. `heap_committed`:: (<>) Amount of memory available for use by the heap. `heap_committed_in_bytes`:: (integer) Amount of memory, in bytes, available for use by the heap. `heap_max`:: (<>) Maximum amount of memory available for use by the heap. `heap_max_in_bytes`:: (integer) Maximum amount of memory, in bytes, available for use by the heap. `non_heap_used`:: (<>) Non-heap memory used. `non_heap_used_in_bytes`:: (integer) Non-heap memory used, in bytes. `non_heap_committed`:: (<>) Amount of non-heap memory available. `non_heap_committed_in_bytes`:: (integer) Amount of non-heap memory available, in bytes. `pools`:: (object) Contains statistics about heap memory usage for the node. + .Properties of `pools` [%collapsible%open] ======== `young`:: (object) Contains statistics about memory usage by the young generation heap for the node. + .Properties of `young` [%collapsible%open] ========= `used`:: (<>) Memory used by the young generation heap. `used_in_bytes`:: (integer) Memory, in bytes, used by the young generation heap. `max`:: (<>) Maximum amount of memory available for use by the young generation heap. `max_in_bytes`:: (integer) Maximum amount of memory, in bytes, available for use by the young generation heap. `peak_used`:: (<>) Largest amount of memory historically used by the young generation heap. `peak_used_in_bytes`:: (integer) Largest amount of memory, in bytes, historically used by the young generation heap. `peak_max`:: (<>) Largest amount of memory historically used by the young generation heap. `peak_max_in_bytes`:: (integer) Largest amount of memory, in bytes, historically used by the young generation heap. ========= `survivor`:: (object) Contains statistics about memory usage by the survivor space for the node. + .Properties of `survivor` [%collapsible%open] ========= `used`:: (<>) Memory used by the survivor space. `used_in_bytes`:: (integer) Memory, in bytes, used by the survivor space. `max`:: (<>) Maximum amount of memory available for use by the survivor space. `max_in_bytes`:: (integer) Maximum amount of memory, in bytes, available for use by the survivor space. `peak_used`:: (<>) Largest amount of memory historically used by the survivor space. `peak_used_in_bytes`:: (integer) Largest amount of memory, in bytes, historically used by the survivor space. `peak_max`:: (<>) Largest amount of memory historically used by the survivor space. `peak_max_in_bytes`:: (integer) Largest amount of memory, in bytes, historically used by the survivor space. ========= `old`:: (object) Contains statistics about memory usage by the old generation heap for the node. + .Properties of `old` [%collapsible%open] ========= `used`:: (<>) Memory used by the old generation heap. `used_in_bytes`:: (integer) Memory, in bytes, used by the old generation heap. `max`:: (<>) Maximum amount of memory available for use by the old generation heap. `max_in_bytes`:: (integer) Maximum amount of memory, in bytes, available for use by the old generation heap. `peak_used`:: (<>) Largest amount of memory historically used by the old generation heap. `peak_used_in_bytes`:: (integer) Largest amount of memory, in bytes, historically used by the old generation heap. `peak_max`:: (<>) Highest memory limit historically available for use by the old generation heap. `peak_max_in_bytes`:: (integer) Highest memory limit, in bytes, historically available for use by the old generation heap. ========= ======== ======= `threads`:: (object) Contains statistics about JVM thread usage for the node. + .Properties of `threads` [%collapsible%open] ======= `count`:: (integer) Number of active threads in use by JVM. `peak_count`:: (integer) Highest number of threads used by JVM. ======= `gc`:: (object) Contains statistics about JVM garbage collectors for the node. + .Properties of `gc` [%collapsible%open] ======= `collectors`:: (object) Contains statistics about JVM garbage collectors for the node. + .Properties of `collectors` [%collapsible%open] ======== `young`:: (object) Contains statistics about JVM garbage collectors that collect young generation objects for the node. + .Properties of `young` [%collapsible%open] ========= `collection_count`:: (integer) Number of JVM garbage collectors that collect young generation objects. `collection_time`:: (<>) Total time spent by JVM collecting young generation objects. `collection_time_in_millis`:: (integer) Total time in milliseconds spent by JVM collecting young generation objects. ========= `old`:: (object) Contains statistics about JVM garbage collectors that collect old generation objects for the node. + .Properties of `old` [%collapsible%open] ========= `collection_count`:: (integer) Number of JVM garbage collectors that collect old generation objects. `collection_time`:: (<>) Total time spent by JVM collecting old generation objects. `collection_time_in_millis`:: (integer) Total time in milliseconds spent by JVM collecting old generation objects. ========= ======== ======= `buffer_pools`:: (object) Contains statistics about JVM buffer pools for the node. + .Properties of `buffer_pools` [%collapsible%open] ======= `mapped`:: (object) Contains statistics about mapped JVM buffer pools for the node. + .Properties of `mapped` [%collapsible%open] ======== `count`:: (integer) Number of mapped buffer pools. `used`:: (<>) Size of mapped buffer pools. `used_in_bytes`:: (integer) Size, in bytes, of mapped buffer pools. `total_capacity`:: (<>) Total capacity of mapped buffer pools. `total_capacity_in_bytes`:: (integer) Total capacity, in bytes, of mapped buffer pools. ======== `direct`:: (object) Contains statistics about direct JVM buffer pools for the node. + .Properties of `direct` [%collapsible%open] ======== `count`:: (integer) Number of direct buffer pools. `used`:: (<>) Size of direct buffer pools. `used_in_bytes`:: (integer) Size, in bytes, of direct buffer pools. `total_capacity`:: (<>) Total capacity of direct buffer pools. `total_capacity_in_bytes`:: (integer) Total capacity, in bytes, of direct buffer pools. ======== ======= `classes`:: (object) Contains statistics about classes loaded by JVM for the node. + .Properties of `classes` [%collapsible%open] ======= `current_loaded_count`:: (integer) Number of classes currently loaded by JVM. `total_loaded_count`:: (integer) Total number of classes loaded since the JVM started. `total_unloaded_count`:: (integer) Total number of classes unloaded since the JVM started. ======= ====== [[cluster-nodes-stats-api-response-body-threadpool]] `thread_pool`:: (object) Contains thread pool statistics for the node + .Properties of `thread_pool` [%collapsible%open] ====== ``:: (object) Contains statistics about the thread pool for the node. + .Properties of `` [%collapsible%open] ======= `threads`:: (integer) Number of threads in the thread pool. `queue`:: (integer) Number of tasks in queue for the thread pool. `active`:: (integer) Number of active threads in the thread pool. `rejected`:: (integer) Number of tasks rejected by the thread pool executor. `largest`:: (integer) Highest number of active threads in the thread pool. `completed`:: (integer) Number of tasks completed by the thread pool executor. ======= ====== [[cluster-nodes-stats-api-response-body-fs]] `fs`:: (object) Contains file store statistics for the node. + .Properties of `fs` [%collapsible%open] ====== `timestamp`:: (integer) Last time the file stores statistics were refreshed. Recorded in milliseconds since the {wikipedia}/Unix_time[Unix Epoch]. `total`:: (object) Contains statistics for all file stores of the node. + .Properties of `total` [%collapsible%open] ======= `total`:: (<>) Total size of all file stores. `total_in_bytes`:: (integer) Total size (in bytes) of all file stores. `free`:: (<>) Total unallocated disk space in all file stores. `free_in_bytes`:: (integer) Total number of unallocated bytes in all file stores. `available`:: (<>) Total disk space available to this Java virtual machine on all file stores. Depending on OS or process level restrictions, this might appear less than `free`. This is the actual amount of free disk space the {es} node can utilise. `available_in_bytes`:: (integer) Total number of bytes available to this Java virtual machine on all file stores. Depending on OS or process level restrictions, this might appear less than `free_in_bytes`. This is the actual amount of free disk space the {es} node can utilise. ======= [[cluster-nodes-stats-fs-data]] `data`:: (array of objects) List of all file stores. + .Properties of `data` [%collapsible%open] ======= `path`:: (string) Path to the file store. `mount`:: (string) Mount point of the file store (ex: /dev/sda2). `type`:: (string) Type of the file store (ex: ext4). `total`:: (<>) Total size of the file store. `total_in_bytes`:: (integer) Total size (in bytes) of the file store. `free`:: (<>) Total amount of unallocated disk space in the file store. `free_in_bytes`:: (integer) Total number of unallocated bytes in the file store. `available`:: (<>) Total amount of disk space available to this Java virtual machine on this file store. `available_in_bytes`:: (integer) Total number of bytes available to this Java virtual machine on this file store. ======= `io_stats` (Linux only):: (objects) Contains I/O statistics for the node. + .Properties of `io_stats` [%collapsible%open] ======= `devices` (Linux only):: (array) Array of disk metrics for each device that is backing an {es} data path. These disk metrics are probed periodically and averages between the last probe and the current probe are computed. + .Properties of `devices` [%collapsible%open] ======== `device_name` (Linux only):: (string) The Linux device name. `operations` (Linux only):: (integer) The total number of read and write operations for the device completed since starting {es}. `read_operations` (Linux only):: (integer) The total number of read operations for the device completed since starting {es}. `write_operations` (Linux only):: (integer) The total number of write operations for the device completed since starting {es}. `read_kilobytes` (Linux only):: (integer) The total number of kilobytes read for the device since starting {es}. `write_kilobytes` (Linux only):: (integer) The total number of kilobytes written for the device since starting {es}. ======== `operations` (Linux only):: (integer) The total number of read and write operations across all devices used by {es} completed since starting {es}. `read_operations` (Linux only):: (integer) The total number of read operations for across all devices used by {es} completed since starting {es}. `write_operations` (Linux only):: (integer) The total number of write operations across all devices used by {es} completed since starting {es}. `read_kilobytes` (Linux only):: (integer) The total number of kilobytes read across all devices used by {es} since starting {es}. `write_kilobytes` (Linux only):: (integer) The total number of kilobytes written across all devices used by {es} since starting {es}. ======= ====== [[cluster-nodes-stats-api-response-body-transport]] `transport`:: (object) Contains transport statistics for the node. + .Properties of `transport` [%collapsible%open] ====== `server_open`:: (integer) Current number of inbound TCP connections used for internal communication between nodes. `total_outbound_connections`:: (integer) The cumulative number of outbound transport connections that this node has opened since it started. Each transport connection may comprise multiple TCP connections but is only counted once in this statistic. Transport connections are typically <> so this statistic should remain constant in a stable cluster. `rx_count`:: (integer) Total number of RX (receive) packets received by the node during internal cluster communication. `rx_size`:: (<>) Size of RX packets received by the node during internal cluster communication. `rx_size_in_bytes`:: (integer) Size, in bytes, of RX packets received by the node during internal cluster communication. `tx_count`:: (integer) Total number of TX (transmit) packets sent by the node during internal cluster communication. `tx_size`:: (<>) Size of TX packets sent by the node during internal cluster communication. `tx_size_in_bytes`:: (integer) Size, in bytes, of TX packets sent by the node during internal cluster communication. ====== [[cluster-nodes-stats-api-response-body-http]] `http`:: (object) Contains http statistics for the node. + .Properties of `http` [%collapsible%open] ====== `current_open`:: (integer) Current number of open HTTP connections for the node. `total_opened`:: (integer) Total number of HTTP connections opened for the node. ====== [[cluster-nodes-stats-api-response-body-breakers]] `breakers`:: (object) Contains circuit breaker statistics for the node. + .Properties of `breakers` [%collapsible%open] ====== ``:: (object) Contains statistics for the circuit breaker. + .Properties of `` [%collapsible%open] ======= `limit_size_in_bytes`:: (integer) Memory limit, in bytes, for the circuit breaker. `limit_size`:: (<>) Memory limit for the circuit breaker. `estimated_size_in_bytes`:: (integer) Estimated memory used, in bytes, for the operation. `estimated_size`:: (<>) Estimated memory used for the operation. `overhead`:: (float) A constant that all estimates for the circuit breaker are multiplied with to calculate a final estimate. `tripped`:: (integer) Total number of times the circuit breaker has been triggered and prevented an out of memory error. ======= ====== [[cluster-nodes-stats-api-response-body-script]] `script`:: (object) Contains script statistics for the node. + .Properties of `script` [%collapsible%open] ====== `compilations`:: (integer) Total number of inline script compilations performed by the node. `cache_evictions`:: (integer) Total number of times the script cache has evicted old data. `compilation_limit_triggered`:: (integer) Total number of times the <> circuit breaker has limited inline script compilations. ====== [[cluster-nodes-stats-api-response-body-discovery]] `discovery`:: (object) Contains node discovery statistics for the node. + .Properties of `discovery` [%collapsible%open] ====== `cluster_state_queue`:: (object) Contains statistics for the cluster state queue of the node. + .Properties of `cluster_state_queue` [%collapsible%open] ======= `total`:: (integer) Total number of cluster states in queue. `pending`:: (integer) Number of pending cluster states in queue. `committed`:: (integer) Number of committed cluster states in queue. ======= `published_cluster_states`:: (object) Contains statistics for the published cluster states of the node. + .Properties of `published_cluster_states` [%collapsible%open] ======= `full_states`:: (integer) Number of published cluster states. `incompatible_diffs`:: (integer) Number of incompatible differences between published cluster states. `compatible_diffs`:: (integer) Number of compatible differences between published cluster states. ======= ====== [[cluster-nodes-stats-api-response-body-ingest]] `ingest`:: (object) Contains ingest statistics for the node. + .Properties of `ingest` [%collapsible%open] ====== `total`:: (object) Contains statistics about ingest operations for the node. + .Properties of `total` [%collapsible%open] ======= `count`:: (integer) Total number of documents ingested during the lifetime of this node. `time`:: (<>) Total time spent preprocessing ingest documents during the lifetime of this node. `time_in_millis`:: (integer) Total time, in milliseconds, spent preprocessing ingest documents during the lifetime of this node. `current`:: (integer) Total number of documents currently being ingested. `failed`:: (integer) Total number of failed ingest operations during the lifetime of this node. ======= `pipelines`:: (object) Contains statistics about ingest pipelines for the node. + .Properties of `pipelines` [%collapsible%open] ======= ``:: (object) Contains statistics about the ingest pipeline. + .Properties of `` [%collapsible%open] ======== `count`:: (integer) Number of documents preprocessed by the ingest pipeline. `time`:: (<>) Total time spent preprocessing documents in the ingest pipeline. `time_in_millis`:: (integer) Total time, in milliseconds, spent preprocessing documents in the ingest pipeline. `failed`:: (integer) Total number of failed operations for the ingest pipeline. `processors`:: (array of objects) Contains statistics for the ingest processors for the ingest pipeline. + .Properties of `processors` [%collapsible%open] ========= ``:: (object) Contains statistics for the ingest processor. + .Properties of `` [%collapsible%open] ========== `count`:: (integer) Number of documents transformed by the processor. `time`:: (<>) Time spent by the processor transforming documents. `time_in_millis`:: (integer) Time, in milliseconds, spent by the processor transforming documents. `current`:: (integer) Number of documents currently being transformed by the processor. `failed`:: (integer) Number of failed operations for the processor. ========== ========= ======== ======= ====== [[cluster-nodes-stats-api-response-body-indexing-pressure]] `indexing_pressure`:: (object) Contains <> statistics for the node. + .Properties of `indexing_pressure` [%collapsible%open] ====== `memory`:: (object) Contains statistics for memory consumption from indexing load. + .Properties of `` [%collapsible%open] ======= `current`:: (object) Contains statistics for current indexing load. + .Properties of `` [%collapsible%open] ======== `combined_coordinating_and_primary`:: (<>) Memory consumed by indexing requests in the coordinating or primary stage. This value is not the sum of coordinating and primary as a node can reuse the coordinating memory if the primary stage is executed locally. `combined_coordinating_and_primary_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the coordinating or primary stage. This value is not the sum of coordinating and primary as a node can reuse the coordinating memory if the primary stage is executed locally. `coordinating`:: (<>) Memory consumed by indexing requests in the coordinating stage. `coordinating_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the coordinating stage. `primary`:: (<>) Memory consumed by indexing requests in the primary stage. `primary_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the primary stage. `replica`:: (<>) Memory consumed by indexing requests in the replica stage. `replica_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the replica stage. `all`:: (<>) Memory consumed by indexing requests in the coordinating, primary, or replica stage. `all_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the coordinating, primary, or replica stage. ======== `total`:: (object) Contains statistics for the cumulative indexing load since the node started. + .Properties of `` [%collapsible%open] ======== `combined_coordinating_and_primary`:: (<>) Memory consumed by indexing requests in the coordinating or primary stage. This value is not the sum of coordinating and primary as a node can reuse the coordinating memory if the primary stage is executed locally. `combined_coordinating_and_primary_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the coordinating or primary stage. This value is not the sum of coordinating and primary as a node can reuse the coordinating memory if the primary stage is executed locally. `coordinating`:: (<>) Memory consumed by indexing requests in the coordinating stage. `coordinating_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the coordinating stage. `primary`:: (<>) Memory consumed by indexing requests in the primary stage. `primary_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the primary stage. `replica`:: (<>) Memory consumed by indexing requests in the replica stage. `replica_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the replica stage. `all`:: (<>) Memory consumed by indexing requests in the coordinating, primary, or replica stage. `all_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the coordinating, primary, or replica stage. `coordinating_rejections`:: (integer) Number of indexing requests rejected in the coordinating stage. `primary_rejections`:: (integer) Number of indexing requests rejected in the primary stage. `replica_rejections`:: (integer) Number of indexing requests rejected in the replica stage. ======== `limit`:: (<>) Configured memory limit for the indexing requests. Replica requests have an automatic limit that is 1.5x this value. `limit_in_bytes`:: (integer) Configured memory limit, in bytes, for the indexing requests. Replica requests have an automatic limit that is 1.5x this value. ======= ====== [[cluster-nodes-stats-api-response-body-adaptive-selection]] `adaptive_selection`:: (object) Contains adaptive selection statistics for the node. + .Properties of `adaptive_selection` [%collapsible%open] ====== `outgoing_searches`:: (integer) The number of outstanding search requests from the node these stats are for to the keyed node. `avg_queue_size`:: (integer) The exponentially weighted moving average queue size of search requests on the keyed node. `avg_service_time`:: (<>) The exponentially weighted moving average service time of search requests on the keyed node. `avg_service_time_ns`:: (integer) The exponentially weighted moving average service time, in nanoseconds, of search requests on the keyed node. `avg_response_time`:: (<>) The exponentially weighted moving average response time of search requests on the keyed node. `avg_response_time_ns`:: (integer) The exponentially weighted moving average response time, in nanoseconds, of search requests on the keyed node. `rank`:: (string) The rank of this node; used for shard selection when routing search requests. ====== ===== ==== [[cluster-nodes-stats-api-example]] ==== {api-examples-title} [source,console] -------------------------------------------------- # return just indices GET /_nodes/stats/indices # return just os and process GET /_nodes/stats/os,process # return just process for node with IP address 10.0.0.1 GET /_nodes/10.0.0.1/stats/process -------------------------------------------------- All stats can be explicitly requested via `/_nodes/stats/_all` or `/_nodes/stats?metric=_all`. You can get information about indices stats on `node`, `indices`, or `shards` level. [source,console] -------------------------------------------------- # Fielddata summarized by node GET /_nodes/stats/indices/fielddata?fields=field1,field2 # Fielddata summarized by node and index GET /_nodes/stats/indices/fielddata?level=indices&fields=field1,field2 # Fielddata summarized by node, index, and shard GET /_nodes/stats/indices/fielddata?level=shards&fields=field1,field2 # You can use wildcards for field names GET /_nodes/stats/indices/fielddata?fields=field* -------------------------------------------------- You can get statistics about search groups for searches executed on this node. [source,console] -------------------------------------------------- # All groups with all stats GET /_nodes/stats?groups=_all # Some groups from just the indices stats GET /_nodes/stats/indices?groups=foo,bar -------------------------------------------------- [[cluster-nodes-stats-ingest-ex]] ===== Retrieve ingest statistics only To return only ingest-related node statistics, set the `` path parameter to `ingest` and use the <> query parameter. [source,console] -------------------------------------------------- GET /_nodes/stats/ingest?filter_path=nodes.*.ingest -------------------------------------------------- You can use the `metric` and `filter_path` query parameters to get the same response. [source,console] -------------------------------------------------- GET /_nodes/stats?metric=ingest&filter_path=nodes.*.ingest -------------------------------------------------- To further refine the response, change the `filter_path` value. For example, the following request only returns ingest pipeline statistics. [source,console] -------------------------------------------------- GET /_nodes/stats?metric=ingest&filter_path=nodes.*.ingest.pipelines -------------------------------------------------- ",12334,True,2571.9673696826994,median "/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include ""hermes/VM/Operations.h"" #include ""hermes/Support/Conversions.h"" #include ""hermes/Support/OSCompat.h"" #include ""hermes/VM/Callable.h"" #include ""hermes/VM/Casting.h"" #include ""hermes/VM/JSArray.h"" #include ""hermes/VM/JSCallableProxy.h"" #include ""hermes/VM/JSError.h"" #include ""hermes/VM/JSGenerator.h"" #include ""hermes/VM/JSObject.h"" #include ""hermes/VM/JSRegExp.h"" #include ""hermes/VM/PrimitiveBox.h"" #include ""hermes/VM/Runtime.h"" #include ""hermes/VM/StringBuilder.h"" #include ""hermes/VM/StringPrimitive.h"" #include ""hermes/VM/StringView.h"" #include ""dtoa/dtoa.h"" #include ""llvh/ADT/SmallString.h"" #include #include namespace hermes { namespace vm { CallResult> stringToSymbolID( Runtime *runtime, PseudoHandle strPrim) { // Unique the string. return runtime->getIdentifierTable().getSymbolHandleFromPrimitive( runtime, std::move(strPrim)); } CallResult> valueToSymbolID( Runtime *runtime, Handle<> nameValHnd) { if (nameValHnd->isSymbol()) { return Handle::vmcast(nameValHnd); } // Convert the value to a string. auto res = toString_RJS(runtime, nameValHnd); if (res == ExecutionStatus::EXCEPTION) return ExecutionStatus::EXCEPTION; // Unique the string. return stringToSymbolID(runtime, std::move(*res)); } HermesValue typeOf(Runtime *runtime, Handle<> valueHandle) { switch (valueHandle->getTag()) { case UndefinedNullTag: return HermesValue::encodeStringValue(runtime->getPredefinedString( valueHandle->isUndefined() ? Predefined::undefined : Predefined::object)); break; case StrTag: return HermesValue::encodeStringValue( runtime->getPredefinedString(Predefined::string)); break; case BoolTag: return HermesValue::encodeStringValue( runtime->getPredefinedString(Predefined::boolean)); break; case SymbolTag: return HermesValue::encodeStringValue( runtime->getPredefinedString(Predefined::symbol)); break; case ObjectTag: if (vmisa(*valueHandle)) { return HermesValue::encodeStringValue( runtime->getPredefinedString(Predefined::function)); } else { return HermesValue::encodeStringValue( runtime->getPredefinedString(Predefined::object)); } break; default: assert(valueHandle->isNumber() && ""Invalid type.""); return HermesValue::encodeStringValue( runtime->getPredefinedString(Predefined::number)); break; } } OptValue toArrayIndex( Runtime *runtime, Handle strPrim) { auto view = StringPrimitive::createStringView(runtime, strPrim); return toArrayIndex(view); } OptValue toArrayIndex(StringView str) { auto len = str.length(); if (str.isASCII()) { const char *ptr = str.castToCharPtr(); return hermes::toArrayIndex(ptr, ptr + len); } const char16_t *ptr = str.castToChar16Ptr(); return hermes::toArrayIndex(ptr, ptr + len); } bool isSameValue(HermesValue x, HermesValue y) { if (x.getTag() != y.getTag()) { // If the tags are different, they must be different. return false; } assert( !x.isEmpty() && !x.isNativeValue() && ""Empty and Native Value cannot be compared""); // Strings are the only type that requires deep comparison. if (x.isString()) { // For strings, we compare each character in sequence. return x.getString()->equals(y.getString()); } // Otherwise they are identical if the raw bits are the same. return x.getRaw() == y.getRaw(); } bool isSameValueZero(HermesValue x, HermesValue y) { if (x.isNumber() && y.isNumber() && x.getNumber() == y.getNumber()) { // Takes care of +0 == -0. return true; } return isSameValue(x, y); } bool isPrimitive(HermesValue val) { assert(val.getTag() != EmptyInvalidTag && ""empty value encountered""); assert(val.getTag() != NativeValueTag && ""native value encountered""); return !val.isObject(); } CallResult ordinaryToPrimitive( Handle selfHandle, Runtime *runtime, PreferredType preferredType) { GCScope gcScope{runtime}; assert( preferredType != PreferredType::NONE && ""OrdinaryToPrimitive requires a type hint""); for (int i = 0; i < 2; ++i) { if (preferredType == PreferredType::STRING) { auto propRes = JSObject::getNamed_RJS( selfHandle, runtime, Predefined::getSymbolID(Predefined::toString)); if (propRes == ExecutionStatus::EXCEPTION) return ExecutionStatus::EXCEPTION; if (auto funcHandle = Handle::dyn_vmcast( runtime->makeHandle(std::move(*propRes)))) { auto callRes = funcHandle->executeCall0(funcHandle, runtime, selfHandle); if (callRes == ExecutionStatus::EXCEPTION) return ExecutionStatus::EXCEPTION; if (isPrimitive(callRes->get())) return callRes.toCallResultHermesValue(); } // This method failed. Try the other one. preferredType = PreferredType::NUMBER; } else { auto propRes = JSObject::getNamed_RJS( selfHandle, runtime, Predefined::getSymbolID(Predefined::valueOf)); if (propRes == ExecutionStatus::EXCEPTION) return ExecutionStatus::EXCEPTION; if (auto funcHandle = Handle::dyn_vmcast( runtime->makeHandle(std::move(*propRes)))) { auto callRes = funcHandle->executeCall0(funcHandle, runtime, selfHandle); if (callRes == ExecutionStatus::EXCEPTION) return ExecutionStatus::EXCEPTION; if (isPrimitive(callRes->get())) return callRes.toCallResultHermesValue(); } // This method failed. Try the other one. preferredType = PreferredType::STRING; } } // Nothing succeeded, time to give up. return runtime->raiseTypeError(""Cannot determine default value of object""); } /// ES5.1 9.1 CallResult toPrimitive_RJS(Runtime *runtime, Handle<> valueHandle, PreferredType hint) { assert( valueHandle->getTag() != EmptyInvalidTag && ""empty value is not allowed""); assert( valueHandle->getTag() != NativeValueTag && ""native value is not allowed""); if (valueHandle->getTag() != ObjectTag) return *valueHandle; // 4. Let exoticToPrim be GetMethod(input, @@toPrimitive). auto exoticToPrim = getMethod( runtime, valueHandle, runtime->makeHandle( Predefined::getSymbolID(Predefined::SymbolToPrimitive))); if (LLVM_UNLIKELY(exoticToPrim == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } // 6. If exoticToPrim is not undefined, then if (vmisa(exoticToPrim->getHermesValue())) { auto callable = runtime->makeHandle( dyn_vmcast(exoticToPrim->getHermesValue())); CallResult> resultRes = Callable::executeCall1( callable, runtime, valueHandle, HermesValue::encodeStringValue(runtime->getPredefinedString( hint == PreferredType::NONE ? Predefined::defaultStr : hint == PreferredType::STRING ? Predefined::string : Predefined::number))); if (LLVM_UNLIKELY(resultRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } PseudoHandle<> result = std::move(*resultRes); if (!result->isObject()) { return result.getHermesValue(); } return runtime->raiseTypeError( ""Symbol.toPrimitive function must return a primitive""); } // 7. If hint is ""default"", let hint be ""number"". // 8. Return OrdinaryToPrimitive(input,hint). return ordinaryToPrimitive( Handle::vmcast(valueHandle), runtime, hint == PreferredType::NONE ? PreferredType::NUMBER : hint); } bool toBoolean(HermesValue value) { switch (value.getTag()) { case EmptyInvalidTag: llvm_unreachable(""empty value""); case NativeValueTag: llvm_unreachable(""native value""); case UndefinedNullTag: return false; case BoolTag: return value.getBool(); case SymbolTag: case ObjectTag: return true; case StrTag: return value.getString()->getStringLength() != 0; default: { auto m = value.getNumber(); return !(m == 0 || std::isnan(m)); } } } /// ES5.1 9.8.1 static CallResult> numberToString( Runtime *runtime, double m) LLVM_NO_SANITIZE(""float-cast-overflow""); static CallResult> numberToString( Runtime *runtime, double m) { char buf8[hermes::NUMBER_TO_STRING_BUF_SIZE]; // Optimization: Fast-case for positive integers < 2^31 int32_t n = static_cast(m); if (m == static_cast(n) && n > 0) { // Write base 10 digits in reverse from end of buf8. char *p = buf8 + sizeof(buf8); do { *--p = '0' + (n % 10); n /= 10; } while (n); size_t len = buf8 + sizeof(buf8) - p; // Temporarily stop the propagation of removing. auto result = StringPrimitive::create(runtime, ASCIIRef(p, len)); if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } return createPseudoHandle(vmcast(*result)); } auto getPredefined = [runtime](Predefined::Str predefinedID) { return createPseudoHandle(runtime->getPredefinedString(predefinedID)); }; if (std::isnan(m)) return getPredefined(Predefined::NaN); if (m == 0) return getPredefined(Predefined::zero); if (m == std::numeric_limits::infinity()) return getPredefined(Predefined::Infinity); if (m == -std::numeric_limits::infinity()) return getPredefined(Predefined::NegativeInfinity); // After special cases, run the generic routine to convert. size_t len = hermes::numberToString(m, buf8, sizeof(buf8)); auto result = StringPrimitive::create(runtime, ASCIIRef(buf8, len)); if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } return createPseudoHandle(vmcast(*result)); } CallResult> toString_RJS( Runtime *runtime, Handle<> valueHandle) { HermesValue value = valueHandle.get(); StringPrimitive *result; switch (value.getTag()) { case EmptyInvalidTag: llvm_unreachable(""empty value""); case NativeValueTag: llvm_unreachable(""native value""); case StrTag: result = vmcast(value); break; case UndefinedNullTag: result = runtime->getPredefinedString( value.isUndefined() ? Predefined::undefined : Predefined::null); break; case BoolTag: result = value.getBool() ? runtime->getPredefinedString(Predefined::trueStr) : runtime->getPredefinedString(Predefined::falseStr); break; case ObjectTag: { auto res = toPrimitive_RJS(runtime, valueHandle, PreferredType::STRING); if (res == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } return toString_RJS(runtime, runtime->makeHandle(res.getValue())); } case SymbolTag: return runtime->raiseTypeError(""Cannot convert Symbol to string""); default: return numberToString(runtime, value.getNumber()); } return createPseudoHandle(result); } double parseIntWithRadix(const StringView str, int radix) { auto res = hermes::parseIntWithRadix(str, radix); return res ? res.getValue() : std::numeric_limits::quiet_NaN(); } /// ES5.1 9.3.1 static inline double stringToNumber( Runtime *runtime, Handle strPrim) { auto &idTable = runtime->getIdentifierTable(); // Fast check for special values (no extraneous whitespace). if (runtime->symbolEqualsToStringPrim( Predefined::getSymbolID(Predefined::Infinity), *strPrim)) { return std::numeric_limits::infinity(); } if (runtime->symbolEqualsToStringPrim( Predefined::getSymbolID(Predefined::PositiveInfinity), *strPrim)) { return std::numeric_limits::infinity(); } if (runtime->symbolEqualsToStringPrim( Predefined::getSymbolID(Predefined::NegativeInfinity), *strPrim)) { } if (runtime->symbolEqualsToStringPrim( Predefined::getSymbolID(Predefined::NaN), *strPrim)) { return std::numeric_limits::quiet_NaN(); } // Trim string to the interval [begin, end). auto orig = StringPrimitive::createStringView(runtime, strPrim); auto begin = orig.begin(); auto end = orig.end(); // Move begin and end to ignore whitespace. while (begin != end && (isWhiteSpaceChar(*begin) || isLineTerminatorChar(*begin))) { ++begin; } while (begin != end && (isWhiteSpaceChar(*(end - 1)) || isLineTerminatorChar(*(end - 1)))) { --end; } // Early return for empty strings (strings only containing whitespace). if (begin == end) { return 0; } // Trim the string. StringView str16 = orig.slice(begin, end); // Slow check for special values. // This should only run if user created a string with extra whitespace, // since normal uses would get caught by the initial check. if (LLVM_UNLIKELY(str16.equals(idTable.getStringView( runtime, Predefined::getSymbolID(Predefined::Infinity))))) { return std::numeric_limits::infinity(); } if (LLVM_UNLIKELY(str16.equals(idTable.getStringView( runtime, Predefined::getSymbolID(Predefined::PositiveInfinity))))) { return std::numeric_limits::infinity(); } if (LLVM_UNLIKELY(str16.equals(idTable.getStringView( runtime, Predefined::getSymbolID(Predefined::NegativeInfinity))))) { return -std::numeric_limits::infinity(); } if (LLVM_UNLIKELY(str16.equals(idTable.getStringView( runtime, Predefined::getSymbolID(Predefined::NaN))))) { return std::numeric_limits::quiet_NaN(); } auto len = str16.length(); // Parse hex codes, since dtoa doesn't do it. // FIXME: May be inaccurate for some hex values. // We need to check other sources first. if (len > 2) { if (str16[0] == u'0' && letterToLower(str16[1]) == u'x') { return parseIntWithRadix(str16.slice(2), 16); } if (str16[0] == u'0' && letterToLower(str16[1]) == u'o') { return parseIntWithRadix(str16.slice(2), 8); } if (str16[0] == u'0' && letterToLower(str16[1]) == u'b') { return parseIntWithRadix(str16.slice(2), 2); } } // Finally, copy 16 bit chars into 8 bit chars and call dtoa. llvh::SmallVector str8(len + 1); uint32_t i = 0; for (auto c16 : str16) { // Check to ensure we only have valid number characters now. if ((u'0' <= c16 && c16 <= u'9') || c16 == u'.' || letterToLower(c16) == u'e' || c16 == u'+' || c16 == u'-') { str8[i] = static_cast(c16); } else { return std::numeric_limits::quiet_NaN(); } ++i; } str8[len] = '\\0'; char *endPtr; double result = ::hermes_g_strtod(str8.data(), &endPtr); if (endPtr == str8.data() + len) { return result; } // If everything failed, return NaN. return std::numeric_limits::quiet_NaN(); } CallResult toNumber_RJS(Runtime *runtime, Handle<> valueHandle) { auto value = valueHandle.get(); double result; switch (value.getTag()) { case EmptyInvalidTag: llvm_unreachable(""empty value""); case NativeValueTag: llvm_unreachable(""native value""); case ObjectTag: { auto res = toPrimitive_RJS(runtime, valueHandle, PreferredType::NUMBER); if (res == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } return toNumber_RJS(runtime, runtime->makeHandle(res.getValue())); } case StrTag: result = stringToNumber(runtime, Handle::vmcast(valueHandle)); break; case UndefinedNullTag: result = value.isUndefined() ? std::numeric_limits::quiet_NaN() : +0.0; break; case BoolTag: result = value.getBool(); break; case SymbolTag: return runtime->raiseTypeError(""Cannot convert Symbol to number""); default: // Already have a number, just return it. return value; } return HermesValue::encodeDoubleValue(result); } CallResult toLength(Runtime *runtime, Handle<> valueHandle) { constexpr double maxLength = 9007199254740991.0; // 2**53 - 1 auto res = toInteger(runtime, valueHandle); if (res == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } auto len = res->getNumber(); if (len <= 0) { len = 0; } else if (len > maxLength) { len = maxLength; } return HermesValue::encodeDoubleValue(len); } CallResult toLengthU64(Runtime *runtime, Handle<> valueHandle) { constexpr double highestIntegralDouble = ((uint64_t)1 << std::numeric_limits::digits) - 1; auto res = toInteger(runtime, valueHandle); if (res == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } auto len = res->getNumber(); if (len <= 0) { len = 0; } else if (len > highestIntegralDouble) { len = highestIntegralDouble; } return len; } CallResult toIndex(Runtime *runtime, Handle<> valueHandle) { auto value = (valueHandle->isUndefined()) ? runtime->makeHandle(HermesValue::encodeDoubleValue(0)) : valueHandle; auto res = toInteger(runtime, value); if (res == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } auto integerIndex = res->getNumber(); if (integerIndex < 0) { return runtime->raiseRangeError(""A negative value cannot be an index""); } auto integerIndexHandle = runtime->makeHandle(HermesValue::encodeDoubleValue(integerIndex)); res = toLength(runtime, integerIndexHandle); if (res == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } auto index = res.getValue(); if (index.getNumber() != integerIndex) { return runtime->raiseRangeError( ""The value given for the index must be between 0 and 2 ^ 53 - 1""); } return res; } CallResult toInteger(Runtime *runtime, Handle<> valueHandle) { auto res = toNumber_RJS(runtime, valueHandle); if (res == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } double num = res->getNumber(); double result; if (std::isnan(num)) { result = 0; } else { result = oscompat::trunc(num); } return HermesValue::encodeDoubleValue(result); } /// Conversion of HermesValues to integers. template static inline CallResult toInt( Runtime *runtime, Handle<> valueHandle) { auto res = toNumber_RJS(runtime, valueHandle); if (res == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } double num = res->getNumber(); T result = static_cast(hermes::truncateToInt32(num)); return HermesValue::encodeNumberValue(result); } CallResult toInt8(Runtime *runtime, Handle<> valueHandle) { return toInt(runtime, valueHandle); } CallResult toInt16(Runtime *runtime, Handle<> valueHandle) { return toInt(runtime, valueHandle); } CallResult toInt32_RJS(Runtime *runtime, Handle<> valueHandle) { return toInt(runtime, valueHandle); } CallResult toUInt8(Runtime *runtime, Handle<> valueHandle) { return toInt(runtime, valueHandle); } uint8_t toUInt8Clamp(double number) { // 3. If number is NaN, return +0. // 4. If number <= 0, return +0. // Not < so that NaN coerces to 0. // NOTE: this check correctly rounds numbers less than 0.5 if (!(number >= 0.5)) { return 0; } // 5. If number >= 255, return 255. if (number > 255) { return 255; } // The next steps are the equivalent of the spec's round-to-even requirement. // Round up and then do the even/odd check. double toTruncate = number + 0.5; uint8_t x = static_cast(toTruncate); // If it was a tie (i.e. it ended in 0.5) then if (x == toTruncate) { // number ended in 0.5 and was rounded up, reduce by 1 if odd, // else leave the same. // That is the same as unsetting the least significant bit. return (x & ~1); } else { // number did not end in 0.5, don't need to check the parity. return x; } } CallResult toUInt8Clamp(Runtime *runtime, Handle<> valueHandle) { // 1. Let number be toNumber_RJS(argument) auto res = toNumber_RJS(runtime, valueHandle); if (res == ExecutionStatus::EXCEPTION) { // 2. ReturnIfAbrupt(number) return ExecutionStatus::EXCEPTION; } return HermesValue::encodeNumberValue(toUInt8Clamp(res->getNumber())); } CallResult toUInt16(Runtime *runtime, Handle<> valueHandle) { return toInt(runtime, valueHandle); } CallResult toUInt32_RJS(Runtime *runtime, Handle<> valueHandle) { return toInt(runtime, valueHandle); } CallResult> getPrimitivePrototype( Runtime *runtime, Handle<> base) { switch (base->getTag()) { case EmptyInvalidTag: llvm_unreachable(""empty value""); case NativeValueTag: llvm_unreachable(""native value""); case ObjectTag: llvm_unreachable(""object value""); case UndefinedNullTag: return runtime->raiseTypeError( base->isUndefined() ? ""Cannot convert undefined value to object"" : ""Cannot convert null value to object""); case StrTag: return Handle::vmcast(&runtime->stringPrototype); case BoolTag: return Handle::vmcast(&runtime->booleanPrototype); case SymbolTag: return Handle::vmcast(&runtime->symbolPrototype); default: assert(base->isNumber() && ""Unknown tag in getPrimitivePrototype.""); return Handle::vmcast(&runtime->numberPrototype); } } CallResult toObject(Runtime *runtime, Handle<> valueHandle) { auto value = valueHandle.get(); switch (value.getTag()) { case EmptyInvalidTag: llvm_unreachable(""empty value""); case NativeValueTag: llvm_unreachable(""native value""); case UndefinedNullTag: return runtime->raiseTypeError( value.isUndefined() ? ""Cannot convert undefined value to object"" : ""Cannot convert null value to object""); case ObjectTag: return value; case BoolTag: return JSBoolean::create( runtime, value.getBool(), Handle::vmcast(&runtime->booleanPrototype)) .getHermesValue(); case StrTag: { auto res = JSString::create( runtime, runtime->makeHandle(value.getString()), Handle::vmcast(&runtime->stringPrototype)); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } return res->getHermesValue(); } case SymbolTag: return JSSymbol::create( runtime, *Handle::vmcast(valueHandle), Handle::vmcast(&runtime->symbolPrototype)) .getHermesValue(); default: assert(valueHandle->isNumber() && ""Unknown tag in toObject.""); return JSNumber::create( runtime, value.getNumber(), Handle::vmcast(&runtime->numberPrototype)) .getHermesValue(); } } ExecutionStatus amendPropAccessErrorMsgWithPropName( Runtime *runtime, Handle<> valueHandle, llvh::StringRef operationStr, SymbolID id) { if (!valueHandle->isNull() && !valueHandle->isUndefined()) { // If value is not null/undefined, fall back to the original exception. return ExecutionStatus::EXCEPTION; } assert(!runtime->getThrownValue().isEmpty() && ""Error must have been thrown""); // Clear the error first because we will re-throw. runtime->clearThrownValue(); // Construct an error message that contains the property name. llvh::StringRef valueStr = valueHandle->isNull() ? ""null"" : ""undefined""; return runtime->raiseTypeError( TwineChar16(""Cannot "") + operationStr + "" property '"" + runtime->getIdentifierTable().getStringView(runtime, id) + ""' of "" + valueStr); } /// Implement a comparison operator. First both operands a converted to /// primitives. If they both end up being strings, a lexicographical comparison /// is performed. Otherwise both operands are converted to numbers and the /// values are compared. /// \\param oper is the comparison operator to use when comparing numbers. #define IMPLEMENT_COMPARISON_OP(name, oper) \\ CallResult name( \\ Runtime *runtime, Handle<> leftHandle, Handle<> rightHandle) { \\ auto resLeft = \\ toPrimitive_RJS(runtime, leftHandle, PreferredType::NUMBER); \\ if (resLeft == ExecutionStatus::EXCEPTION) \\ return ExecutionStatus::EXCEPTION; \\ MutableHandle<> left(runtime, resLeft.getValue()); \\ \\ auto resRight = \\ toPrimitive_RJS(runtime, rightHandle, PreferredType::NUMBER); \\ if (resRight == ExecutionStatus::EXCEPTION) \\ return ExecutionStatus::EXCEPTION; \\ MutableHandle<> right(runtime, resRight.getValue()); \\ \\ /* If both are strings, we must do a string comparison.*/ \\ if (left->isString() && right->isString()) { \\ return left->getString()->compare(right->getString()) oper 0; \\ } \\ \\ /* Convert both to a number and compare the numbers. */ \\ resLeft = toNumber_RJS(runtime, left); \\ if (resLeft == ExecutionStatus::EXCEPTION) \\ return ExecutionStatus::EXCEPTION; \\ left = resLeft.getValue(); \\ resRight = toNumber_RJS(runtime, right); \\ if (resRight == ExecutionStatus::EXCEPTION) \\ return ExecutionStatus::EXCEPTION; \\ right = resRight.getValue(); \\ \\ return left->getNumber() oper right->getNumber(); \\ } IMPLEMENT_COMPARISON_OP(lessOp_RJS, <); IMPLEMENT_COMPARISON_OP(greaterOp_RJS, >); IMPLEMENT_COMPARISON_OP(lessEqualOp_RJS, <=); IMPLEMENT_COMPARISON_OP(greaterEqualOp_RJS, >=); CallResult abstractEqualityTest_RJS(Runtime *runtime, Handle<> xHandle, Handle<> yHandle) { MutableHandle<> x{runtime, xHandle.get()}; MutableHandle<> y{runtime, yHandle.get()}; abstractEqualityTailCall: // Same type comparison. if (x->getTag() == y->getTag() || (x->isNumber() && y->isNumber())) { bool result; switch (x->getTag()) { case EmptyInvalidTag: llvm_unreachable(""can't compare empties""); case NativeValueTag: llvm_unreachable(""native value""); case UndefinedNullTag: result = true; break; case StrTag: result = x->getString()->equals(y->getString()); break; case ObjectTag: // Return true if x and y refer to the same object. result = x->getPointer() == y->getPointer(); break; case BoolTag: result = x->getBool() == y->getBool(); break; case SymbolTag: result = x->getSymbol() == y->getSymbol(); break; default: { result = x->getNumber() == y->getNumber(); break; } } return HermesValue::encodeBoolValue(result); } // If the types are different, combine tags for use in the switch statement. // Use NativeValueTag as a placeholder for numbers. assert( !x->isNativeValue() && !x->isEmpty() && ""invalid value for comparison""); assert( !y->isNativeValue() && !y->isEmpty() && ""invalid value for comparison""); constexpr TagKind NumberTag = NativeValueTag; // Tag numbers as numbers, and use default tag values for everything else. TagKind xType = x->isNumber() ? NumberTag : x->getTag(); TagKind yType = y->isNumber() ? NumberTag : y->getTag(); switch (HermesValue::combineTags(xType, yType)) { case HermesValue::combineTags(UndefinedNullTag, UndefinedNullTag): return HermesValue::encodeBoolValue(true); case HermesValue::combineTags(NumberTag, StrTag): return HermesValue::encodeBoolValue( x->getNumber() == stringToNumber(runtime, Handle::vmcast(y))); case HermesValue::combineTags(StrTag, NumberTag): return HermesValue::encodeBoolValue( stringToNumber(runtime, Handle::vmcast(x)) == y->getNumber()); case HermesValue::combineTags(BoolTag, NumberTag): // Do both conversions and check numerical equality. return HermesValue::encodeBoolValue(x->getBool() == y->getNumber()); case HermesValue::combineTags(BoolTag, StrTag): // Do string parsing and check double equality. return HermesValue::encodeBoolValue( x->getBool() == stringToNumber(runtime, Handle::vmcast(y))); case HermesValue::combineTags(BoolTag, ObjectTag): x = HermesValue::encodeDoubleValue(x->getBool()); goto abstractEqualityTailCall; case HermesValue::combineTags(NumberTag, BoolTag): return HermesValue::encodeBoolValue(x->getNumber() == y->getBool()); case HermesValue::combineTags(StrTag, BoolTag): return HermesValue::encodeBoolValue( stringToNumber(runtime, Handle::vmcast(x)) == y->getBool()); case HermesValue::combineTags(ObjectTag, BoolTag): y = HermesValue::encodeDoubleValue(y->getBool()); goto abstractEqualityTailCall; case HermesValue::combineTags(StrTag, ObjectTag): case HermesValue::combineTags(SymbolTag, ObjectTag): case HermesValue::combineTags(NumberTag, ObjectTag): { auto status = toPrimitive_RJS(runtime, y, PreferredType::NONE); if (status == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } y = status.getValue(); goto abstractEqualityTailCall; } case HermesValue::combineTags(ObjectTag, StrTag): case HermesValue::combineTags(ObjectTag, SymbolTag): case HermesValue::combineTags(ObjectTag, NumberTag): { auto status = toPrimitive_RJS(runtime, x, PreferredType::NONE); if (status == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } x = status.getValue(); goto abstractEqualityTailCall; } default: // Final case, return false. return HermesValue::encodeBoolValue(false); } // namespace vm } // namespace hermes bool strictEqualityTest(HermesValue x, HermesValue y) { // Numbers are special because they can have different tags and they don't // obey bit-exact equality (because of NaN). if (x.isNumber()) return y.isNumber() && x.getNumber() == y.getNumber(); // If they are not numbers and are bit exact, they must be the same. if (x.getRaw() == y.getRaw()) return true; // All the rest of the cases need to have the same tags. if (x.getTag() != y.getTag()) return false; // The only remaining case is string, which needs a deep comparison. return x.isString() && x.getString()->equals(y.getString()); } CallResult addOp_RJS(Runtime *runtime, Handle<> xHandle, Handle<> yHandle) { auto resX = toPrimitive_RJS(runtime, xHandle, PreferredType::NONE); if (resX == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } auto x = runtime->makeHandle(resX.getValue()); auto resY = toPrimitive_RJS(runtime, yHandle, PreferredType::NONE); if (resY == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } auto y = runtime->makeHandle(resY.getValue()); // If one of the values is a string, concatenate as strings. if (x->isString() || y->isString()) { auto resX = toString_RJS(runtime, x); if (resX == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } auto xStr = runtime->makeHandle(std::move(*resX)); auto resY = toString_RJS(runtime, y); if (resY == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } auto yStr = runtime->makeHandle(std::move(*resY)); return StringPrimitive::concat(runtime, xStr, yStr); } // Add the numbers since neither are strings. resX = toNumber_RJS(runtime, x); if (LLVM_UNLIKELY(resX == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } auto xNum = resX.getValue().getNumber(); resY = toNumber_RJS(runtime, y); if (LLVM_UNLIKELY(resY == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } auto yNum = resY.getValue().getNumber(); return HermesValue::encodeDoubleValue(xNum + yNum); } static const size_t MIN_RADIX = 2; static const size_t MAX_RADIX = 36; static inline char toRadixChar(unsigned x, unsigned radix) { const char chars[] = ""0123456789abcdefghijklmnopqrstuvwxyz""; static_assert(sizeof(chars) - 1 == MAX_RADIX, ""Invalid chars array""); assert( x < radix && x < std::strlen(chars) && ""invalid number to radix conversion""); return chars[x]; } /// \\return the exponent component of the double \\p x. static inline int doubleExponent(double x) { int e; std::frexp(x, &e); return e; } Handle numberToStringWithRadix(Runtime *runtime, double number, unsigned radix) { (void)MIN_RADIX; (void)MAX_RADIX; assert(MIN_RADIX <= radix && radix <= MAX_RADIX && ""Invalid radix""); // Two parts of the final result: integer part and fractional part. llvh::SmallString<64> result{}; // Used to store just the fractional part of the string (not including '.'). llvh::SmallString<32> fStr{}; // If negative, treat as if positive and add a '-' later. bool negative = false; if (number < 0) { negative = true; number = -number; } // Split number into integer and fractional parts. double iPart; double fPart = std::modf(number, &iPart); // If there's a fractional part, convert it and store in fStr. if (fPart != 0) { // Distance to the next double value. double next = oscompat::nextafter(number, std::numeric_limits::infinity()); double minDenorm = oscompat::nextafter(0.0, std::numeric_limits::infinity()); // Precision of the input (half the distance to the next double). // We only compute digits up to that precision. // Ensure that delta > 0 by clamping it by the min denormalized positive // double number. double delta = std::max(0.5 * (next - number), minDenorm); while (fPart > delta) { // Multiply by radix to find the next digit. fPart *= radix; delta *= radix; // Write the next digit. unsigned digit = static_cast(fPart); fStr.push_back(toRadixChar(digit, radix)); // Remove current digit from fPart to prepare for next iteration. fPart -= digit; // Round-to-even. if (fPart > 0.5 || (fPart == 0.5 && (digit & 1))) { // Must round up, necessitating changing written digits. if (fPart + delta > 1) { // Round because printing the next closest double would not give // closer results than rounding. The distance between the next // double and this one is large enough that at this point, we're // doing worse than rounding up if we were to print out the next // double precisely. while (true) { // Rounding requires backtracking to fix everything up. if (fStr.size() == 0) { // Rounding failed to stop in the fractional part, // so carry over to the integral part. ++iPart; break; } // Iterator to the last digit of the string. char &c = fStr.back(); unsigned digitForC = c <= '9' ? c - '0' : c - 'a' + 10; if (digitForC + 1 < radix) { // Can increment this digit, and we're done. c = toRadixChar(digitForC + 1, radix); break; } // We weren't able to increment, so this will be a trailing 0, // which we don't want to keep around anyway. So, pop the last // digit off the string and continue on. fStr.pop_back(); } // Rounded off the number, done writing the fractional string. break; } } } } // Now, create the integer part. if (iPart == 0) { result.push_back('0'); } else { // Write the number backwards, then reverse it. This simplifies the code. // Physical mantissa size. // Hidden bit is not included because it's not after the decimal point in // the binary scientific notation representation of a double. // We use this to calculate whether we have the precision required to know // what the next digit is going to be. constexpr const int MANTISSA_SIZE = DBL_MANT_DIG - 1; // Handle trailing zeros. while (doubleExponent(iPart / radix) > MANTISSA_SIZE) { // (iPart / radix) doesn't have enough precision to be useful here, // because its exponent is larger than the number of bits that the // mantissa can encode. So, just put a trailing zero, divide by radix, // and move on to the next digit. result.push_back('0'); iPart /= radix; } // Print the rest of the string when we know we have enough precision to // do so. while (iPart > 0) { // Cast digit to int because we know 2 <= digit <= 36. int digit = static_cast(std::fmod(iPart, radix)); result.push_back(toRadixChar(digit, radix)); iPart = (iPart - digit) / radix; } // Int string was generated in reverse, so flip it. std::reverse(result.begin(), result.end()); } // Concatenate the fractional string on if it exists. if (!fStr.empty()) { result += '.'; result += fStr; } // Account for negative numbers. if (negative) { result.insert(result.begin(), '-'); } return runtime->makeHandle(runtime->ignoreAllocationFailure( StringPrimitive::create(runtime, result))); } CallResult> getMethod(Runtime *runtime, Handle<> O, Handle<> key) { GCScopeMarkerRAII gcScope{runtime}; auto objRes = toObject(runtime, O); if (LLVM_UNLIKELY(objRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } auto obj = runtime->makeHandle(*objRes); auto funcRes = JSObject::getComputed_RJS(obj, runtime, key); if (LLVM_UNLIKELY(funcRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } if ((*funcRes)->isUndefined() || (*funcRes)->isNull()) { return PseudoHandle<>::create(HermesValue::encodeUndefinedValue()); } if (!vmisa(funcRes->get())) { return runtime->raiseTypeError(""Could not get callable method from object""); } return funcRes; } CallResult getIterator( Runtime *runtime, Handle<> obj, llvh::Optional> methodOpt) { MutableHandle method{runtime}; if (LLVM_LIKELY(!methodOpt.hasValue())) { auto methodRes = getMethod( runtime, obj, runtime->makeHandle( Predefined::getSymbolID(Predefined::SymbolIterator))); if (LLVM_UNLIKELY(methodRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } if (!vmisa(methodRes->getHermesValue())) { return runtime->raiseTypeError(""iterator method is not callable""); } method = vmcast(methodRes->getHermesValue()); } else { method = **methodOpt; } auto iteratorRes = Callable::executeCall0(method, runtime, obj); if (LLVM_UNLIKELY(iteratorRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } if (LLVM_UNLIKELY(!(*iteratorRes)->isObject())) { return runtime->raiseTypeError(""iterator is not an object""); } auto iterator = runtime->makeHandle(std::move(*iteratorRes)); CallResult> nextMethodRes = JSObject::getNamed_RJS( iterator, runtime, Predefined::getSymbolID(Predefined::next)); if (LLVM_UNLIKELY(nextMethodRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } // We perform this check prior to returning, because every function in the JS // library which gets an iterator immediately calls the 'next' function. if (!vmisa(nextMethodRes->get())) { return runtime->raiseTypeError( ""'next' method on iterator must be callable""); } auto nextMethod = Handle::vmcast(runtime->makeHandle(std::move(*nextMethodRes))); return IteratorRecord{iterator, nextMethod}; } CallResult> iteratorNext( Runtime *runtime, const IteratorRecord &iteratorRecord, llvh::Optional> value) { GCScopeMarkerRAII marker{runtime}; auto resultRes = value ? Callable::executeCall1( iteratorRecord.nextMethod, runtime, iteratorRecord.iterator, value->getHermesValue()) : Callable::executeCall0( iteratorRecord.nextMethod, runtime, iteratorRecord.iterator); if (LLVM_UNLIKELY(resultRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } if (LLVM_UNLIKELY(!(*resultRes)->isObject())) { return runtime->raiseTypeError(""iterator.next() did not return an object""); } return PseudoHandle::vmcast(std::move(*resultRes)); } CallResult> iteratorStep( Runtime *runtime, const IteratorRecord &iteratorRecord) { auto resultRes = iteratorNext(runtime, iteratorRecord); if (LLVM_UNLIKELY(resultRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } Handle result = runtime->makeHandle(std::move(*resultRes)); auto completeRes = JSObject::getNamed_RJS( result, runtime, Predefined::getSymbolID(Predefined::done)); if (LLVM_UNLIKELY(completeRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } if (toBoolean(completeRes->get())) { return Runtime::makeNullHandle(); } return result; } ExecutionStatus iteratorClose( Runtime *runtime, Handle iterator, Handle<> completion) { ExecutionStatus completionStatus = completion->isEmpty() ? ExecutionStatus::RETURNED : ExecutionStatus::EXCEPTION; // 4. Let innerResult be GetMethod(iterator, ""return""). // Do this lazily: innerResult is only actually used if GetMethod returns // a callable which, when called, doesn't throw. Defer storing to innerResult // until that point. auto returnRes = getMethod( runtime, iterator, runtime->makeHandle(Predefined::getSymbolID(Predefined::returnStr))); MutableHandle<> innerResult{runtime}; if (LLVM_LIKELY(returnRes != ExecutionStatus::EXCEPTION)) { if (!vmisa(returnRes->getHermesValue())) { runtime->setThrownValue(*completion); return completionStatus; } Handle returnFn = runtime->makeHandle(vmcast(returnRes->getHermesValue())); auto innerResultRes = Callable::executeCall0(returnFn, runtime, iterator); if (LLVM_UNLIKELY(innerResultRes == ExecutionStatus::EXCEPTION)) { if (isUncatchableError(runtime->getThrownValue())) { // If the call to return threw an uncatchable exception, that overrides // the completion, since the point of an uncatchable exception is to // prevent more JS from executing. return ExecutionStatus::EXCEPTION; } // If the error is catchable, suppress it temporarily below in lieu // of the returnRes exception by writing to innerResultException. // Spec text overwrites the value in `innerResult`. } else { innerResult = std::move(*innerResultRes); } } // Runtime::thrownValue now contains the innerResult's exception if it // was thrown. // GetMethod error here is deliberately suppressed (no ""?"" in the spec). if (completionStatus == ExecutionStatus::EXCEPTION) { // 6. If completion.[[Type]] is throw, return Completion(completion). // Note: Overrides the innerResult exception. runtime->setThrownValue(*completion); return ExecutionStatus::EXCEPTION; } if (LLVM_UNLIKELY(!runtime->getThrownValue().isEmpty())) { // 7. If innerResult.[[Type]] is throw, return Completion(innerResult). // Note: innerResult exception is still in Runtime::thrownValue, // so there is no need to set it again. return ExecutionStatus::EXCEPTION; } if (!innerResult->isObject()) { // 8. If Type(innerResult.[[Value]]) is not Object, // throw a TypeError exception. return runtime->raiseTypeError( ""iterator.return() did not return an object""); } return ExecutionStatus::RETURNED; } bool isUncatchableError(HermesValue value) { if (auto *jsError = dyn_vmcast(value)) { return !jsError->catchable(); } return false; } Handle createIterResultObject(Runtime *runtime, Handle<> value, bool done) { auto objHandle = runtime->makeHandle(JSObject::create(runtime)); auto status = JSObject::defineOwnProperty( objHandle, runtime, Predefined::getSymbolID(Predefined::value), DefinePropertyFlags::getDefaultNewPropertyFlags(), value); (void)status; assert( status != ExecutionStatus::EXCEPTION && *status && ""put own value property cannot fail""); status = JSObject::defineOwnProperty( objHandle, runtime, Predefined::getSymbolID(Predefined::done), DefinePropertyFlags::getDefaultNewPropertyFlags(), Runtime::getBoolValue(done)); assert( status != ExecutionStatus::EXCEPTION && *status && ""put own value property cannot fail""); return objHandle; } CallResult> speciesConstructor( Handle O, Runtime *runtime, Handle defaultConstructor) { // construct from the ""constructor"" property in self if that is defined, else // use the default one. auto res = JSObject::getNamed_RJS( O, runtime, Predefined::getSymbolID(Predefined::constructor)); if (res == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } PseudoHandle<> cons = std::move(*res); if (cons->isUndefined()) { return defaultConstructor; } if (!cons->isObject()) { return runtime->raiseTypeError( ""Constructor must be an object if it is not undefined""); } // There is no @@species (no Symbols yet), so we'll assume that there was // no other constructor specified. return defaultConstructor; } bool isConstructor(Runtime *runtime, HermesValue value) { return isConstructor(runtime, dyn_vmcast(value)); } bool isConstructor(Runtime *runtime, Callable *callable) { // This is not a complete definition, since ES6 and later define member // functions of objects to not be constructors; however, Hermes does not have // ES6 classes implemented yet, so we cannot check for that case. if (!callable) { return false; } // We traverse the BoundFunction target chain to find the eventual target. while (BoundFunction *b = dyn_vmcast(callable)) { callable = b->getTarget(runtime); } // If it is a bytecode function, check the flags. if (auto *func = dyn_vmcast(callable)) { auto *cb = func->getCodeBlock(); // Even though it doesn't make sense logically, we need to compile the // function in order to access it flags. cb->lazyCompile(runtime); return !func->getCodeBlock()->getHeaderFlags().isCallProhibited(true); } // We check for NativeFunction since those are defined to not be // constructible, with the exception of NativeConstructor. if (!vmisa(callable) || vmisa(callable)) { return true; } // JSCallableProxy is a NativeFunction, but may or may not be a // constructor, so we ask it. if (auto *cproxy = dyn_vmcast(callable)) { return cproxy->isConstructor(runtime); } return false; } CallResult ordinaryHasInstance(Runtime *runtime, Handle<> constructor, Handle<> object) { // 1. If IsCallable(C) is false, return false. if (!vmisa(*constructor)) { return false; } Callable *ctor = vmcast(*constructor); BoundFunction *bound; // 2. If C has a [[BoundTargetFunction]] internal slot, then while (LLVM_UNLIKELY(bound = dyn_vmcast(ctor))) { // 2a. Let BC be the value of C’s [[BoundTargetFunction]] internal slot. // 2b. Return InstanceofOperator(O,BC) (see 12.9.4). // Note that we can do this with the loop instead, // because bound->getTarget() must be a Callable, and Callables cannot // redefine @@hasInstance (non-configurable). // Callables call this function directly from their @@hasInstance // function. ctor = bound->getTarget(runtime); } // At this point 'ctor' is the actual function with a prototype. assert(ctor != nullptr && ""ctor must not be null""); // 3. If Type(O) is not Object, return false. if (LLVM_UNLIKELY(!object->isObject())) { return false; } // 4. Let P be Get(C, ""prototype""). auto propRes = JSObject::getNamed_RJS( runtime->makeHandle(ctor), runtime, Predefined::getSymbolID(Predefined::prototype)); if (LLVM_UNLIKELY(propRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } // 5. If Type(P) is not Object, throw a TypeError exception. Handle ctorPrototype = runtime->makeHandle( PseudoHandle::dyn_vmcast(std::move(*propRes))); if (LLVM_UNLIKELY(!ctorPrototype)) { return runtime->raiseTypeError( ""function's '.prototype' is not an object in 'instanceof'""); } // 6.1.7.3 Invariants of the Essential Internal Methods notes that // detection of infinite prototype chains is not enforceable as an // invariant if exotic objects exist in the chain. Most of the // time, ScopedNativeDepthTracker will detect this. Here, we need to // check that we're not repeating forever. Since ordinary object // chains are verified at the time the parent is set, we count Proxy // objects. Thus, any length chain of ordinary objects is ok. constexpr unsigned int kMaxProxyCount = 1024; unsigned int proxyCount = 0; MutableHandle head{runtime, vmcast(object.get())}; GCScopeMarkerRAII gcScope{runtime}; // 6. Repeat while (true) { // 6a. Let O be O.[[GetPrototypeOf]](). CallResult> parentRes = JSObject::getPrototypeOf(head, runtime); if (LLVM_UNLIKELY(parentRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } // 6b. If O is null, return false. if (!*parentRes) { return false; } // 6c. If SameValue(P, O) is true, return true. if (parentRes->get() == ctorPrototype.get()) { return true; } if (head->isProxyObject()) { ++proxyCount; if (proxyCount > kMaxProxyCount) { return runtime->raiseRangeError( ""Maximum prototype chain length exceeded""); } } head = parentRes->get(); gcScope.flush(); } } CallResult instanceOfOperator_RJS( Runtime *runtime, Handle<> object, Handle<> constructor) { // 1. If Type(C) is not Object, throw a TypeError exception. if (LLVM_UNLIKELY(!constructor->isObject())) { return runtime->raiseTypeError( ""right operand of 'instanceof' is not an object""); } // Fast path: Function.prototype[Symbol.hasInstance] is non-configurable // and non-writable (ES6.0 19.2.3.6), so we directly run its behavior here. // Simply call through to ordinaryHasInstance. if (vmisa(*constructor)) { return ordinaryHasInstance(runtime, constructor, object); } // 2. Let instOfHandler be GetMethod(C,@@hasInstance). CallResult> instOfHandlerRes = JSObject::getNamed_RJS( Handle::vmcast(constructor), runtime, Predefined::getSymbolID(Predefined::SymbolHasInstance)); if (LLVM_UNLIKELY(instOfHandlerRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } auto instOfHandler = runtime->makeHandle(std::move(*instOfHandlerRes)); // 4. If instOfHandler is not undefined, then if (!instOfHandler->isUndefined()) { // 5. Return ToBoolean(Call(instOfHandler, C, «O»)). if (!vmisa(*instOfHandler)) { return runtime->raiseTypeError(""instanceof handler must be callable""); } auto callRes = Callable::executeCall1( Handle::vmcast(instOfHandler), runtime, constructor, *object); if (LLVM_UNLIKELY(callRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } return toBoolean(callRes->get()); } // 6. If IsCallable(C) is false, throw a TypeError exception. if (!vmisa(*constructor)) { return runtime->raiseTypeError( ""right operand of 'instanceof' is not callable""); } // 7. Return OrdinaryHasInstance(C, O). return ordinaryHasInstance(runtime, constructor, object); } /// ES6.0 7.2.8 /// Returns true if the object is a JSRegExp or has a Symbol.match property that /// evaluates to true. CallResult isRegExp(Runtime *runtime, Handle<> arg) { // 1. If Type(argument) is not Object, return false. if (!arg->isObject()) { return false; } Handle obj = Handle::vmcast(arg); // 2. Let isRegExp be Get(argument, @@match). auto propRes = JSObject::getNamed_RJS( obj, runtime, Predefined::getSymbolID(Predefined::SymbolMatch)); // 3. ReturnIfAbrupt(isRegExp). if (LLVM_UNLIKELY(propRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } // 4. If isRegExp is not undefined, return ToBoolean(isRegExp). if (!(*propRes)->isUndefined()) { return toBoolean(propRes->get()); } // 5. If argument has a [[RegExpMatcher]] internal slot, return true. // 6. Return false. return vmisa(arg.get()); } CallResult> symbolDescriptiveString( Runtime *runtime, Handle sym) { auto desc = runtime->makeHandle( runtime->getStringPrimFromSymbolID(*sym)); SafeUInt32 descLen(desc->getStringLength()); descLen.add(8); auto builder = StringBuilder::createStringBuilder(runtime, descLen); if (LLVM_UNLIKELY(builder == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } builder->appendASCIIRef({""Symbol("", 7}); builder->appendStringPrim(desc); builder->appendCharacter(')'); return builder->getStringPrimitive(); } CallResult isArray(Runtime *runtime, JSObject *obj) { if (!obj) { return false; } while (true) { if (vmisa(obj)) { return true; } if (LLVM_LIKELY(!obj->isProxyObject())) { return false; } if (JSProxy::isRevoked(obj, runtime)) { return runtime->raiseTypeError(""Proxy has been revoked""); } obj = JSProxy::getTarget(obj, runtime).get(); assert(obj && ""target of non-revoked Proxy is null""); } } CallResult isConcatSpreadable(Runtime *runtime, Handle<> value) { auto O = Handle::dyn_vmcast(value); if (!O) { return false; } CallResult> spreadable = JSObject::getNamed_RJS( O, runtime, Predefined::getSymbolID(Predefined::SymbolIsConcatSpreadable)); if (LLVM_UNLIKELY(spreadable == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } if (!(*spreadable)->isUndefined()) { return toBoolean(spreadable->get()); } return isArray(runtime, *O); } ExecutionStatus toPropertyDescriptor( Handle<> obj, Runtime *runtime, DefinePropertyFlags &flags, MutableHandle<> &valueOrAccessor) { GCScopeMarkerRAII gcMarker{runtime}; // Verify that the attributes argument is also an object. auto attributes = Handle::dyn_vmcast(obj); if (!attributes) { return runtime->raiseTypeError( ""Object.defineProperty() Attributes argument is not an object""); } NamedPropertyDescriptor desc; // Get enumerable property of the attributes. if (JSObject::getNamedDescriptor( attributes, runtime, Predefined::getSymbolID(Predefined::enumerable), desc)) { auto propRes = JSObject::getNamed_RJS( attributes, runtime, Predefined::getSymbolID(Predefined::enumerable), PropOpFlags().plusThrowOnError()); if (LLVM_UNLIKELY(propRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } flags.enumerable = toBoolean(propRes->get()); flags.setEnumerable = true; } // Get configurable property of the attributes. if (JSObject::getNamedDescriptor( attributes, runtime, Predefined::getSymbolID(Predefined::configurable), desc)) { auto propRes = JSObject::getNamed_RJS( attributes, runtime, Predefined::getSymbolID(Predefined::configurable), PropOpFlags().plusThrowOnError()); if (LLVM_UNLIKELY(propRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } flags.configurable = toBoolean(propRes->get()); flags.setConfigurable = true; } // Get value property of the attributes. if (JSObject::getNamedDescriptor( attributes, runtime, Predefined::getSymbolID(Predefined::value), desc)) { auto propRes = JSObject::getNamed_RJS( attributes, runtime, Predefined::getSymbolID(Predefined::value), PropOpFlags().plusThrowOnError()); if (LLVM_UNLIKELY(propRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } valueOrAccessor = std::move(*propRes); flags.setValue = true; } // Get writable property of the attributes. if (JSObject::getNamedDescriptor( attributes, runtime, Predefined::getSymbolID(Predefined::writable), desc)) { auto propRes = JSObject::getNamed_RJS( attributes, runtime, Predefined::getSymbolID(Predefined::writable), PropOpFlags().plusThrowOnError()); if (LLVM_UNLIKELY(propRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } flags.writable = toBoolean(propRes->get()); flags.setWritable = true; } // Get getter property of the attributes. MutableHandle getterPtr{runtime}; if (JSObject::getNamedDescriptor( attributes, runtime, Predefined::getSymbolID(Predefined::get), desc)) { auto propRes = JSObject::getNamed_RJS( attributes, runtime, Predefined::getSymbolID(Predefined::get), PropOpFlags().plusThrowOnError()); if (LLVM_UNLIKELY(propRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } flags.setGetter = true; PseudoHandle<> getter = std::move(*propRes); if (LLVM_LIKELY(!getter->isUndefined())) { getterPtr = dyn_vmcast(getter.get()); if (LLVM_UNLIKELY(!getterPtr)) { return runtime->raiseTypeError( ""Invalid property descriptor. Getter must be a function.""); } } } // Get setter property of the attributes. MutableHandle setterPtr{runtime}; if (JSObject::getNamedDescriptor( attributes, runtime, Predefined::getSymbolID(Predefined::set), desc)) { auto propRes = JSObject::getNamed_RJS( attributes, runtime, Predefined::getSymbolID(Predefined::set), PropOpFlags().plusThrowOnError()); if (LLVM_UNLIKELY(propRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } flags.setSetter = true; PseudoHandle<> setter = std::move(*propRes); if (LLVM_LIKELY(!setter->isUndefined())) { setterPtr = PseudoHandle::dyn_vmcast(std::move(setter)); if (LLVM_UNLIKELY(!setterPtr)) { return runtime->raiseTypeError( ""Invalid property descriptor. Setter must be a function.""); } } } // Construct property accessor if getter/setter is set. if (flags.setSetter || flags.setGetter) { if (flags.setValue) { return runtime->raiseTypeError( ""Invalid property descriptor. Can't set both accessor and value.""); } if (flags.setWritable) { return runtime->raiseTypeError( ""Invalid property descriptor. Can't set both accessor and writable.""); } auto crtRes = PropertyAccessor::create(runtime, getterPtr, setterPtr); if (LLVM_UNLIKELY(crtRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } valueOrAccessor = *crtRes; } return ExecutionStatus::RETURNED; } CallResult objectFromPropertyDescriptor( Runtime *runtime, ComputedPropertyDescriptor desc, Handle<> valueOrAccessor) { Handle obj = runtime->makeHandle(JSObject::create(runtime)); DefinePropertyFlags dpf = DefinePropertyFlags::getDefaultNewPropertyFlags(); if (!desc.flags.accessor) { // Data Descriptor auto result = JSObject::defineOwnProperty( obj, runtime, Predefined::getSymbolID(Predefined::value), dpf, valueOrAccessor, PropOpFlags().plusThrowOnError()); assert( result != ExecutionStatus::EXCEPTION && ""defineOwnProperty() failed on a new object""); if (result == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } result = JSObject::defineOwnProperty( obj, runtime, Predefined::getSymbolID(Predefined::writable), dpf, Runtime::getBoolValue(desc.flags.writable), PropOpFlags().plusThrowOnError()); assert( result != ExecutionStatus::EXCEPTION && ""defineOwnProperty() failed on a new object""); if (result == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } } else { // Accessor auto *accessor = vmcast(valueOrAccessor.get()); auto getter = runtime->makeHandle( accessor->getter ? HermesValue::encodeObjectValue(accessor->getter.get(runtime)) : HermesValue::encodeUndefinedValue()); auto setter = runtime->makeHandle( accessor->setter ? HermesValue::encodeObjectValue(accessor->setter.get(runtime)) : HermesValue::encodeUndefinedValue()); auto result = JSObject::defineOwnProperty( obj, runtime, Predefined::getSymbolID(Predefined::get), dpf, getter, PropOpFlags().plusThrowOnError()); assert( result != ExecutionStatus::EXCEPTION && ""defineOwnProperty() failed on a new object""); if (result == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } result = JSObject::defineOwnProperty( obj, runtime, Predefined::getSymbolID(Predefined::set), dpf, setter, PropOpFlags().plusThrowOnError()); assert( result != ExecutionStatus::EXCEPTION && ""defineOwnProperty() failed on a new object""); if (result == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } } auto result = JSObject::defineOwnProperty( obj, runtime, Predefined::getSymbolID(Predefined::enumerable), dpf, Runtime::getBoolValue(desc.flags.enumerable), PropOpFlags().plusThrowOnError()); assert( result != ExecutionStatus::EXCEPTION && ""defineOwnProperty() failed on a new object""); if (result == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } result = JSObject::defineOwnProperty( obj, runtime, Predefined::getSymbolID(Predefined::configurable), dpf, Runtime::getBoolValue(desc.flags.configurable), PropOpFlags().plusThrowOnError()); assert( result != ExecutionStatus::EXCEPTION && ""defineOwnProperty() failed on a new object""); if (result == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } return obj.getHermesValue(); } } // namespace vm } // namespace hermes ",16131,True,3142.855116078707,median "/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #define DEBUG_TYPE ""gc"" #include ""hermes/VM/GC.h"" #include ""hermes/Platform/Logging.h"" #include ""hermes/Support/ErrorHandling.h"" #include ""hermes/Support/OSCompat.h"" #include ""hermes/VM/CellKind.h"" #include ""hermes/VM/JSWeakMapImpl.h"" #include ""hermes/VM/RootAndSlotAcceptorDefault.h"" #include ""hermes/VM/Runtime.h"" #include ""hermes/VM/SmallHermesValue-inline.h"" #include ""hermes/VM/VTable.h"" #include ""llvh/Support/Debug.h"" #include ""llvh/Support/FileSystem.h"" #include ""llvh/Support/Format.h"" #include ""llvh/Support/raw_os_ostream.h"" #include ""llvh/Support/raw_ostream.h"" #include #include #include #include using llvh::dbgs; using llvh::format; namespace hermes { namespace vm { const char GCBase::kNaturalCauseForAnalytics[] = ""natural""; const char GCBase::kHandleSanCauseForAnalytics[] = ""handle-san""; GCBase::GCBase( GCCallbacks *gcCallbacks, PointerBase *pointerBase, const GCConfig &gcConfig, std::shared_ptr crashMgr, HeapKind kind) : gcCallbacks_(gcCallbacks), pointerBase_(pointerBase), crashMgr_(crashMgr), heapKind_(kind), analyticsCallback_(gcConfig.getAnalyticsCallback()), recordGcStats_(gcConfig.getShouldRecordStats()), // Start off not in GC. inGC_(false), name_(gcConfig.getName()), allocationLocationTracker_(this), samplingAllocationTracker_(this), #ifdef HERMESVM_SANITIZE_HANDLES sanitizeRate_(gcConfig.getSanitizeConfig().getSanitizeRate()), #endif tripwireCallback_(gcConfig.getTripwireConfig().getCallback()), tripwireLimit_(gcConfig.getTripwireConfig().getLimit()) #ifndef NDEBUG , randomizeAllocSpace_(gcConfig.getShouldRandomizeAllocSpace()) #endif { buildMetadataTable(); #ifdef HERMESVM_PLATFORM_LOGGING hermesLog( ""HermesGC"", ""Initialisation (Init: %dMB, Max: %dMB, Tripwire: %dMB)"", gcConfig.getInitHeapSize() >> 20, gcConfig.getMaxHeapSize() >> 20, gcConfig.getTripwireConfig().getLimit() >> 20); #endif // HERMESVM_PLATFORM_LOGGING #ifdef HERMESVM_SANITIZE_HANDLES const std::minstd_rand::result_type seed = gcConfig.getSanitizeConfig().getRandomSeed() >= 0 ? gcConfig.getSanitizeConfig().getRandomSeed() : std::random_device()(); if (sanitizeRate_ > 0.0 && sanitizeRate_ < 1.0) { llvh::errs() << ""Warning: you are using handle sanitization with random sampling.\\n"" << ""Sanitize Rate: ""; llvh::write_double(llvh::errs(), sanitizeRate_, llvh::FloatStyle::Percent); llvh::errs() << ""\\n"" << ""Sanitize Rate Seed: "" << seed << ""\\n"" << ""Re-run with -gc-sanitize-handles-random-seed="" << seed << "" for deterministic crashes.\\n""; } randomEngine_.seed(seed); #endif } GCBase::GCCycle::GCCycle( GCBase *gc, OptValue gcCallbacksOpt, std::string extraInfo) : gc_(gc), gcCallbacksOpt_(gcCallbacksOpt), extraInfo_(std::move(extraInfo)), previousInGC_(gc_->inGC_) { if (!previousInGC_) { if (gcCallbacksOpt_.hasValue()) { gcCallbacksOpt_.getValue()->onGCEvent( GCEventKind::CollectionStart, extraInfo_); } gc_->inGC_ = true; } } GCBase::GCCycle::~GCCycle() { if (!previousInGC_) { gc_->inGC_ = false; if (gcCallbacksOpt_.hasValue()) { gcCallbacksOpt_.getValue()->onGCEvent( GCEventKind::CollectionEnd, extraInfo_); } } } void GCBase::runtimeWillExecute() { if (recordGcStats_ && !execStartTimeRecorded_) { execStartTime_ = std::chrono::steady_clock::now(); execStartCPUTime_ = oscompat::thread_cpu_time(); oscompat::num_context_switches( startNumVoluntaryContextSwitches_, startNumInvoluntaryContextSwitches_); execStartTimeRecorded_ = true; } } std::error_code GCBase::createSnapshotToFile(const std::string &fileName) { std::error_code code; llvh::raw_fd_ostream os(fileName, code, llvh::sys::fs::FileAccess::FA_Write); if (code) { return code; } createSnapshot(os); return std::error_code{}; } namespace { constexpr HeapSnapshot::NodeID objectIDForRootSection( RootAcceptor::Section section) { // Since root sections start at zero, and in IDTracker the root sections // start one past the reserved GC root, this number can be added to // do conversions. return GCBase::IDTracker::reserved( static_cast( static_cast( GCBase::IDTracker::ReservedObjectID::GCRoots) + 1 + static_cast(section))); } // Abstract base class for all snapshot acceptors. struct SnapshotAcceptor : public RootAndSlotAcceptorWithNamesDefault { using RootAndSlotAcceptorWithNamesDefault::accept; SnapshotAcceptor(PointerBase *base, HeapSnapshot &snap) : RootAndSlotAcceptorWithNamesDefault(base), snap_(snap) {} void acceptHV(HermesValue &hv, const char *name) override { if (hv.isPointer()) { GCCell *ptr = static_cast(hv.getPointer()); accept(ptr, name); } } void acceptSHV(SmallHermesValue &hv, const char *name) override { if (hv.isPointer()) { GCCell *ptr = static_cast(hv.getPointer(pointerBase_)); accept(ptr, name); } } protected: HeapSnapshot &snap_; }; struct PrimitiveNodeAcceptor : public SnapshotAcceptor { using SnapshotAcceptor::accept; PrimitiveNodeAcceptor( PointerBase *base, HeapSnapshot &snap, GCBase::IDTracker &tracker) : SnapshotAcceptor(base, snap), tracker_(tracker) {} // Do nothing for any value except a number. void accept(GCCell *&ptr, const char *name) override {} void acceptHV(HermesValue &hv, const char *) override { if (hv.isNumber()) { seenNumbers_.insert(hv.getNumber()); } } void acceptSHV(SmallHermesValue &hv, const char *) override { if (hv.isNumber()) { seenNumbers_.insert(hv.getNumber(pointerBase_)); } } void writeAllNodes() { // Always write out the nodes for singletons. snap_.beginNode(); snap_.endNode( HeapSnapshot::NodeType::Object, ""undefined"", GCBase::IDTracker::reserved( GCBase::IDTracker::ReservedObjectID::Undefined), 0, 0); snap_.beginNode(); snap_.endNode( HeapSnapshot::NodeType::Object, ""null"", GCBase::IDTracker::reserved(GCBase::IDTracker::ReservedObjectID::Null), 0, 0); snap_.beginNode(); snap_.endNode( HeapSnapshot::NodeType::Object, ""true"", GCBase::IDTracker::reserved(GCBase::IDTracker::ReservedObjectID::True), 0, 0); snap_.beginNode(); snap_.endNode( HeapSnapshot::NodeType::Object, ""false"", GCBase::IDTracker::reserved(GCBase::IDTracker::ReservedObjectID::False), 0, 0); for (double num : seenNumbers_) { // A number never has any edges, so just make a node for it. snap_.beginNode(); // Convert the number value to a string, according to the JS conversion // routines. char buf[hermes::NUMBER_TO_STRING_BUF_SIZE]; size_t len = hermes::numberToString(num, buf, sizeof(buf)); snap_.endNode( HeapSnapshot::NodeType::Number, llvh::StringRef{buf, len}, tracker_.getNumberID(num), // Numbers are zero-sized in the heap because they're stored inline. 0, 0); } } private: GCBase::IDTracker &tracker_; // Track all numbers that are seen in a heap pass, and only emit one node for // each of them. llvh::DenseSet seenNumbers_; }; struct EdgeAddingAcceptor : public SnapshotAcceptor, public WeakRefAcceptor { using SnapshotAcceptor::accept; EdgeAddingAcceptor(GCBase &gc, HeapSnapshot &snap) : SnapshotAcceptor(gc.getPointerBase(), snap), gc_(gc) {} void accept(GCCell *&ptr, const char *name) override { if (!ptr) { return; } snap_.addNamedEdge( HeapSnapshot::EdgeType::Internal, llvh::StringRef::withNullAsEmpty(name), gc_.getObjectID(ptr)); } void acceptHV(HermesValue &hv, const char *name) override { if (auto id = gc_.getSnapshotID(hv)) { snap_.addNamedEdge( HeapSnapshot::EdgeType::Internal, llvh::StringRef::withNullAsEmpty(name), id.getValue()); } } void acceptSHV(SmallHermesValue &shv, const char *name) override { HermesValue hv = shv.toHV(pointerBase_); acceptHV(hv, name); } void accept(WeakRefBase &wr) override { WeakRefSlot *slot = wr.unsafeGetSlot(); if (slot->state() == WeakSlotState::Free) { // If the slot is free, there's no edge to add. return; } if (!slot->hasPointer()) { // Filter out empty refs from adding edges. return; } // Assume all weak pointers have no names, and are stored in an array-like // structure. std::string indexName = std::to_string(nextEdge_++); snap_.addNamedEdge( HeapSnapshot::EdgeType::Weak, indexName, gc_.getObjectID(slot->getPointer())); } void acceptSym(SymbolID sym, const char *name) override { if (sym.isInvalid()) { return; } snap_.addNamedEdge( HeapSnapshot::EdgeType::Internal, llvh::StringRef::withNullAsEmpty(name), gc_.getObjectID(sym)); } private: GCBase &gc_; // For unnamed edges, use indices instead. unsigned nextEdge_{0}; }; struct SnapshotRootSectionAcceptor : public SnapshotAcceptor, public WeakAcceptorDefault { using SnapshotAcceptor::accept; using WeakRootAcceptor::acceptWeak; SnapshotRootSectionAcceptor(PointerBase *base, HeapSnapshot &snap) : SnapshotAcceptor(base, snap), WeakAcceptorDefault(base) {} void accept(GCCell *&, const char *) override { // While adding edges to root sections, there's no need to do anything for // pointers. } void accept(WeakRefBase &wr) override { // Same goes for weak refs. } void acceptWeak(GCCell *&ptr) override { // Same goes for weak pointers. } void beginRootSection(Section section) override { // Make an element edge from the super root to each root section. snap_.addIndexedEdge( HeapSnapshot::EdgeType::Element, rootSectionNum_++, objectIDForRootSection(section)); } void endRootSection() override { // Do nothing for the end of the root section. } private: // v8's roots start numbering at 1. int rootSectionNum_{1}; }; struct SnapshotRootAcceptor : public SnapshotAcceptor, public WeakAcceptorDefault { using SnapshotAcceptor::accept; using WeakRootAcceptor::acceptWeak; SnapshotRootAcceptor(GCBase &gc, HeapSnapshot &snap) : SnapshotAcceptor(gc.getPointerBase(), snap), WeakAcceptorDefault(gc.getPointerBase()), gc_(gc) {} void accept(GCCell *&ptr, const char *name) override { pointerAccept(ptr, name, false); } void acceptWeak(GCCell *&ptr) override { pointerAccept(ptr, nullptr, true); } void accept(WeakRefBase &wr) override { WeakRefSlot *slot = wr.unsafeGetSlot(); if (slot->state() == WeakSlotState::Free) { // If the slot is free, there's no edge to add. return; } if (!slot->hasPointer()) { // Filter out empty refs from adding edges. return; } pointerAccept(slot->getPointer(), nullptr, true); } void acceptSym(SymbolID sym, const char *name) override { if (sym.isInvalid()) { return; } auto nameRef = llvh::StringRef::withNullAsEmpty(name); const auto id = gc_.getObjectID(sym); if (!nameRef.empty()) { snap_.addNamedEdge(HeapSnapshot::EdgeType::Internal, nameRef, id); } else { // Unnamed edges get indices. snap_.addIndexedEdge(HeapSnapshot::EdgeType::Element, nextEdge_++, id); } } void provideSnapshot( const std::function &func) override { func(snap_); } void beginRootSection(Section section) override { assert( currentSection_ == Section::InvalidSection && ""beginRootSection called while previous section is open""); snap_.beginNode(); currentSection_ = section; } void endRootSection() override { // A root section creates a synthetic node with that name and makes edges // come from that root. static const char *rootNames[] = { // Parentheses around the name is adopted from V8's roots. #define ROOT_SECTION(name) ""("" #name "")"", #include ""hermes/VM/RootSections.def"" }; snap_.endNode( HeapSnapshot::NodeType::Synthetic, rootNames[static_cast(currentSection_)], objectIDForRootSection(currentSection_), // The heap visualizer doesn't like it when these synthetic nodes have a // size (it describes them as living in the heap). 0, 0); currentSection_ = Section::InvalidSection; // Reset the edge counter, so each root section's unnamed edges start at // zero. nextEdge_ = 0; } private: GCBase &gc_; llvh::DenseSet seenIDs_; // For unnamed edges, use indices instead. unsigned nextEdge_{0}; Section currentSection_{Section::InvalidSection}; void pointerAccept(GCCell *ptr, const char *name, bool weak) { assert( currentSection_ != Section::InvalidSection && ""accept called outside of begin/end root section pair""); if (!ptr) { return; } const auto id = gc_.getObjectID(ptr); if (!seenIDs_.insert(id).second) { // Already seen this node, don't add another edge. return; } auto nameRef = llvh::StringRef::withNullAsEmpty(name); if (!nameRef.empty()) { snap_.addNamedEdge( weak ? HeapSnapshot::EdgeType::Weak : HeapSnapshot::EdgeType::Internal, nameRef, id); } else if (weak) { std::string numericName = std::to_string(nextEdge_++); snap_.addNamedEdge(HeapSnapshot::EdgeType::Weak, numericName.c_str(), id); } else { // Unnamed edges get indices. snap_.addIndexedEdge(HeapSnapshot::EdgeType::Element, nextEdge_++, id); } } }; } // namespace void GCBase::createSnapshot(GC *gc, llvh::raw_ostream &os) { JSONEmitter json(os); HeapSnapshot snap(json, gcCallbacks_->getStackTracesTree()); const auto rootScan = [gc, &snap, this]() { { // Make the super root node and add edges to each root section. SnapshotRootSectionAcceptor rootSectionAcceptor(getPointerBase(), snap); // The super root has a single element pointing to the ""(GC roots)"" // synthetic node. v8 also has some ""shortcut"" edges to things like the // global object, but those don't seem necessary for correctness. snap.beginNode(); snap.addIndexedEdge( HeapSnapshot::EdgeType::Element, 1, IDTracker::reserved(IDTracker::ReservedObjectID::GCRoots)); snap.endNode( HeapSnapshot::NodeType::Synthetic, """", IDTracker::reserved(IDTracker::ReservedObjectID::SuperRoot), 0, 0); snapshotAddGCNativeNodes(snap); snap.beginNode(); markRoots(rootSectionAcceptor, true); markWeakRoots(rootSectionAcceptor, /*markLongLived*/ true); snapshotAddGCNativeEdges(snap); snap.endNode( HeapSnapshot::NodeType::Synthetic, ""(GC roots)"", static_cast( IDTracker::reserved(IDTracker::ReservedObjectID::GCRoots)), 0, 0); } { // Make a node for each root section and add edges into the actual heap. // Within a root section, there might be duplicates. The root acceptor // filters out duplicate edges because there cannot be duplicate edges to // nodes reachable from the super root. SnapshotRootAcceptor rootAcceptor(*gc, snap); markRoots(rootAcceptor, true); markWeakRoots(rootAcceptor, /*markLongLived*/ true); } gcCallbacks_->visitIdentifiers([&snap, this]( SymbolID sym, const StringPrimitive *str) { snap.beginNode(); if (str) { snap.addNamedEdge( HeapSnapshot::EdgeType::Internal, ""description"", getObjectID(str)); } snap.endNode( HeapSnapshot::NodeType::Symbol, convertSymbolToUTF8(sym), idTracker_.getObjectID(sym), sizeof(SymbolID), 0); }); }; snap.beginSection(HeapSnapshot::Section::Nodes); rootScan(); // Add all primitive values as nodes if they weren't added before. // This must be done as a step before adding any edges to these nodes. // In particular, custom edge adders might try to add edges to primitives that // haven't been recorded yet. // The acceptor is recording some state between objects, so define it outside // the loop. PrimitiveNodeAcceptor primitiveAcceptor( getPointerBase(), snap, getIDTracker()); SlotVisitorWithNames primitiveVisitor{ primitiveAcceptor}; // Add a node for each object in the heap. const auto snapshotForObject = [&snap, &primitiveVisitor, gc, this](GCCell *cell) { auto &allocationLocationTracker = getAllocationLocationTracker(); // First add primitive nodes. markCellWithNames(primitiveVisitor, cell); EdgeAddingAcceptor acceptor(*gc, snap); SlotVisitorWithNames visitor(acceptor); // Allow nodes to add extra nodes not in the JS heap. cell->getVT()->snapshotMetaData.addNodes(cell, gc, snap); snap.beginNode(); // Add all internal edges first. markCellWithNames(visitor, cell); // Allow nodes to add custom edges not represented by metadata. cell->getVT()->snapshotMetaData.addEdges(cell, gc, snap); auto stackTracesTreeNode = allocationLocationTracker.getStackTracesTreeNodeForAlloc( gc->getObjectID(cell)); snap.endNode( cell->getVT()->snapshotMetaData.nodeType(), cell->getVT()->snapshotMetaData.nameForNode(cell, gc), gc->getObjectID(cell), cell->getAllocatedSize(), stackTracesTreeNode ? stackTracesTreeNode->id : 0); }; gc->forAllObjs(snapshotForObject); // Write the singleton number nodes into the snapshot. primitiveAcceptor.writeAllNodes(); snap.endSection(HeapSnapshot::Section::Nodes); snap.beginSection(HeapSnapshot::Section::Edges); rootScan(); // No need to run the primitive scan again, as it only adds nodes, not edges. // Add edges between objects in the heap. forAllObjs(snapshotForObject); snap.endSection(HeapSnapshot::Section::Edges); snap.emitAllocationTraceInfo(); snap.beginSection(HeapSnapshot::Section::Samples); getAllocationLocationTracker().addSamplesToSnapshot(snap); snap.endSection(HeapSnapshot::Section::Samples); snap.beginSection(HeapSnapshot::Section::Locations); forAllObjs([&snap, gc](GCCell *cell) { cell->getVT()->snapshotMetaData.addLocations(cell, gc, snap); }); snap.endSection(HeapSnapshot::Section::Locations); } void GCBase::snapshotAddGCNativeNodes(HeapSnapshot &snap) { snap.beginNode(); snap.endNode( HeapSnapshot::NodeType::Native, ""std::deque"", IDTracker::reserved(IDTracker::ReservedObjectID::WeakRefSlotStorage), weakSlots_.size() * sizeof(decltype(weakSlots_)::value_type), 0); } void GCBase::snapshotAddGCNativeEdges(HeapSnapshot &snap) { snap.addNamedEdge( HeapSnapshot::EdgeType::Internal, ""weakRefSlots"", IDTracker::reserved(IDTracker::ReservedObjectID::WeakRefSlotStorage)); } void GCBase::enableHeapProfiler( std::function)> fragmentCallback) { getAllocationLocationTracker().enable(std::move(fragmentCallback)); } void GCBase::disableHeapProfiler() { getAllocationLocationTracker().disable(); } void GCBase::enableSamplingHeapProfiler(size_t samplingInterval, int64_t seed) { getSamplingAllocationTracker().enable(samplingInterval, seed); } void GCBase::disableSamplingHeapProfiler(llvh::raw_ostream &os) { getSamplingAllocationTracker().disable(os); } void GCBase::checkTripwire(size_t dataSize) { if (LLVM_LIKELY(!tripwireCallback_) || LLVM_LIKELY(dataSize < tripwireLimit_) || tripwireCalled_) { return; } class Ctx : public GCTripwireContext { public: Ctx(GCBase *gc) : gc_(gc) {} std::error_code createSnapshotToFile(const std::string &path) override { return gc_->createSnapshotToFile(path); } std::error_code createSnapshot(std::ostream &os) override { llvh::raw_os_ostream ros(os); gc_->createSnapshot(ros); return std::error_code{}; } private: GCBase *gc_; } ctx(this); tripwireCalled_ = true; tripwireCallback_(ctx); } void GCBase::printAllCollectedStats(llvh::raw_ostream &os) { if (!recordGcStats_) return; dump(os); os << ""GC stats:\\n""; JSONEmitter json{os, /*pretty*/ true}; json.openDict(); printStats(json); json.closeDict(); os << ""\\n""; } void GCBase::getHeapInfo(HeapInfo &info) { info.numCollections = cumStats_.numCollections; } void GCBase::getHeapInfoWithMallocSize(HeapInfo &info) { // Assign to overwrite anything previously in the heap info. // A deque doesn't have a capacity, so the size is the lower bound. info.mallocSizeEstimate = weakSlots_.size() * sizeof(decltype(weakSlots_)::value_type); } #ifndef NDEBUG void GCBase::getDebugHeapInfo(DebugHeapInfo &info) { recordNumAllocatedObjects(); info.numAllocatedObjects = numAllocatedObjects_; info.numReachableObjects = numReachableObjects_; info.numCollectedObjects = numCollectedObjects_; info.numFinalizedObjects = numFinalizedObjects_; info.numMarkedSymbols = numMarkedSymbols_; info.numHiddenClasses = numHiddenClasses_; info.numLeafHiddenClasses = numLeafHiddenClasses_; } size_t GCBase::countUsedWeakRefs() const { size_t count = 0; for (auto &slot : weakSlots_) { if (slot.state() != WeakSlotState::Free) { ++count; } } return count; } #endif #ifndef NDEBUG void GCBase::DebugHeapInfo::assertInvariants() const { // The number of allocated objects at any time is at least the number // found reachable in the last collection. assert(numAllocatedObjects >= numReachableObjects); // The number of objects finalized in the last collection is at most the // number of objects collected. assert(numCollectedObjects >= numFinalizedObjects); } #endif void GCBase::dump(llvh::raw_ostream &, bool) { /* nop */ } void GCBase::printStats(JSONEmitter &json) { json.emitKeyValue(""type"", ""hermes""); json.emitKeyValue(""version"", 0); gcCallbacks_->printRuntimeGCStats(json); std::chrono::duration elapsedTime = std::chrono::steady_clock::now() - execStartTime_; auto elapsedCPUSeconds = std::chrono::duration_cast>( oscompat::thread_cpu_time()) .count() - std::chrono::duration_cast>( execStartCPUTime_) .count(); HeapInfo info; getHeapInfoWithMallocSize(info); getHeapInfo(info); #ifndef NDEBUG DebugHeapInfo debugInfo; getDebugHeapInfo(debugInfo); #endif json.emitKey(""heapInfo""); json.openDict(); #ifndef NDEBUG json.emitKeyValue(""Num allocated cells"", debugInfo.numAllocatedObjects); json.emitKeyValue(""Num reachable cells"", debugInfo.numReachableObjects); json.emitKeyValue(""Num collected cells"", debugInfo.numCollectedObjects); json.emitKeyValue(""Num finalized cells"", debugInfo.numFinalizedObjects); json.emitKeyValue(""Num marked symbols"", debugInfo.numMarkedSymbols); json.emitKeyValue(""Num hidden classes"", debugInfo.numHiddenClasses); json.emitKeyValue(""Num leaf classes"", debugInfo.numLeafHiddenClasses); json.emitKeyValue(""Num weak references"", ((GC *)this)->countUsedWeakRefs()); #endif json.emitKeyValue(""Peak RSS"", oscompat::peak_rss()); json.emitKeyValue(""Current RSS"", oscompat::current_rss()); json.emitKeyValue(""Current Dirty"", oscompat::current_private_dirty()); json.emitKeyValue(""Heap size"", info.heapSize); json.emitKeyValue(""Allocated bytes"", info.allocatedBytes); json.emitKeyValue(""Num collections"", info.numCollections); json.emitKeyValue(""Malloc size"", info.mallocSizeEstimate); json.closeDict(); long vol = -1; long invol = -1; if (oscompat::num_context_switches(vol, invol)) { vol -= startNumVoluntaryContextSwitches_; invol -= startNumInvoluntaryContextSwitches_; } json.emitKey(""general""); json.openDict(); json.emitKeyValue(""numCollections"", cumStats_.numCollections); json.emitKeyValue(""totalTime"", elapsedTime.count()); json.emitKeyValue(""totalCPUTime"", elapsedCPUSeconds); json.emitKeyValue(""totalGCTime"", formatSecs(cumStats_.gcWallTime.sum()).secs); json.emitKeyValue(""volCtxSwitch"", vol); json.emitKeyValue(""involCtxSwitch"", invol); json.emitKeyValue( ""avgGCPause"", formatSecs(cumStats_.gcWallTime.average()).secs); json.emitKeyValue(""maxGCPause"", formatSecs(cumStats_.gcWallTime.max()).secs); json.emitKeyValue( ""totalGCCPUTime"", formatSecs(cumStats_.gcCPUTime.sum()).secs); json.emitKeyValue( ""avgGCCPUPause"", formatSecs(cumStats_.gcCPUTime.average()).secs); json.emitKeyValue( ""maxGCCPUPause"", formatSecs(cumStats_.gcCPUTime.max()).secs); json.emitKeyValue(""finalHeapSize"", formatSize(cumStats_.finalHeapSize).bytes); json.emitKeyValue( ""peakAllocatedBytes"", formatSize(getPeakAllocatedBytes()).bytes); json.emitKeyValue(""peakLiveAfterGC"", formatSize(getPeakLiveAfterGC()).bytes); json.emitKeyValue( ""totalAllocatedBytes"", formatSize(info.totalAllocatedBytes).bytes); json.closeDict(); json.emitKey(""collections""); json.openArray(); for (const auto &event : analyticsEvents_) { json.openDict(); json.emitKeyValue(""runtimeDescription"", event.runtimeDescription); json.emitKeyValue(""gcKind"", event.gcKind); json.emitKeyValue(""collectionType"", event.collectionType); json.emitKeyValue(""cause"", event.cause); json.emitKeyValue(""duration"", event.duration.count()); json.emitKeyValue(""cpuDuration"", event.cpuDuration.count()); json.emitKeyValue(""preAllocated"", event.allocated.before); json.emitKeyValue(""postAllocated"", event.allocated.after); json.emitKeyValue(""preSize"", event.size.before); json.emitKeyValue(""postSize"", event.size.after); json.emitKeyValue(""preExternal"", event.external.before); json.emitKeyValue(""postExternal"", event.external.after); json.emitKeyValue(""survivalRatio"", event.survivalRatio); json.emitKey(""tags""); json.openArray(); for (const auto &tag : event.tags) { json.emitValue(tag); } json.closeArray(); json.closeDict(); } json.closeArray(); } void GCBase::recordGCStats( const GCAnalyticsEvent &event, CumulativeHeapStats *stats, bool onMutator) { // Hades OG collections do not block the mutator, and so do not contribute to // the max pause time or the total execution time. if (onMutator) stats->gcWallTime.record( std::chrono::duration(event.duration).count()); stats->gcCPUTime.record( std::chrono::duration(event.cpuDuration).count()); stats->finalHeapSize = event.size.after; stats->usedBefore.record(event.allocated.before); stats->usedAfter.record(event.allocated.after); stats->numCollections++; } void GCBase::recordGCStats(const GCAnalyticsEvent &event, bool onMutator) { if (analyticsCallback_) { analyticsCallback_(event); } if (recordGcStats_) { analyticsEvents_.push_back(event); } recordGCStats(event, &cumStats_, onMutator); } void GCBase::oom(std::error_code reason) { char detailBuffer[400]; oomDetail(detailBuffer, reason); #ifdef HERMESVM_EXCEPTION_ON_OOM // No need to run finalizeAll, the exception will propagate and eventually run // ~Runtime. throw JSOutOfMemoryError( std::string(detailBuffer) + ""\\ncall stack:\\n"" + gcCallbacks_->getCallStackNoAlloc()); #else hermesLog(""HermesGC"", ""OOM: %s."", detailBuffer); // Record the OOM custom data with the crash manager. crashMgr_->setCustomData(""HermesGCOOMDetailBasic"", detailBuffer); hermes_fatal(""OOM"", reason); #endif } void GCBase::oomDetail( llvh::MutableArrayRef detailBuffer, std::error_code reason) { HeapInfo heapInfo; getHeapInfo(heapInfo); snprintf( detailBuffer.data(), detailBuffer.size(), ""[%.20s] reason = %.150s (%d from category: %.50s), numCollections = %u, heapSize = %"" PRIu64 "", allocated = %"" PRIu64 "", va = %"" PRIu64 "", external = %"" PRIu64, name_.c_str(), reason.message().c_str(), reason.value(), reason.category().name(), heapInfo.numCollections, heapInfo.heapSize, heapInfo.allocatedBytes, heapInfo.va, heapInfo.externalBytes); } #ifndef NDEBUG /*static*/ bool GCBase::isMostRecentCellInFinalizerVector( const std::vector &finalizables, const GCCell *cell) { return !finalizables.empty() && finalizables.back() == cell; } #endif #ifdef HERMESVM_SANITIZE_HANDLES bool GCBase::shouldSanitizeHandles() { static std::uniform_real_distribution<> dist(0.0, 1.0); return dist(randomEngine_) < sanitizeRate_; } #endif #ifdef HERMESVM_GC_RUNTIME #define GCBASE_BARRIER_1(name, type1) \\ void GCBase::name(type1 arg1) { \\ runtimeGCDispatch([&](auto *gc) { gc->name(arg1); }); \\ } #define GCBASE_BARRIER_2(name, type1, type2) \\ void GCBase::name(type1 arg1, type2 arg2) { \\ runtimeGCDispatch([&](auto *gc) { gc->name(arg1, arg2); }); \\ } GCBASE_BARRIER_2(writeBarrier, const GCHermesValue *, HermesValue); GCBASE_BARRIER_2(writeBarrier, const GCSmallHermesValue *, SmallHermesValue); GCBASE_BARRIER_2(writeBarrier, const GCPointerBase *, const GCCell *); GCBASE_BARRIER_2(constructorWriteBarrier, const GCHermesValue *, HermesValue); GCBASE_BARRIER_2( constructorWriteBarrier, const GCSmallHermesValue *, SmallHermesValue); GCBASE_BARRIER_2( constructorWriteBarrier, const GCPointerBase *, const GCCell *); GCBASE_BARRIER_2(writeBarrierRange, const GCHermesValue *, uint32_t); GCBASE_BARRIER_2(writeBarrierRange, const GCSmallHermesValue *, uint32_t); GCBASE_BARRIER_2(constructorWriteBarrierRange, const GCHermesValue *, uint32_t); GCBASE_BARRIER_2( constructorWriteBarrierRange, const GCSmallHermesValue *, uint32_t); GCBASE_BARRIER_1(snapshotWriteBarrier, const GCHermesValue *); GCBASE_BARRIER_1(snapshotWriteBarrier, const GCSmallHermesValue *); GCBASE_BARRIER_1(snapshotWriteBarrier, const GCPointerBase *); GCBASE_BARRIER_1(snapshotWriteBarrier, const GCSymbolID *); GCBASE_BARRIER_2(snapshotWriteBarrierRange, const GCHermesValue *, uint32_t); GCBASE_BARRIER_2( snapshotWriteBarrierRange, const GCSmallHermesValue *, uint32_t); GCBASE_BARRIER_1(weakRefReadBarrier, GCCell *); GCBASE_BARRIER_1(weakRefReadBarrier, HermesValue); #undef GCBASE_BARRIER_1 #undef GCBASE_BARRIER_2 #endif /*static*/ std::vector GCBase::buildKeyList( GC *gc, JSWeakMap *weakMap) { std::vector res; for (auto iter = weakMap->keys_begin(), end = weakMap->keys_end(); iter != end; iter++) { if (iter->getObject(gc)) { res.push_back(&(*iter)); } } return res; } HeapSnapshot::NodeID GCBase::getObjectID(const GCCell *cell) { assert(cell && ""Called getObjectID on a null pointer""); return getObjectID(CompressedPointer::encodeNonNull( const_cast(cell), pointerBase_)); } HeapSnapshot::NodeID GCBase::getObjectIDMustExist(const GCCell *cell) { assert(cell && ""Called getObjectID on a null pointer""); return idTracker_.getObjectIDMustExist(CompressedPointer::encodeNonNull( const_cast(cell), pointerBase_)); } HeapSnapshot::NodeID GCBase::getObjectID(CompressedPointer cell) { assert(cell && ""Called getObjectID on a null pointer""); return idTracker_.getObjectID(cell); } HeapSnapshot::NodeID GCBase::getObjectID(SymbolID sym) { return idTracker_.getObjectID(sym); } HeapSnapshot::NodeID GCBase::getNativeID(const void *mem) { assert(mem && ""Called getNativeID on a null pointer""); return idTracker_.getNativeID(mem); } bool GCBase::hasObjectID(const GCCell *cell) { assert(cell && ""Called hasObjectID on a null pointer""); return idTracker_.hasObjectID(CompressedPointer::encodeNonNull( const_cast(cell), pointerBase_)); } void GCBase::newAlloc(const GCCell *ptr, uint32_t sz) { allocationLocationTracker_.newAlloc(ptr, sz); samplingAllocationTracker_.newAlloc(ptr, sz); } void GCBase::moveObject( const GCCell *oldPtr, uint32_t oldSize, const GCCell *newPtr, uint32_t newSize) { idTracker_.moveObject( CompressedPointer::encodeNonNull( const_cast(oldPtr), pointerBase_), CompressedPointer::encodeNonNull( const_cast(newPtr), pointerBase_)); // Use newPtr here because the idTracker_ just moved it. allocationLocationTracker_.updateSize(newPtr, oldSize, newSize); samplingAllocationTracker_.updateSize(newPtr, oldSize, newSize); } void GCBase::untrackObject(const GCCell *cell, uint32_t sz) { assert(cell && ""Called untrackObject on a null pointer""); // The allocation tracker needs to use the ID, so this needs to come // before untrackObject. getAllocationLocationTracker().freeAlloc(cell, sz); getSamplingAllocationTracker().freeAlloc(cell, sz); idTracker_.untrackObject(CompressedPointer::encodeNonNull( const_cast(cell), pointerBase_)); } #ifndef NDEBUG uint64_t GCBase::nextObjectID() { return debugAllocationCounter_++; } #endif const GCExecTrace &GCBase::getGCExecTrace() const { return execTrace_; } /*static*/ double GCBase::clockDiffSeconds(TimePoint start, TimePoint end) { std::chrono::duration elapsed = (end - start); return elapsed.count(); } /*static*/ double GCBase::clockDiffSeconds( std::chrono::microseconds start, std::chrono::microseconds end) { std::chrono::duration elapsed = (end - start); return elapsed.count(); } llvh::raw_ostream &operator<<( llvh::raw_ostream &os, const DurationFormatObj &dfo) { if (dfo.secs >= 1.0) { os << format(""%5.3f"", dfo.secs) << "" s""; } else if (dfo.secs >= 0.001) { os << format(""%5.3f"", dfo.secs * 1000.0) << "" ms""; } else { os << format(""%5.3f"", dfo.secs * 1000000.0) << "" us""; } return os; } llvh::raw_ostream &operator<<(llvh::raw_ostream &os, const SizeFormatObj &sfo) { double dblsize = static_cast(sfo.bytes); if (sfo.bytes >= (1024 * 1024 * 1024)) { double gbs = dblsize / (1024.0 * 1024.0 * 1024.0); os << format(""%0.3f GiB"", gbs); } else if (sfo.bytes >= (1024 * 1024)) { double mbs = dblsize / (1024.0 * 1024.0); os << format(""%0.3f MiB"", mbs); } else if (sfo.bytes >= 1024) { double kbs = dblsize / 1024.0; os << format(""%0.3f KiB"", kbs); } else { os << sfo.bytes << "" B""; } return os; } GCBase::GCCallbacks::~GCCallbacks() {} GCBase::IDTracker::IDTracker() { assert(lastID_ % 2 == 1 && ""First JS object ID isn't odd""); } void GCBase::IDTracker::moveObject( CompressedPointer oldLocation, CompressedPointer newLocation) { if (oldLocation == newLocation) { // Don't need to do anything if the object isn't moving anywhere. This can // happen in old generations where it is compacted to the same location. return; } std::lock_guard lk{mtx_}; auto old = objectIDMap_.find(oldLocation.getRaw()); if (old == objectIDMap_.end()) { // Avoid making new keys for objects that don't need to be tracked. return; } const auto oldID = old->second; assert( objectIDMap_.count(newLocation.getRaw()) == 0 && ""Moving to a location that is already tracked""); // Have to erase first, because any other access can invalidate the iterator. objectIDMap_.erase(old); objectIDMap_[newLocation.getRaw()] = oldID; // Update the reverse map entry if it exists. auto reverseMappingIt = idObjectMap_.find(oldID); if (reverseMappingIt != idObjectMap_.end()) { assert( reverseMappingIt->second == oldLocation.getRaw() && ""The reverse mapping should have the old address""); reverseMappingIt->second = newLocation.getRaw(); } } llvh::SmallVector &GCBase::IDTracker::getExtraNativeIDs(HeapSnapshot::NodeID node) { std::lock_guard lk{mtx_}; // The operator[] will default construct the vector to be empty if it doesn't // exist. return extraNativeIDs_[node]; } HeapSnapshot::NodeID GCBase::IDTracker::getNumberID(double num) { std::lock_guard lk{mtx_}; auto &numberRef = numberIDMap_[num]; // If the entry didn't exist, the value was initialized to 0. if (numberRef != 0) { return numberRef; } // Else, it is a number that hasn't been seen before. return numberRef = nextNumberID(); } llvh::Optional GCBase::IDTracker::getObjectForID( HeapSnapshot::NodeID id) { std::lock_guard lk{mtx_}; auto it = idObjectMap_.find(id); if (it != idObjectMap_.end()) { return CompressedPointer::fromRaw(it->second); } // Do an O(N) search through the map, then cache the result. // This trades time for memory, since this is a rare operation. for (const auto &p : objectIDMap_) { if (p.second == id) { // Cache the result so repeated lookups are fast. // This cache is unlikely to grow that large, unless someone hovers over // every single object in a snapshot in Chrome. auto itAndDidInsert = idObjectMap_.try_emplace(p.second, p.first); assert(itAndDidInsert.second); return CompressedPointer::fromRaw(itAndDidInsert.first->second); } } // ID not found in the map, wasn't an object to begin with. return llvh::None; } bool GCBase::IDTracker::hasNativeIDs() { std::lock_guard lk{mtx_}; return !nativeIDMap_.empty(); } bool GCBase::IDTracker::isTrackingIDs() { std::lock_guard lk{mtx_}; return !objectIDMap_.empty(); } HeapSnapshot::NodeID GCBase::IDTracker::getObjectID(CompressedPointer cell) { std::lock_guard lk{mtx_}; auto iter = objectIDMap_.find(cell.getRaw()); if (iter != objectIDMap_.end()) { return iter->second; } // Else, assume it is an object that needs to be tracked and give it a new ID. const auto objID = nextObjectID(); objectIDMap_[cell.getRaw()] = objID; return objID; } bool GCBase::IDTracker::hasObjectID(CompressedPointer cell) { std::lock_guard lk{mtx_}; return objectIDMap_.count(cell.getRaw()); } HeapSnapshot::NodeID GCBase::IDTracker::getObjectIDMustExist( CompressedPointer cell) { std::lock_guard lk{mtx_}; auto iter = objectIDMap_.find(cell.getRaw()); assert(iter != objectIDMap_.end() && ""cell must already have an ID""); return iter->second; } HeapSnapshot::NodeID GCBase::IDTracker::getObjectID(SymbolID sym) { std::lock_guard lk{mtx_}; auto iter = symbolIDMap_.find(sym.unsafeGetIndex()); if (iter != symbolIDMap_.end()) { return iter->second; } // Else, assume it is a symbol that needs to be tracked and give it a new ID. const auto symID = nextObjectID(); symbolIDMap_[sym.unsafeGetIndex()] = symID; return symID; } HeapSnapshot::NodeID GCBase::IDTracker::getNativeID(const void *mem) { std::lock_guard lk{mtx_}; auto iter = nativeIDMap_.find(mem); if (iter != nativeIDMap_.end()) { return iter->second; } // Else, assume it is a piece of native memory that needs to be tracked and // give it a new ID. const auto objID = nextNativeID(); nativeIDMap_[mem] = objID; return objID; } void GCBase::IDTracker::untrackObject(CompressedPointer cell) { std::lock_guard lk{mtx_}; // It's ok if this didn't exist before, since erase will remove it anyway, and // the default constructed zero ID won't be present in extraNativeIDs_. const auto id = objectIDMap_[cell.getRaw()]; objectIDMap_.erase(cell.getRaw()); extraNativeIDs_.erase(id); // Erase the reverse mapping entry if it exists. idObjectMap_.erase(id); } void GCBase::IDTracker::untrackNative(const void *mem) { std::lock_guard lk{mtx_}; nativeIDMap_.erase(mem); } void GCBase::IDTracker::untrackSymbol(uint32_t symIdx) { std::lock_guard lk{mtx_}; symbolIDMap_.erase(symIdx); } HeapSnapshot::NodeID GCBase::IDTracker::lastID() const { return lastID_; } HeapSnapshot::NodeID GCBase::IDTracker::nextObjectID() { // This must be unique for most features that rely on it, check for overflow. if (LLVM_UNLIKELY( lastID_ >= std::numeric_limits::max() - kIDStep)) { hermes_fatal(""Ran out of object IDs""); } return lastID_ += kIDStep; } HeapSnapshot::NodeID GCBase::IDTracker::nextNativeID() { // Calling nextObjectID effectively allocates two new IDs, one even // and one odd, returning the latter. For native objects, we want the former. HeapSnapshot::NodeID id = nextObjectID(); assert(id > 0 && ""nextObjectID should check for overflow""); return id - 1; } HeapSnapshot::NodeID GCBase::IDTracker::nextNumberID() { // Numbers will all be considered JS memory, not native memory. return nextObjectID(); } GCBase::AllocationLocationTracker::AllocationLocationTracker(GCBase *gc) : gc_(gc) {} bool GCBase::AllocationLocationTracker::isEnabled() const { return enabled_; } StackTracesTreeNode * GCBase::AllocationLocationTracker::getStackTracesTreeNodeForAlloc( HeapSnapshot::NodeID id) const { auto mapIt = stackMap_.find(id); return mapIt == stackMap_.end() ? nullptr : mapIt->second; } void GCBase::AllocationLocationTracker::enable( std::function< void(uint64_t, std::chrono::microseconds, std::vector)> callback) { assert(!enabled_ && ""Shouldn't enable twice""); enabled_ = true; std::lock_guard lk{mtx_}; // For correct visualization of the allocation timeline, it's necessary that // objects in the heap snapshot that existed before sampling was enabled have // numerically lower IDs than those allocated during sampling. We ensure this // by assigning IDs to everything here. uint64_t numObjects = 0; uint64_t numBytes = 0; gc_->forAllObjs([&numObjects, &numBytes, this](GCCell *cell) { numObjects++; numBytes += cell->getAllocatedSize(); gc_->getObjectID(cell); }); fragmentCallback_ = std::move(callback); startTime_ = std::chrono::steady_clock::now(); fragments_.clear(); // The first fragment has all objects that were live before the profiler was // enabled. // The ID and timestamp will be filled out via flushCallback. fragments_.emplace_back(Fragment{ IDTracker::kInvalidNode, std::chrono::microseconds(), numObjects, numBytes, // Say the fragment is touched here so it is written out // automatically by flushCallback. true}); // Immediately flush the first fragment. flushCallback(); } void GCBase::AllocationLocationTracker::disable() { std::lock_guard lk{mtx_}; flushCallback(); enabled_ = false; fragmentCallback_ = nullptr; } void GCBase::AllocationLocationTracker::newAlloc( const GCCell *ptr, uint32_t sz) { // Note we always get the current IP even if allocation tracking is not // enabled as it allows us to assert this feature works across many tests. // Note it's not very slow, it's slower than the non-virtual version // in Runtime though. const auto *ip = gc_->gcCallbacks_->getCurrentIPSlow(); if (!enabled_) { return; } std::lock_guard lk{mtx_}; // This is stateful and causes the object to have an ID assigned. const auto id = gc_->getObjectID(ptr); HERMES_SLOW_ASSERT( &findFragmentForID(id) == &fragments_.back() && ""Should only ever be allocating into the newest fragment""); Fragment &lastFrag = fragments_.back(); assert( lastFrag.lastSeenObjectID_ == IDTracker::kInvalidNode && ""Last fragment should not have an ID assigned yet""); lastFrag.numObjects_++; lastFrag.numBytes_ += sz; lastFrag.touchedSinceLastFlush_ = true; if (lastFrag.numBytes_ >= kFlushThreshold) { flushCallback(); } if (auto node = gc_->gcCallbacks_->getCurrentStackTracesTreeNode(ip)) { auto itAndDidInsert = stackMap_.try_emplace(id, node); assert(itAndDidInsert.second && ""Failed to create a new node""); (void)itAndDidInsert; } } void GCBase::AllocationLocationTracker::updateSize( const GCCell *ptr, uint32_t oldSize, uint32_t newSize) { int32_t delta = static_cast(newSize) - static_cast(oldSize); if (!delta || !enabled_) { // Nothing to update. return; } std::lock_guard lk{mtx_}; const auto id = gc_->getObjectIDMustExist(ptr); Fragment &frag = findFragmentForID(id); frag.numBytes_ += delta; frag.touchedSinceLastFlush_ = true; } void GCBase::AllocationLocationTracker::freeAlloc( const GCCell *ptr, uint32_t sz) { if (!enabled_) { // Fragments won't exist if the heap profiler isn't enabled. return; } // Hold a lock during freeAlloc because concurrent Hades might be creating an // alloc (newAlloc) at the same time. std::lock_guard lk{mtx_}; // The ID must exist here since the memory profiler guarantees everything has // an ID (it does a heap pass at the beginning to assign them all). const auto id = gc_->getObjectIDMustExist(ptr); stackMap_.erase(id); Fragment &frag = findFragmentForID(id); assert( frag.numObjects_ >= 1 && ""Num objects decremented too much for fragment""); frag.numObjects_--; assert(frag.numBytes_ >= sz && ""Num bytes decremented too much for fragment""); frag.numBytes_ -= sz; frag.touchedSinceLastFlush_ = true; } GCBase::AllocationLocationTracker::Fragment & GCBase::AllocationLocationTracker::findFragmentForID(HeapSnapshot::NodeID id) { assert(fragments_.size() >= 1 && ""Must have at least one fragment available""); for (auto it = fragments_.begin(); it != fragments_.end() - 1; ++it) { if (it->lastSeenObjectID_ >= id) { return *it; } } // Since no previous fragments matched, it must be the last fragment. return fragments_.back(); } void GCBase::AllocationLocationTracker::flushCallback() { Fragment &lastFrag = fragments_.back(); const auto lastID = gc_->getIDTracker().lastID(); const auto duration = std::chrono::duration_cast( std::chrono::steady_clock::now() - startTime_); assert( lastFrag.lastSeenObjectID_ == IDTracker::kInvalidNode && ""Last fragment should not have an ID assigned yet""); // In case a flush happens without any allocations occurring, don't add a new // fragment. if (lastFrag.touchedSinceLastFlush_) { lastFrag.lastSeenObjectID_ = lastID; lastFrag.timestamp_ = duration; // Place an empty fragment at the end, for any new allocs. fragments_.emplace_back(Fragment{ IDTracker::kInvalidNode, std::chrono::microseconds(), 0, 0, false}); } if (fragmentCallback_) { std::vector updatedFragments; // Don't include the last fragment, which is newly created (or has no // objects in it). for (size_t i = 0; i < fragments_.size() - 1; ++i) { auto &fragment = fragments_[i]; if (fragment.touchedSinceLastFlush_) { updatedFragments.emplace_back( i, fragment.numObjects_, fragment.numBytes_); fragment.touchedSinceLastFlush_ = false; } } fragmentCallback_(lastID, duration, std::move(updatedFragments)); } } void GCBase::AllocationLocationTracker::addSamplesToSnapshot( HeapSnapshot &snap) { std::lock_guard lk{mtx_}; if (enabled_) { flushCallback(); } // There might not be fragments if tracking has never been enabled. If there // are, the last one is always invalid. assert( (fragments_.empty() || fragments_.back().lastSeenObjectID_ == IDTracker::kInvalidNode) && ""Last fragment should not have an ID assigned yet""); // Loop over the fragments if we have any, and always skip the last one. for (size_t i = 0, e = fragments_.size(); i + 1 < e; ++i) { const auto &fragment = fragments_[i]; snap.addSample(fragment.timestamp_, fragment.lastSeenObjectID_); } } void GCBase::SamplingAllocationLocationTracker::enable( size_t samplingInterval, int64_t seed) { if (seed < 0) { seed = std::random_device()(); } randomEngine_.seed(seed); dist_ = llvh::make_unique>(samplingInterval); limit_ = nextSample(); } void GCBase::SamplingAllocationLocationTracker::disable(llvh::raw_ostream &os) { JSONEmitter json{os}; ChromeSamplingMemoryProfile profile{json}; std::lock_guard lk{mtx_}; // Track a map of size -> count for each stack tree node. llvh::DenseMap> sizesToCounts; // Do a pre-pass to compute sizesToCounts. for (const auto &s : samples_) { const Sample &sample = s.second; sizesToCounts[sample.node][sample.size]++; } // Have to emit the tree of stack frames before emitting samples, Chrome // requires the tree emitted first. profile.emitTree(gc_->gcCallbacks_->getStackTracesTree(), sizesToCounts); profile.beginSamples(); for (const auto &s : samples_) { const Sample &sample = s.second; profile.emitSample(sample.size, sample.node, sample.id); } profile.endSamples(); dist_.reset(); samples_.clear(); limit_ = 0; } void GCBase::SamplingAllocationLocationTracker::newAlloc( const GCCell *ptr, uint32_t sz) { // If the sampling profiler isn't enabled, don't check anything else. if (!isEnabled()) { return; } if (sz <= limit_) { // Exit if it's not time for a sample yet. limit_ -= sz; return; } const auto *ip = gc_->gcCallbacks_->getCurrentIPSlow(); // This is stateful and causes the object to have an ID assigned. const auto id = gc_->getObjectID(ptr); if (StackTracesTreeNode *node = gc_->gcCallbacks_->getCurrentStackTracesTreeNode(ip)) { // Hold a lock while modifying samples_. std::lock_guard lk{mtx_}; auto sampleItAndDidInsert = samples_.try_emplace(id, Sample{sz, node, nextSampleID_++}); assert(sampleItAndDidInsert.second && ""Failed to create a sample""); (void)sampleItAndDidInsert; } // Reset the limit. limit_ = nextSample(); } void GCBase::SamplingAllocationLocationTracker::freeAlloc( const GCCell *ptr, uint32_t sz) { // If the sampling profiler isn't enabled, don't check anything else. if (!isEnabled()) { return; } if (!gc_->hasObjectID(ptr)) { // This object's lifetime isn't being tracked. return; } const auto id = gc_->getObjectIDMustExist(ptr); // Hold a lock while modifying samples_. std::lock_guard lk{mtx_}; samples_.erase(id); } void GCBase::SamplingAllocationLocationTracker::updateSize( const GCCell *ptr, uint32_t oldSize, uint32_t newSize) { int32_t delta = static_cast(newSize) - static_cast(oldSize); if (!delta || !isEnabled() || !gc_->hasObjectID(ptr)) { // Nothing to update. return; } const auto id = gc_->getObjectIDMustExist(ptr); // Hold a lock while modifying samples_. std::lock_guard lk{mtx_}; const auto it = samples_.find(id); if (it == samples_.end()) { return; } Sample &sample = it->second; // Update the size stored in the sample. sample.size = newSize; } size_t GCBase::SamplingAllocationLocationTracker::nextSample() { return (*dist_)(randomEngine_); } llvh::Optional GCBase::getSnapshotID(HermesValue val) { if (val.isPointer() && val.getPointer()) { // Make nullptr HermesValue look like a JS null. // This should be rare, but is occasionally used by some parts of the VM. return val.getPointer() ? getObjectID(static_cast(val.getPointer())) : IDTracker::reserved(IDTracker::ReservedObjectID::Null); } else if (val.isNumber()) { return idTracker_.getNumberID(val.getNumber()); } else if (val.isSymbol() && val.getSymbol().isValid()) { return idTracker_.getObjectID(val.getSymbol()); } else if (val.isUndefined()) { return IDTracker::reserved(IDTracker::ReservedObjectID::Undefined); } else if (val.isNull()) { return static_cast( IDTracker::reserved(IDTracker::ReservedObjectID::Null)); } else if (val.isBool()) { return static_cast( val.getBool() ? IDTracker::reserved(IDTracker::ReservedObjectID::True) : IDTracker::reserved(IDTracker::ReservedObjectID::False)); } else { return llvh::None; } } void *GCBase::getObjectForID(HeapSnapshot::NodeID id) { if (llvh::Optional ptr = idTracker_.getObjectForID(id)) { return ptr->get(pointerBase_); } return nullptr; } void GCBase::sizeDiagnosticCensus(size_t allocatedBytes) { struct DiagnosticStat { uint64_t count{0}; uint64_t size{0}; std::map breakdown; static constexpr double getPercent(double numer, double denom) { return denom != 0 ? 100 * numer / denom : 0.0; } void printBreakdown(size_t depth) const { if (breakdown.empty()) return; static const char *fmtBase = ""%-25s : %'10"" PRIu64 "" [%'10"" PRIu64 "" B | %4.1f%%]""; const std::string fmtStr = std::string(depth, '\\t') + fmtBase; size_t totalSize = 0; size_t totalCount = 0; for (const auto &stat : breakdown) { hermesLog( ""HermesGC"", fmtStr.c_str(), stat.first.c_str(), stat.second.count, stat.second.size, getPercent(stat.second.size, size)); stat.second.printBreakdown(depth + 1); totalSize += stat.second.size; totalCount += stat.second.count; } if (size_t other = size - totalSize) hermesLog( ""HermesGC"", fmtStr.c_str(), ""Other"", count - totalCount, other, getPercent(other, size)); } }; struct HeapSizeDiagnostic { uint64_t numCell = 0; uint64_t numVariableSizedObject = 0; DiagnosticStat stats; void rootsDiagnosticFrame() const { // Use this to print commas on large numbers char *currentLocale = std::setlocale(LC_NUMERIC, nullptr); std::setlocale(LC_NUMERIC, """"); hermesLog(""HermesGC"", ""Root size: %'7"" PRIu64 "" B"", stats.size); stats.printBreakdown(1); std::setlocale(LC_NUMERIC, currentLocale); } void sizeDiagnosticFrame() const { // Use this to print commas on large numbers char *currentLocale = std::setlocale(LC_NUMERIC, nullptr); std::setlocale(LC_NUMERIC, """"); hermesLog(""HermesGC"", ""Heap size: %'7"" PRIu64 "" B"", stats.size); hermesLog(""HermesGC"", ""\\tTotal cells: %'7"" PRIu64, numCell); hermesLog( ""HermesGC"", ""\\tNum variable size cells: %'7"" PRIu64, numVariableSizedObject); stats.printBreakdown(1); std::setlocale(LC_NUMERIC, currentLocale); } }; struct HeapSizeDiagnosticAcceptor final : public RootAndSlotAcceptor { // Can't be static in a local class. const int64_t HINT8_MIN = -(1 << 7); const int64_t HINT8_MAX = (1 << 7) - 1; const int64_t HINT16_MIN = -(1 << 15); const int64_t HINT16_MAX = (1 << 15) - 1; const int64_t HINT24_MIN = -(1 << 23); const int64_t HINT24_MAX = (1 << 23) - 1; const int64_t HINT32_MIN = -(1LL << 31); const int64_t HINT32_MAX = (1LL << 31) - 1; HeapSizeDiagnostic diagnostic; PointerBase *pointerBase_; HeapSizeDiagnosticAcceptor(PointerBase *pb) : pointerBase_{pb} {} using SlotAcceptor::accept; void accept(GCCell *&ptr) override { diagnostic.stats.breakdown[""Pointer""].count++; diagnostic.stats.breakdown[""Pointer""].size += sizeof(GCCell *); } void accept(GCPointerBase &ptr) override { diagnostic.stats.breakdown[""GCPointer""].count++; diagnostic.stats.breakdown[""GCPointer""].size += sizeof(GCPointerBase); } void accept(PinnedHermesValue &hv) override { acceptNullable(hv); } void acceptNullable(PinnedHermesValue &hv) override { acceptHV( hv, diagnostic.stats.breakdown[""HermesValue""], sizeof(PinnedHermesValue)); } void accept(GCHermesValue &hv) override { acceptHV( hv, diagnostic.stats.breakdown[""HermesValue""], sizeof(GCHermesValue)); } void accept(GCSmallHermesValue &shv) override { acceptHV( shv.toHV(pointerBase_), diagnostic.stats.breakdown[""SmallHermesValue""], sizeof(GCSmallHermesValue)); } void acceptHV( const HermesValue &hv, DiagnosticStat &diag, const size_t hvBytes) { diag.count++; diag.size += hvBytes; llvh::StringRef hvType; if (hv.isBool()) { hvType = ""Bool""; } else if (hv.isNumber()) { hvType = ""Number""; double val = hv.getNumber(); double intpart; llvh::StringRef numType = ""Doubles""; if (std::modf(val, &intpart) == 0.0) { if (val >= static_cast(HINT8_MIN) && val <= static_cast(HINT8_MAX)) { numType = ""Int8""; } else if ( val >= static_cast(HINT16_MIN) && val <= static_cast(HINT16_MAX)) { numType = ""Int16""; } else if ( val >= static_cast(HINT24_MIN) && val <= static_cast(HINT24_MAX)) { numType = ""Int24""; } else if ( val >= static_cast(HINT32_MIN) && val <= static_cast(HINT32_MAX)) { numType = ""Int32""; } } diag.breakdown[""Number""].breakdown[numType].count++; diag.breakdown[""Number""].breakdown[numType].size += hvBytes; } else if (hv.isString()) { hvType = ""StringPointer""; } else if (hv.isSymbol()) { hvType = ""Symbol""; } else if (hv.isObject()) { hvType = ""ObjectPointer""; } else if (hv.isNull()) { hvType = ""Null""; } else if (hv.isUndefined()) { hvType = ""Undefined""; } else if (hv.isEmpty()) { hvType = ""Empty""; } else if (hv.isNativeValue()) { hvType = ""NativeValue""; } else { assert(false && ""Should be no other hermes values""); } diag.breakdown[hvType].count++; diag.breakdown[hvType].size += hvBytes; } void accept(const RootSymbolID &sym) override { acceptSym(sym); } void accept(const GCSymbolID &sym) override { acceptSym(sym); } void acceptSym(SymbolID sym) { diagnostic.stats.breakdown[""Symbol""].count++; diagnostic.stats.breakdown[""Symbol""].size += sizeof(SymbolID); } }; hermesLog(""HermesGC"", ""%s:"", ""Roots""); HeapSizeDiagnosticAcceptor rootAcceptor{getPointerBase()}; DroppingAcceptor namedRootAcceptor{rootAcceptor}; markRoots(namedRootAcceptor, /* markLongLived */ true); // For roots, compute the overall size and counts from the breakdown. for (const auto &substat : rootAcceptor.diagnostic.stats.breakdown) { rootAcceptor.diagnostic.stats.count += substat.second.count; rootAcceptor.diagnostic.stats.size += substat.second.size; } rootAcceptor.diagnostic.rootsDiagnosticFrame(); hermesLog(""HermesGC"", ""%s:"", ""Heap contents""); HeapSizeDiagnosticAcceptor acceptor{getPointerBase()}; forAllObjs([&acceptor, this](GCCell *cell) { markCell(cell, acceptor); acceptor.diagnostic.numCell++; if (cell->isVariableSize()) { acceptor.diagnostic.numVariableSizedObject++; // In theory should use sizeof(VariableSizeRuntimeCell), but that includes // padding sometimes. To be conservative, use the field it contains // directly instead. acceptor.diagnostic.stats.breakdown[""Cell headers""].size += (sizeof(GCCell) + sizeof(uint32_t)); } else { acceptor.diagnostic.stats.breakdown[""Cell headers""].size += sizeof(GCCell); } // We include ExternalStringPrimitives because we're including external // memory in the overall heap size. We do not include // BufferedStringPrimitives because they just store a pointer to an // ExternalStringPrimitive (which is already tracked). auto *strprim = dyn_vmcast(cell); if (strprim && !isBufferedStringPrimitive(cell)) { auto &stat = strprim->isASCII() ? acceptor.diagnostic.stats.breakdown[""StringPrimitive (ASCII)""] : acceptor.diagnostic.stats.breakdown[""StringPrimitive (UTF-16)""]; stat.count++; const size_t len = strprim->getStringLength(); // If the string is UTF-16 then the length is in terms of 16 bit // characters. const size_t sz = strprim->isASCII() ? len : len * 2; stat.size += sz; if (len < 8) { auto &subStat = stat.breakdown [""StringPrimitive (size "" + std::to_string(len) + "")""]; subStat.count++; subStat.size += sz; } } }); assert( acceptor.diagnostic.stats.size == 0 && acceptor.diagnostic.stats.count == 0 && ""Should not be setting overall stats during heap scan.""); for (const auto &substat : acceptor.diagnostic.stats.breakdown) acceptor.diagnostic.stats.count += substat.second.count; acceptor.diagnostic.stats.size = allocatedBytes; acceptor.diagnostic.sizeDiagnosticFrame(); } } // namespace vm } // namespace hermes #undef DEBUG_TYPE ",16301,True,2758.1857503432166,median "// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include ""src/lib/fidl_codec/wire_parser.h"" #include #include #include #include #include #include #include #include ""gmock/gmock.h"" #include ""gtest/gtest.h"" #include ""lib/fidl/cpp/test/frobinator_impl.h"" #include ""rapidjson/stringbuffer.h"" #include ""rapidjson/writer.h"" #include ""src/lib/fidl_codec/encoder.h"" #include ""src/lib/fidl_codec/fidl_codec_test.h"" #include ""src/lib/fidl_codec/library_loader.h"" #include ""src/lib/fidl_codec/library_loader_test_data.h"" #include ""src/lib/fidl_codec/message_decoder.h"" #include ""src/lib/fidl_codec/wire_object.h"" #include ""test/fidlcodec/examples/cpp/fidl.h"" namespace fidl_codec { constexpr uint32_t kUninitialized = 0xdeadbeef; constexpr float kFloatValue = 0.25; constexpr double kDoubleValue = 9007199254740992.0; constexpr int kUint32Precision = 8; const Colors FakeColors(/*new_reset=*/""#rst#"", /*new_red=*/""#red#"", /*new_green=*/""#gre#"", /*new_blue=*/""#blu#"", /*new_white_on_magenta=*/""#wom#"", /*new_yellow_background=*/""#yeb#""); AsyncLoopForTest::AsyncLoopForTest() : impl_(std::make_unique()) {} AsyncLoopForTest::~AsyncLoopForTest() = default; zx_status_t AsyncLoopForTest::RunUntilIdle() { return impl_->loop()->RunUntilIdle(); } zx_status_t AsyncLoopForTest::Run() { return impl_->loop()->Run(); } async_dispatcher_t* AsyncLoopForTest::dispatcher() { return impl_->loop()->dispatcher(); } LibraryLoader* InitLoader() { std::vector> library_files; fidl_codec_test::FidlcodecExamples examples; for (const auto& element : examples.map()) { std::unique_ptr file = std::make_unique(std::istringstream(element.second)); library_files.push_back(std::move(file)); } LibraryReadError err; return new LibraryLoader(&library_files, &err); } LibraryLoader* GetLoader() { static LibraryLoader* loader = InitLoader(); return loader; } class WireParserTest : public ::testing::Test { protected: void SetUp() override { loader_ = GetLoader(); ASSERT_NE(loader_, nullptr); } LibraryLoader* loader() const { return loader_; } private: LibraryLoader* loader_; }; TEST_F(WireParserTest, ParseSingleString) { fidl::MessageBuffer buffer; fidl::Message message = buffer.CreateEmptyMessage(); InterceptRequest( message, [](fidl::InterfacePtr& ptr) { ptr->Grob(""one"", [](const fidl::StringPtr& /*value*/) { FAIL(); }); }); fidl_message_header_t header = message.header(); const std::vector* methods = loader()->GetByOrdinal(header.ordinal); ASSERT_NE(methods, nullptr); ASSERT_TRUE(!methods->empty()); const InterfaceMethod* method = (*methods)[0]; ASSERT_NE(method, nullptr); ASSERT_EQ(""Grob"", method->name()); zx_handle_info_t* handle_infos = nullptr; if (message.handles().size() > 0) { handle_infos = new zx_handle_info_t[message.handles().size()]; for (uint32_t i = 0; i < message.handles().size(); ++i) { handle_infos[i].handle = message.handles().data()[i]; handle_infos[i].type = ZX_OBJ_TYPE_NONE; handle_infos[i].rights = 0; } } std::unique_ptr decoded_request; fidl_codec::DecodeRequest(method, message.bytes().data(), message.bytes().size(), handle_infos, message.handles().size(), &decoded_request); rapidjson::Document actual; if (decoded_request != nullptr) { decoded_request->ExtractJson(actual.GetAllocator(), actual); } rapidjson::Document expected; expected.Parse(R""JSON({""value"":""one""})JSON""); ASSERT_EQ(expected, actual); delete[] handle_infos; } // This is a general-purpose macro for calling InterceptRequest and checking its // results. It can be generalized to a wide variety of types (and is, below). // It checks for successful parsing, as well as failure when parsing truncated // values. // |_iface| is the interface method name on examples::FidlCodecTestInterface // (TODO: generalize which interface to use) // |_json_value| is the expected JSON representation of the message. // |_pretty_print| is the expected pretty print of the message. // The remaining parameters are the parameters to |_iface| to generate the // message. #define TEST_DECODE_WIRE_BODY(_iface, _json_value, _pretty_print, ...) \\ do { \\ fidl::MessageBuffer buffer; \\ fidl::Message message = buffer.CreateEmptyMessage(); \\ using test::fidlcodec::examples::FidlCodecTestInterface; \\ InterceptRequest( \\ message, \\ [&](fidl::InterfacePtr& ptr) { ptr->_iface(__VA_ARGS__); }); \\ \\ fidl_message_header_t header = message.header(); \\ \\ const std::vector* methods = loader()->GetByOrdinal(header.ordinal); \\ ASSERT_NE(methods, nullptr); \\ ASSERT_TRUE(!methods->empty()); \\ const InterfaceMethod* method = (*methods)[0]; \\ ASSERT_NE(method, nullptr); \\ ASSERT_EQ(#_iface, method->name()); \\ \\ zx_handle_info_t* handle_infos = nullptr; \\ if (message.handles().size() > 0) { \\ handle_infos = new zx_handle_info_t[message.handles().size()]; \\ for (uint32_t i = 0; i < message.handles().size(); ++i) { \\ handle_infos[i].handle = message.handles().data()[i]; \\ handle_infos[i].type = ZX_OBJ_TYPE_CHANNEL; \\ handle_infos[i].rights = ZX_RIGHT_TRANSFER | ZX_RIGHT_READ | ZX_RIGHT_WRITE | \\ ZX_RIGHT_SIGNAL | ZX_RIGHT_SIGNAL_PEER | ZX_RIGHT_WAIT | \\ ZX_RIGHT_INSPECT; \\ } \\ } \\ \\ MessageDecoder decoder(message.bytes().data(), message.bytes().size(), handle_infos, \\ message.handles().size(), /*output_errors=*/true); \\ std::unique_ptr object = decoder.DecodeMessage(*method->request()); \\ ASSERT_FALSE(decoder.HasError()) << ""Could not decode message""; \\ rapidjson::Document actual; \\ if (object != nullptr) { \\ object->ExtractJson(actual.GetAllocator(), actual); \\ } \\ rapidjson::StringBuffer actual_string; \\ rapidjson::Writer actual_w(actual_string); \\ actual.Accept(actual_w); \\ \\ rapidjson::Document expected; \\ std::string expected_source = _json_value; \\ expected.Parse(expected_source.c_str()); \\ rapidjson::StringBuffer expected_string; \\ rapidjson::Writer expected_w(expected_string); \\ expected.Accept(expected_w); \\ \\ ASSERT_EQ(expected, actual) << ""expected = "" << expected_string.GetString() << "" ("" \\ << expected_source << "")"" \\ << "" and actual = "" << actual_string.GetString(); \\ \\ std::stringstream result; \\ if (object != nullptr) { \\ object->PrettyPrint(result, FakeColors, """", 0, 80, 80); \\ } \\ ASSERT_EQ(result.str(), _pretty_print) \\ << ""expected = "" << _pretty_print << "" actual = "" << result.str(); \\ \\ for (uint32_t actual = 0; actual < message.bytes().actual(); ++actual) { \\ MessageDecoder decoder(message.bytes().data(), actual, handle_infos, \\ message.handles().size(), /*output_errors=*/false); \\ std::unique_ptr object = decoder.DecodeMessage(*method->request()); \\ ASSERT_TRUE(decoder.HasError()) << ""expect decoder error for buffer size "" << actual \\ << "" instead of "" << message.bytes().actual(); \\ } \\ \\ for (uint32_t actual = 0; message.handles().actual() > actual; actual++) { \\ MessageDecoder decoder(message.bytes().data(), message.bytes().size(), handle_infos, actual, \\ /*output_errors=*/false); \\ std::unique_ptr object = decoder.DecodeMessage(*method->request()); \\ ASSERT_TRUE(decoder.HasError()) << ""expect decoder error for handle size "" << actual \\ << "" instead of "" << message.handles().actual(); \\ } \\ \\ auto encode_result = Encoder::EncodeMessage(header.txid, header.ordinal, header.flags, \\ header.magic_number, *object.get()); \\ ASSERT_THAT(encode_result.bytes, ::testing::ElementsAreArray(message.bytes())); \\ ASSERT_EQ(message.handles().size(), encode_result.handles.size()); \\ \\ for (uint32_t i = 0; i < message.handles().size(); ++i) { \\ EXPECT_EQ(message.handles().data()[i], encode_result.handles[i].handle); \\ } \\ delete[] handle_infos; \\ } while (0) // This is a convenience wrapper for calling TEST_DECODE_WIRE_BODY that simply // executes the code in a test. // |_testname| is the name of the test (prepended by Parse in the output) // |_iface| is the interface method name on examples::FidlCodecTestInterface // (TODO: generalize which interface to use) // |_json_value| is the expected JSON representation of the message. // |_pretty_print| is the expected pretty print of the message. // The remaining parameters are the parameters to |_iface| to generate the // message. #define TEST_DECODE_WIRE(_testname, _iface, _json_value, _pretty_print, ...) \\ TEST_F(WireParserTest, Parse##_testname) { \\ TEST_DECODE_WIRE_BODY(_iface, _json_value, _pretty_print, __VA_ARGS__); \\ } // Scalar Tests namespace { template std::string ValueToJson(const std::string& key, T value) { return ""\\"""" + key + ""\\"":\\"""" + std::to_string(value) + ""\\""""; } template <> std::string ValueToJson(const std::string& key, bool value) { return ""\\"""" + key + ""\\"":\\"""" + (value ? ""true"" : ""false"") + ""\\""""; } template <> std::string ValueToJson(const std::string& key, const char* value) { return ""\\"""" + key + ""\\"":\\"""" + value + ""\\""""; } template <> std::string ValueToJson(const std::string& key, std::string value) { return ""\\"""" + key + ""\\"":\\"""" + value + ""\\""""; } template std::string SingleToJson(const std::string& key, T value) { return ""{ "" + ValueToJson(key, value) + "" }""; } template std::string ValueToPretty(const std::string& key, const std::string& type, T value) { return key + "": #gre#"" + type + ""#rst# = #blu#"" + std::to_string(value) + ""#rst#""; } template <> std::string ValueToPretty(const std::string& key, const std::string& type, bool value) { return key + "": #gre#"" + type + ""#rst# = #blu#"" + (value ? ""true"" : ""false"") + ""#rst#""; } template <> std::string ValueToPretty(const std::string& key, const std::string& type, const char* value) { return key + "": #gre#"" + type + ""#rst# = #red#\\"""" + value + ""\\""#rst#""; } template <> std::string ValueToPretty(const std::string& key, const std::string& type, std::string value) { return key + "": #gre#"" + type + ""#rst# = #red#\\"""" + value + ""\\""#rst#""; } std::string HandleToJson(const std::string& key, zx_handle_t value) { std::stringstream ss; ss << std::hex << std::setfill('0') << std::setw(kUint32Precision) << value << std::dec << std::setw(0); return ""\\"""" + key + ""\\"":\\""ZX_OBJ_TYPE_CHANNEL:"" + ss.str() + ""(ZX_RIGHT_TRANSFER | ZX_RIGHT_READ | ZX_RIGHT_WRITE | ZX_RIGHT_SIGNAL | "" + ""ZX_RIGHT_SIGNAL_PEER | ZX_RIGHT_WAIT | ZX_RIGHT_INSPECT)\\""""; } std::string HandleToPretty(const std::string& key, zx_handle_t value) { std::stringstream ss; ss << std::hex << std::setfill('0') << std::setw(kUint32Precision) << value << std::dec << std::setw(0); return key + "": #gre#handle#rst# = #red#ZX_OBJ_TYPE_CHANNEL:"" + ss.str() + ""#blu#"" + ""(ZX_RIGHT_TRANSFER | ZX_RIGHT_READ | ZX_RIGHT_WRITE | ZX_RIGHT_SIGNAL | "" + ""ZX_RIGHT_SIGNAL_PEER | ZX_RIGHT_WAIT | ZX_RIGHT_INSPECT)"" + ""#rst#""; } template std::string SingleToPretty(const std::string& key, const std::string& type, T value) { return ""{ "" + ValueToPretty(key, type, value) + "" }""; } } // namespace #define TEST_SINGLE(_testname, _iface, _key, _type, _value) \\ TEST_DECODE_WIRE(_testname, _iface, SingleToJson(#_key, _value), \\ SingleToPretty(#_key, #_type, _value), _value) TEST_DECODE_WIRE(Empty, Empty, ""{}"", ""{}"") TEST_SINGLE(String, String, s, string, ""Hello World!"") TEST_SINGLE(BoolTrue, Bool, b, bool, true) TEST_SINGLE(BoolFalse, Bool, b, bool, false) TEST_SINGLE(Int8Min, Int8, i8, int8, std::numeric_limits::min()) TEST_SINGLE(Int16Min, Int16, i16, int16, std::numeric_limits::min()) TEST_SINGLE(Int32Min, Int32, i32, int32, std::numeric_limits::min()) TEST_SINGLE(Int64Min, Int64, i64, int64, std::numeric_limits::min()) TEST_SINGLE(Int8Max, Int8, i8, int8, std::numeric_limits::max()) TEST_SINGLE(Int16Max, Int16, i16, int16, std::numeric_limits::max()) TEST_SINGLE(Int32Max, Int32, i32, int32, std::numeric_limits::max()) TEST_SINGLE(Int64Max, Int64, i64, int64, std::numeric_limits::max()) TEST_SINGLE(Uint8Min, Uint8, ui8, uint8, std::numeric_limits::min()) TEST_SINGLE(Uint16Min, Uint16, ui16, uint16, std::numeric_limits::min()) TEST_SINGLE(Uint32Min, Uint32, ui32, uint32, std::numeric_limits::min()) TEST_SINGLE(Uint64Min, Uint64, ui64, uint64, std::numeric_limits::min()) TEST_SINGLE(Uint8Max, Uint8, ui8, uint8, std::numeric_limits::max()) TEST_SINGLE(Uint16Max, Uint16, ui16, uint16, std::numeric_limits::max()) TEST_SINGLE(Uint32Max, Uint32, ui32, uint32, std::numeric_limits::max()) TEST_SINGLE(Uint64Max, Uint64, ui64, uint64, std::numeric_limits::max()) TEST_SINGLE(Float32, Float32, f32, float32, kFloatValue) TEST_SINGLE(Float64, Float64, f64, float64, kDoubleValue) TEST_DECODE_WIRE(TwoTuple, Complex, R""({""real"":""1"", ""imaginary"":""2""})"", ""{ "" + ValueToPretty(""real"", ""int32"", 1) + "", "" + ValueToPretty(""imaginary"", ""int32"", 2) + "" }"", 1, 2); TEST_DECODE_WIRE(StringInt, StringInt, R""({""s"":""groucho"", ""i32"":""4""})"", ""{ "" + ValueToPretty(""s"", ""string"", ""groucho"") + "", "" + ValueToPretty(""i32"", ""int32"", 4) + "" }"", ""groucho"", 4) // Vector / Array Tests namespace { std::array one_param_array = {1}; std::array two_param_array = {1, 2}; std::vector one_param_vector = {1}; std::vector two_param_vector = {1, 2}; } // namespace TEST_DECODE_WIRE(Array1, Array1, R""({""b_1"":[""1""]})"", ""{ b_1: #gre#array#rst# = [ #blu#1#rst# ] }"", one_param_array); TEST_DECODE_WIRE(Array2, Array2, R""({""b_2"":[""1"", ""2""]})"", ""{ b_2: #gre#array#rst# = [ #blu#1#rst#, #blu#2#rst# ] }"", two_param_array); TEST_DECODE_WIRE(NullVector, Vector, R""({""v_1"": null})"", ""{ v_1: #gre#vector#rst# = #blu#null#rst# }"", nullptr) TEST_DECODE_WIRE(VectorOneElt, Vector, R""({""v_1"":[""1""]})"", ""{ v_1: #gre#vector#rst# = [ #blu#1#rst# ] }"", one_param_vector); TEST_DECODE_WIRE(VectorTwoElt, Vector, R""({""v_1"":[""1"", ""2""]})"", ""{ v_1: #gre#vector#rst# = [ #blu#1#rst#, #blu#2#rst# ] }"", two_param_vector); namespace { std::array TwoStringArrayFromVals(const std::string& v1, const std::string& v2) { std::array brother_array; brother_array[0] = v1; brother_array[1] = v2; return brother_array; } } // namespace TEST_DECODE_WIRE(TwoStringArrayInt, TwoStringArrayInt, R""({""arr"":[""harpo"",""chico""], ""i32"":""1""})"", R""({ arr: #gre#array#rst# = [ #red#""harpo""#rst#, #red#""chico""#rst# ], )"" + ValueToPretty(""i32"", ""int32"", 1) + "" }"", TwoStringArrayFromVals(""harpo"", ""chico""), 1) namespace { std::vector TwoStringVectorFromVals(const std::string& v1, const std::string& v2) { return std::vector({v1, v2}); } std::vector VectorUint8() { const int kItemCount = 40; std::vector result; for (int i = 0; i <= kItemCount; ++i) { result.push_back(i); } return result; } std::vector VectorUint8(const char* text) { std::vector result; while (*text != 0) { result.push_back(*text++); } return result; } std::vector VectorUint32() { const int kItemCount = 25; std::vector result; for (int i = 0; i <= kItemCount; ++i) { const int kShift = 16; result.push_back(i + ((i & 1) << kShift)); } return result; } } // namespace TEST_DECODE_WIRE(TwoStringVectorInt, TwoStringVectorInt, R""({""vec"":[""harpo"", ""chico""], ""i32"":""1""})"", R""({ vec: #gre#vector#rst# = [ #red#""harpo""#rst#, #red#""chico""#rst# ], )"" + ValueToPretty(""i32"", ""int32"", 1) + "" }"", TwoStringVectorFromVals(""harpo"", ""chico""), 1) TEST_DECODE_WIRE(TwoStringVectors, TwoStringVectors, R""({""v_1"":[""harpo"",""chico""],""v_2"":[""groucho"",""zeppo""]})"", ""{\\n v_1: #gre#vector#rst# = "" R""([ #red#""harpo""#rst#, #red#""chico""#rst# ])"" ""\\n v_2: #gre#vector#rst# = "" R""([ #red#""groucho""#rst#, #red#""zeppo""#rst# ])"" ""\\n}"", TwoStringVectorFromVals(""harpo"", ""chico""), TwoStringVectorFromVals(""groucho"", ""zeppo"")) TEST_DECODE_WIRE( VectorUint8, VectorUint8, R""({""v"":[""0"",""1"",""2"",""3"",""4"",""5"",""6"",""7"",""8"",""9"",""10"",""11"",""12"",""13"",""14"",""15"",""16"",""17"",""18"",""19"",""20"",""21"",""22"",""23"",""24"",""25"",""26"",""27"",""28"",""29"",""30"",""31"",""32"",""33"",""34"",""35"",""36"",""37"",""38"",""39"",""40""]})"", ""{\\n"" "" v: #gre#vector#rst# = [\\n"" "" #blu#0#rst#, #blu#1#rst#, #blu#2#rst#, #blu#3#rst#, #blu#4#rst#, #blu#5#rst#, "" ""#blu#6#rst#, #blu#7#rst#, #blu#8#rst#, #blu#9#rst#, #blu#10#rst#, #blu#11#rst#, #blu#12#rst#, "" ""#blu#13#rst#, #blu#14#rst#, #blu#15#rst#, #blu#16#rst#, #blu#17#rst#, #blu#18#rst#, "" ""#blu#19#rst#, #blu#20#rst#,\\n"" "" #blu#21#rst#, #blu#22#rst#, #blu#23#rst#, #blu#24#rst#, #blu#25#rst#, #blu#26#rst#, "" ""#blu#27#rst#, #blu#28#rst#, #blu#29#rst#, #blu#30#rst#, #blu#31#rst#, #blu#32#rst#, "" ""#blu#33#rst#, #blu#34#rst#, #blu#35#rst#, #blu#36#rst#, #blu#37#rst#, #blu#38#rst#, "" ""#blu#39#rst#,\\n"" "" #blu#40#rst#\\n"" "" ]\\n"" ""}"", VectorUint8()) TEST_DECODE_WIRE( VectorUint8String, VectorUint8, R""({""v"":[""72"",""101"",""108"",""108"",""111"",""32"",""116"",""101"",""115"",""116"",""105"",""110"",""103"",""32"",""119"",""111"",""114"",""108"",""100"",""33""]})"", ""{ v: #gre#vector#rst# = \\""Hello testing world!\\"" }"", VectorUint8(""Hello testing world!"")) TEST_DECODE_WIRE( VectorUint8MultilineString, VectorUint8, R""({""v"":[""72"",""101"",""108"",""108"",""111"",""32"",""116"",""101"",""115"",""116"",""105"",""110"",""103"",""32"",""119"",""111"",""114"",""108"",""100"",""33"",""10"",""72"",""111"",""119"",""32"",""97"",""114"",""101"",""32"",""121"",""111"",""117"",""32"",""116"",""111"",""100"",""97"",""121"", ""63"",""10"",""73"",""39"",""109"",""32"",""116"",""101"",""115"",""116"",""105"",""110"",""103"",""32"",""102"",""105"",""100"",""108"",""95"",""99"",""111"",""100"",""101"",""99"",""46""]})"", ""{\\n"" "" v: #gre#vector#rst# = [\\n"" "" Hello testing world!\\n"" "" How are you today?\\n"" "" I'm testing fidl_codec.\\n"" "" ]\\n"" ""}"", VectorUint8(""Hello testing world!\\nHow are you today?\\nI'm testing fidl_codec."")) TEST_DECODE_WIRE( VectorUint32, VectorUint32, R""({""v"":[""0"",""65537"",""2"",""65539"",""4"",""65541"",""6"",""65543"",""8"",""65545"",""10"",""65547"",""12"",""65549"",""14"",""65551"",""16"",""65553"",""18"",""65555"",""20"",""65557"",""22"",""65559"",""24"",""65561""]})"", ""{\\n"" "" v: #gre#vector#rst# = [\\n"" "" #blu#0#rst#, #blu#65537#rst#, #blu#2#rst#, #blu#65539#rst#, #blu#4#rst#, #blu#65541#rst#, "" ""#blu#6#rst#, #blu#65543#rst#, #blu#8#rst#, #blu#65545#rst#, #blu#10#rst#, #blu#65547#rst#, "" ""#blu#12#rst#, #blu#65549#rst#, #blu#14#rst#,\\n"" "" #blu#65551#rst#, #blu#16#rst#, #blu#65553#rst#, #blu#18#rst#, #blu#65555#rst#, "" ""#blu#20#rst#, #blu#65557#rst#, #blu#22#rst#, #blu#65559#rst#, #blu#24#rst#, #blu#65561#rst#\\n"" "" ]\\n"" ""}"", VectorUint32()) // Struct Tests namespace { class StructSupport { public: StructSupport() { pt.s = ""Hello""; pt.b = true; pt.i8 = std::numeric_limits::min(); pt.i16 = std::numeric_limits::min(); pt.i32 = std::numeric_limits::min(); pt.i64 = std::numeric_limits::min(); pt.u8 = std::numeric_limits::max(); pt.u16 = std::numeric_limits::max(); pt.u32 = std::numeric_limits::max(); pt.u64 = std::numeric_limits::max(); pt.f32 = kFloatValue; pt.f64 = kDoubleValue; } std::string GetJson() { std::ostringstream es; es << R""({""p"":{)"" << ValueToJson(""s"", pt.s) << "","" << ValueToJson(""b"", pt.b) << "","" << ValueToJson(""i8"", pt.i8) << "","" << ValueToJson(""i16"", pt.i16) << "","" << ValueToJson(""i32"", pt.i32) << "","" << ValueToJson(""i64"", pt.i64) << "","" << ValueToJson(""u8"", pt.u8) << "","" << ValueToJson(""u16"", pt.u16) << "","" << ValueToJson(""u32"", pt.u32) << "","" << ValueToJson(""u64"", pt.u64) << "","" << ValueToJson(""f32"", pt.f32) << "","" << ValueToJson(""f64"", pt.f64) << ""}}""; return es.str(); } std::string GetPretty() { std::ostringstream es; es << ""{\\n"" << "" p: #gre#test.fidlcodec.examples/PrimitiveTypes#rst# = {\\n"" << "" "" << ValueToPretty(""s"", ""string"", pt.s) << ""\\n"" << "" "" << ValueToPretty(""b"", ""bool"", pt.b) << ""\\n"" << "" "" << ValueToPretty(""i8"", ""int8"", pt.i8) << ""\\n"" << "" "" << ValueToPretty(""i16"", ""int16"", pt.i16) << ""\\n"" << "" "" << ValueToPretty(""i32"", ""int32"", pt.i32) << ""\\n"" << "" "" << ValueToPretty(""i64"", ""int64"", pt.i64) << ""\\n"" << "" "" << ValueToPretty(""u8"", ""uint8"", pt.u8) << ""\\n"" << "" "" << ValueToPretty(""u16"", ""uint16"", pt.u16) << ""\\n"" << "" "" << ValueToPretty(""u32"", ""uint32"", pt.u32) << ""\\n"" << "" "" << ValueToPretty(""u64"", ""uint64"", pt.u64) << ""\\n"" << "" "" << ValueToPretty(""f32"", ""float32"", pt.f32) << ""\\n"" << "" "" << ValueToPretty(""f64"", ""float64"", pt.f64) << ""\\n"" << "" }\\n"" << ""}""; return es.str(); } test::fidlcodec::examples::PrimitiveTypes pt; }; } // namespace TEST_F(WireParserTest, ParseStruct) { StructSupport sd; TEST_DECODE_WIRE_BODY(Struct, sd.GetJson(), sd.GetPretty(), sd.pt); } TEST_DECODE_WIRE(NullableStruct, NullableStruct, R""({""p"":null})"", ""{ p: #gre#test.fidlcodec.examples/PrimitiveTypes#rst# = #blu#null#rst# }"", nullptr); TEST_DECODE_WIRE(NullableStructAndInt, NullableStructAndInt, R""({""p"":null, ""i"":""1""})"", ""{ p: #gre#test.fidlcodec.examples/PrimitiveTypes#rst# = "" ""#blu#null#rst#, i: #gre#int32#rst# = #blu#1#rst# }"", nullptr, 1); namespace { test::fidlcodec::examples::SmallStruct SmallStructFromVals(uint8_t a, uint8_t b, uint8_t c) { test::fidlcodec::examples::SmallStruct ss; ss.a = a; ss.b = b; ss.c = c; return ss; } } // namespace TEST_DECODE_WIRE(SmallStruct, SmallStructAfterByte, R""({""u"":""1"",""s1"":{""a"":""2"",""b"":""3"",""c"":""4""},""s2"":{""a"":""5"",""b"":""6"",""c"":""7""}})"", ""{\\n"" "" u: #gre#uint8#rst# = #blu#1#rst#\\n"" "" s1: #gre#test.fidlcodec.examples/SmallStruct#rst# = {\\n"" "" a: #gre#uint8#rst# = #blu#2#rst#\\n"" "" b: #gre#uint8#rst# = #blu#3#rst#\\n"" "" c: #gre#uint8#rst# = #blu#4#rst#\\n"" "" }\\n"" "" s2: #gre#test.fidlcodec.examples/SmallStruct#rst# = {\\n"" "" a: #gre#uint8#rst# = #blu#5#rst#\\n"" "" b: #gre#uint8#rst# = #blu#6#rst#\\n"" "" c: #gre#uint8#rst# = #blu#7#rst#\\n"" "" }\\n"" ""}"", 1, SmallStructFromVals(2, 3, 4), SmallStructFromVals(5, 6, 7)); namespace { test::fidlcodec::examples::TwoStringStruct TwoStringStructFromVals(const std::string& v1, const std::string& v2) { test::fidlcodec::examples::TwoStringStruct tss; tss.value1 = v1; tss.value2 = v2; return tss; } std::unique_ptr TwoStringStructFromValsPtr( const std::string& v1, const std::string& v2) { std::unique_ptr ptr( new test::fidlcodec::examples::TwoStringStruct()); ptr->value1 = v1; ptr->value2 = v2; return ptr; } std::string TwoStringStructIntPretty(const char* s1, const char* s2, int v) { std::string result = ""{\\n s: #gre#test.fidlcodec.examples/TwoStringStruct#rst# = {\\n""; result += "" "" + ValueToPretty(""value1"", ""string"", s1) + ""\\n""; result += "" "" + ValueToPretty(""value2"", ""string"", s2) + ""\\n""; result += "" }\\n""; result += "" "" + ValueToPretty(""i32"", ""int32"", v) + ""\\n""; result += ""}""; return result; } } // namespace TEST_DECODE_WIRE(TwoStringStructInt, TwoStringStructInt, R""({""s"":{""value1"":""harpo"", ""value2"":""chico""}, ""i32"":""1""})"", TwoStringStructIntPretty(""harpo"", ""chico"", 1), TwoStringStructFromVals(""harpo"", ""chico""), 1) TEST_DECODE_WIRE(TwoStringNullableStructInt, TwoStringNullableStructInt, R""({""s"":{""value1"":""harpo"", ""value2"":""chico""}, ""i32"":""1""})"", TwoStringStructIntPretty(""harpo"", ""chico"", 1), TwoStringStructFromValsPtr(""harpo"", ""chico""), 1) // Union and XUnion tests namespace { using isu = test::fidlcodec::examples::IntStructUnion; using xisu = test::fidlcodec::examples::IntStructXunion; template T GetIntUnion(int32_t i) { T u; u.set_variant_i(i); return u; } template T GetStructUnion(const std::string& v1, const std::string& v2) { T u; test::fidlcodec::examples::TwoStringStruct tss = TwoStringStructFromVals(v1, v2); u.set_variant_tss(tss); return u; } template std::unique_ptr GetIntUnionPtr(int32_t i) { std::unique_ptr ptr(new T()); ptr->set_variant_i(i); return ptr; } template std::unique_ptr GetStructUnionPtr(const std::string& v1, const std::string& v2) { std::unique_ptr ptr(new T()); test::fidlcodec::examples::TwoStringStruct tss = TwoStringStructFromVals(v1, v2); ptr->set_variant_tss(tss); return ptr; } std::string IntUnionIntPretty(const std::string& name, int u, int v) { std::string result = ""{\\n""; result += "" isu: #gre#test.fidlcodec.examples/"" + name + ""#rst# = { "" + ValueToPretty(""variant_i"", ""int32"", u) + "" }\\n""; result += "" "" + ValueToPretty(""i"", ""int32"", v) + ""\\n""; result += ""}""; return result; } std::string StructUnionIntPretty(const std::string& name, const char* u1, const char* u2, int v) { std::string result = ""{\\n""; result += "" isu: #gre#test.fidlcodec.examples/"" + name + ""#rst# = {\\n""; result += "" variant_tss: #gre#test.fidlcodec.examples/TwoStringStruct#rst# = "" ""{\\n""; result += "" "" + ValueToPretty(""value1"", ""string"", u1) + ""\\n""; result += "" "" + ValueToPretty(""value2"", ""string"", u2) + ""\\n""; result += "" }\\n""; result += "" }\\n""; result += "" "" + ValueToPretty(""i"", ""int32"", v) + ""\\n""; result += ""}""; return result; } std::string IntIntUnionPretty(const std::string& name, int v, int u) { std::string result = ""{\\n""; result += "" "" + ValueToPretty(""i"", ""int32"", v) + ""\\n""; result += "" isu: #gre#test.fidlcodec.examples/"" + name + ""#rst# = { "" + ValueToPretty(""variant_i"", ""int32"", u) + "" }\\n""; result += ""}""; return result; } std::string IntStructUnionPretty(const std::string& name, int v, const char* u1, const char* u2) { std::string result = ""{\\n""; result += "" "" + ValueToPretty(""i"", ""int32"", v) + ""\\n""; result += "" isu: #gre#test.fidlcodec.examples/"" + name + ""#rst# = {\\n""; result += "" variant_tss: #gre#test.fidlcodec.examples/TwoStringStruct#rst# = "" ""{\\n""; result += "" "" + ValueToPretty(""value1"", ""string"", u1) + ""\\n""; result += "" "" + ValueToPretty(""value2"", ""string"", u2) + ""\\n""; result += "" }\\n""; result += "" }\\n""; result += ""}""; return result; } } // namespace TEST_DECODE_WIRE(UnionInt, Union, R""({""isu"":{""variant_i"":""42""}, ""i"" : ""1""})"", IntUnionIntPretty(""IntStructUnion"", 42, 1), GetIntUnion(42), 1); TEST_DECODE_WIRE(UnionStruct, Union, R""({""isu"":{""variant_tss"":{""value1"":""harpo"",""value2"":""chico""}}, ""i"":""1""})"", StructUnionIntPretty(""IntStructUnion"", ""harpo"", ""chico"", 1), GetStructUnion(""harpo"", ""chico""), 1); TEST_DECODE_WIRE(NullableUnionInt, NullableUnion, R""({""isu"":{""variant_i"":""42""}, ""i"" : ""1""})"", IntUnionIntPretty(""IntStructUnion"", 42, 1), GetIntUnionPtr(42), 1); TEST_DECODE_WIRE(NullableUnionStruct, NullableUnion, R""({""isu"":{""variant_tss"":{""value1"":""harpo"",""value2"":""chico""}}, ""i"":""1""})"", StructUnionIntPretty(""IntStructUnion"", ""harpo"", ""chico"", 1), GetStructUnionPtr(""harpo"", ""chico""), 1); TEST_DECODE_WIRE(NullableUnionIntFirstInt, NullableUnionIntFirst, R""({""i"" : ""1"", ""isu"":{""variant_i"":""42""}})"", IntIntUnionPretty(""IntStructUnion"", 1, 42), 1, GetIntUnionPtr(42)); TEST_DECODE_WIRE(NullableUnionIntFirstStruct, NullableUnionIntFirst, R""({""i"": ""1"", ""isu"":{""variant_tss"":{""value1"":""harpo"",""value2"":""chico""}}})"", IntStructUnionPretty(""IntStructUnion"", 1, ""harpo"", ""chico""), 1, GetStructUnionPtr(""harpo"", ""chico"")); TEST_DECODE_WIRE(XUnionInt, XUnion, R""({""isu"":{""variant_i"":""42""}, ""i"" : ""1""})"", IntUnionIntPretty(""IntStructXunion"", 42, 1), GetIntUnion(42), 1); TEST_DECODE_WIRE(XUnionStruct, XUnion, R""({""isu"":{""variant_tss"":{""value1"":""harpo"",""value2"":""chico""}}, ""i"":""1""})"", StructUnionIntPretty(""IntStructXunion"", ""harpo"", ""chico"", 1), GetStructUnion(""harpo"", ""chico""), 1); TEST_DECODE_WIRE(NullableXUnionInt, NullableXUnion, R""({""isu"":{""variant_i"":""42""}, ""i"" : ""1""})"", IntUnionIntPretty(""IntStructXunion"", 42, 1), GetIntUnionPtr(42), 1); TEST_DECODE_WIRE(NullableXUnionStruct, NullableXUnion, R""({""isu"":{""variant_tss"":{""value1"":""harpo"",""value2"":""chico""}}, ""i"":""1""})"", StructUnionIntPretty(""IntStructXunion"", ""harpo"", ""chico"", 1), GetStructUnionPtr(""harpo"", ""chico""), 1); TEST_DECODE_WIRE(NullableXUnionIntFirstInt, NullableXUnionIntFirst, R""({""i"" : ""1"", ""isu"":{""variant_i"":""42""}})"", IntIntUnionPretty(""IntStructXunion"", 1, 42), 1, GetIntUnionPtr(42)); TEST_DECODE_WIRE(NullableXUnionIntFirstStruct, NullableXUnionIntFirst, R""({""i"": ""1"", ""isu"":{""variant_tss"":{""value1"":""harpo"",""value2"":""chico""}}})"", IntStructUnionPretty(""IntStructXunion"", 1, ""harpo"", ""chico""), 1, GetStructUnionPtr(""harpo"", ""chico"")); namespace { using uuu = test::fidlcodec::examples::U8U16Union; using uux = test::fidlcodec::examples::U8U16Xunion; template T GetUInt8Union(uint8_t i) { T u; u.set_variant_u8(i); return u; } template T GetUInt16Union(uint16_t i) { T u; u.set_variant_u16(i); return u; } std::string ShortUnionPretty(const std::string& name, const char* field, const char* type, int u, int v) { std::string result = ""{\\n""; result += "" u: #gre#test.fidlcodec.examples/"" + name + ""#rst# = { "" + ValueToPretty(field, type, u) + "" }\\n""; result += "" "" + ValueToPretty(""i"", ""int32"", v) + ""\\n""; result += ""}""; return result; } } // namespace TEST_DECODE_WIRE(ShortUnion8, ShortUnion, R""({""u"":{""variant_u8"":""16""}, ""i"":""1""})"", ShortUnionPretty(""U8U16Union"", ""variant_u8"", ""uint8"", 16, 1), GetUInt8Union(16), 1); TEST_DECODE_WIRE(ShortUnion16, ShortUnion, R""({""u"":{""variant_u16"":""1024""}, ""i"":""1""})"", ShortUnionPretty(""U8U16Union"", ""variant_u16"", ""uint16"", 1024, 1), GetUInt16Union(1024), 1); TEST_DECODE_WIRE(ShortXUnion8, ShortXUnion, R""({""u"":{""variant_u8"":""16""}, ""i"":""1""})"", ShortUnionPretty(""U8U16Xunion"", ""variant_u8"", ""uint8"", 16, 1), GetUInt8Union(16), 1); TEST_DECODE_WIRE(ShortXUnion16, ShortXUnion, R""({""u"":{""variant_u16"":""1024""}, ""i"":""1""})"", ShortUnionPretty(""U8U16Xunion"", ""variant_u16"", ""uint16"", 1024, 1), GetUInt16Union(1024), 1); // Enum Tests TEST_DECODE_WIRE(DefaultEnum, DefaultEnumMessage, R""({""ev"":""X""})"", ""{ ev: #gre#test.fidlcodec.examples/DefaultEnum#rst# = #blu#X#rst# }"", test::fidlcodec::examples::DefaultEnum::X); TEST_DECODE_WIRE(I8Enum, I8EnumMessage, R""({""ev"":""X""})"", ""{ ev: #gre#test.fidlcodec.examples/I8Enum#rst# = #blu#X#rst# }"", test::fidlcodec::examples::I8Enum::X); TEST_DECODE_WIRE(I16Enum, I16EnumMessage, R""({""ev"":""X""})"", ""{ ev: #gre#test.fidlcodec.examples/I16Enum#rst# = #blu#X#rst# }"", test::fidlcodec::examples::I16Enum::X); // Table Tests test::fidlcodec::examples::ValueTable GetTable(std::optional first_int16, std::optional value1, std::optional value2, std::optional third_union_val) { test::fidlcodec::examples::ValueTable table; if (first_int16.has_value()) { table.set_first_int16(*first_int16); } if (value1.has_value()) { table.set_second_struct(TwoStringStructFromVals(*value1, *value2)); } if (third_union_val.has_value()) { test::fidlcodec::examples::IntStructUnion u; u.set_variant_i(*third_union_val); table.set_third_union(std::move(u)); } return table; } std::string TablePretty(std::optional first_int16, std::optional value1, std::optional value2, std::optional third_union_val, int i) { if (!first_int16.has_value() && !value1.has_value() && !third_union_val.has_value()) { std::string result = ""{ table: #gre#test.fidlcodec.examples/ValueTable#rst# = {}, ""; result += ValueToPretty(""i"", ""int32"", i); result += "" }""; return result; } std::string result = ""{\\n""; if (!value1.has_value() && !third_union_val.has_value()) { result += "" table: #gre#test.fidlcodec.examples/ValueTable#rst# = { ""; result += ValueToPretty(""first_int16"", ""int16"", *first_int16) + "" }\\n""; } else { result += "" table: #gre#test.fidlcodec.examples/ValueTable#rst# = {\\n""; if (first_int16.has_value()) { result += "" "" + ValueToPretty(""first_int16"", ""int16"", *first_int16) + ""\\n""; } if (value1.has_value()) { result += "" second_struct: "" ""#gre#test.fidlcodec.examples/TwoStringStruct#rst# = {\\n""; result += "" "" + ValueToPretty(""value1"", ""string"", *value1) + ""\\n""; result += "" "" + ValueToPretty(""value2"", ""string"", *value2) + ""\\n""; result += "" }\\n""; } if (third_union_val.has_value()) { result += "" third_union: #gre#test.fidlcodec.examples/IntStructUnion#rst# = {\\n""; result += "" "" + ValueToPretty(""variant_i"", ""int32"", *third_union_val) + ""\\n""; result += "" }\\n""; } result += "" }\\n""; } result += "" "" + ValueToPretty(""i"", ""int32"", i) + ""\\n""; result += ""}""; return result; } TEST_DECODE_WIRE(Table0, Table, R""({""table"":{}, ""i"":""2""})"", TablePretty({}, {}, {}, {}, 2), GetTable({}, {}, {}, {}), 2) TEST_DECODE_WIRE(Table1, Table, R""({""table"":{ ""third_union"":{""variant_i"":""42""} }, ""i"":""2""})"", TablePretty({}, {}, {}, 42, 2), GetTable({}, {}, {}, 42), 2) TEST_DECODE_WIRE(Table2, Table, R""({""table"":{ ""second_struct"":{""value1"":""harpo"", ""value2"":""groucho""} }, ""i"":""2""})"", TablePretty({}, ""harpo"", ""groucho"", {}, 2), GetTable({}, ""harpo"", ""groucho"", {}), 2) TEST_DECODE_WIRE(Table3, Table, R""({""table"":{ ""second_struct"":{ ""value1"":""harpo"", ""value2"":""groucho""}, ""third_union"":{""variant_i"":""42""}}, ""i"":""2""})"", TablePretty({}, ""harpo"", ""groucho"", 42, 2), GetTable({}, ""harpo"", ""groucho"", 42), 2) TEST_DECODE_WIRE(Table4, Table, R""({""table"":{ ""first_int16"":""1"" }, ""i"":""2""})"", TablePretty(1, {}, {}, {}, 2), GetTable(1, {}, {}, {}), 2) TEST_DECODE_WIRE(Table5, Table, R""({""table"":{ ""first_int16"":""1"", ""third_union"":{""variant_i"":""42""} }, ""i"":""2""})"", TablePretty(1, {}, {}, 42, 2), GetTable(1, {}, {}, 42), 2) TEST_DECODE_WIRE(Table6, Table, R""({""table"":{ ""first_int16"":""1"", ""second_struct"":{ ""value1"":""harpo"", ""value2"":""groucho""} }, ""i"":""2""})"", TablePretty(1, ""harpo"", ""groucho"", {}, 2), GetTable(1, ""harpo"", ""groucho"", {}), 2) TEST_DECODE_WIRE(Table7, Table, R""({""table"":{ ""first_int16"":""1"", ""second_struct"":{ ""value1"":""harpo"", ""value2"":""groucho""}, ""third_union"":{""variant_i"":""42""} }, ""i"":""2""})"", TablePretty(1, ""harpo"", ""groucho"", 42, 2), GetTable(1, ""harpo"", ""groucho"", 42), 2) // TODO(DX-1476): Add a test that exercises what happens when we encounter an // unknown type in a table. // Handle Tests namespace { class HandleSupport { public: HandleSupport() { zx::channel::create(0, &out1_, &out2_); json_ = ""{"" + HandleToJson(""ch"", out2_.get()) + ""}""; pretty_ = ""{ "" + HandleToPretty(""ch"", out2_.get()) + "" }""; } zx::channel handle() { return std::move(out2_); } template fidl::InterfaceHandle interface() { return fidl::InterfaceHandle(std::move(out2_)); } std::string GetJSON() { return json_; } std::string GetPretty() { return pretty_; } private: zx::channel out1_; zx::channel out2_; std::string json_; std::string pretty_; }; } // namespace TEST_F(WireParserTest, ParseHandle) { HandleSupport support; TEST_DECODE_WIRE_BODY(Handle, support.GetJSON(), support.GetPretty(), support.handle()); } TEST_F(WireParserTest, ParseNullableHandle) { HandleSupport support; TEST_DECODE_WIRE_BODY(NullableHandle, support.GetJSON(), support.GetPretty(), support.handle()); } TEST_F(WireParserTest, ParseProtocol) { HandleSupport support; TEST_DECODE_WIRE_BODY(Protocol, support.GetJSON(), support.GetPretty(), support.interface()); } namespace { class HandleStructSupport { public: HandleStructSupport() { zx::channel::create(0, &out1_, &out2_); zx::channel::create(0, &out3_, &out4_); json_ = ""{\\""hs\\"":{"" + HandleToJson(""h1"", out1_.get()) + "","" + HandleToJson(""h2"", out2_.get()) + "","" + HandleToJson(""h3"", out3_.get()) + ""}}""; pretty_ = ""{\\n hs: #gre#test.fidlcodec.examples/HandleStruct#rst# = {\\n "" + HandleToPretty(""h1"", out1_.get()) + ""\\n "" + HandleToPretty(""h2"", out2_.get()) + ""\\n "" + HandleToPretty(""h3"", out3_.get()) + ""\\n }\\n}""; } test::fidlcodec::examples::HandleStruct handle_struct() { test::fidlcodec::examples::HandleStruct hs; hs.h1 = std::move(out1_); hs.h2 = std::move(out2_); hs.h3 = std::move(out3_); return hs; } std::string GetJSON() { return json_; } std::string GetPretty() { return pretty_; } private: zx::channel out1_; zx::channel out2_; zx::channel out3_; zx::channel out4_; std::string json_; std::string pretty_; }; } // namespace TEST_F(WireParserTest, ParseHandleStruct) { HandleStructSupport support; TEST_DECODE_WIRE_BODY(HandleStructMessage, support.GetJSON(), support.GetPretty(), support.handle_struct()); } namespace { class TraversalOrderSupport { public: TraversalOrderSupport() { zx::channel::create(0, &sh1_, &sh2_); zx::channel::create(0, &h1_, &h2_); json_ = ""{\\""t\\"":{\\""s\\"":{"" + HandleToJson(""sh1"", sh1_.get()) + "","" + HandleToJson(""sh2"", sh2_.get()) + ""},"" + HandleToJson(""h1"", h1_.get()) + "","" + HandleToJson(""h2"", h2_.get()) + ""}}""; pretty_ = ""{\\n t: #gre#test.fidlcodec.examples/TraversalOrder#rst# = {\\n "" ""s: #gre#test.fidlcodec.examples/OptHandleStruct#rst# = {\\n "" + HandleToPretty(""sh1"", sh1_.get()) + ""\\n "" + HandleToPretty(""sh2"", sh2_.get()) + ""\\n }\\n "" + HandleToPretty(""h1"", h1_.get()) + ""\\n "" + HandleToPretty(""h2"", h2_.get()) + ""\\n }\\n}""; } test::fidlcodec::examples::TraversalOrder TraversalOrder() { test::fidlcodec::examples::TraversalOrder t; auto s = std::make_unique(); s->sh1 = std::move(sh1_); s->sh2 = std::move(sh2_); t.s = std::move(s); t.h1 = std::move(h1_); t.h2 = std::move(h2_); return t; } std::string GetJSON() { return json_; } std::string GetPretty() { return pretty_; } private: zx::channel sh1_; zx::channel sh2_; zx::channel h1_; zx::channel h2_; std::string json_; std::string pretty_; }; } // namespace TEST_F(WireParserTest, ParseTraversalOrder) { TraversalOrderSupport support; TEST_DECODE_WIRE_BODY(TraversalOrderMessage, support.GetJSON(), support.GetPretty(), support.TraversalOrder()); } // Corrupt data tests TEST_F(WireParserTest, BadSchemaPrintHex) { std::vector> library_files; // i32 in the schema is missing ""subtype"": ""int32"" std::string bad_schema = R""FIDL({ ""version"": ""0.0.1"", ""name"": ""fidl.examples.types"", ""library_dependencies"": [], ""bits_declarations"": [], ""const_declarations"": [], ""enum_declarations"": [], ""interface_declarations"": [ { ""name"": ""test.fidlcodec.examples/FidlCodecTestInterface"", ""location"": { ""filename"": ""../../src/lib/fidl_codec/testdata/types.test.fidl"", ""line"": 11, ""column"": 10 }, ""methods"": [ { ""ordinal"": 913676553315942400, ""generated_ordinal"": 913676553315942400, ""name"": ""Int32"", ""location"": { ""filename"": ""../../src/lib/fidl_codec/testdata/types.test.fidl"", ""line"": 16, ""column"": 5 }, ""has_request"": true, ""maybe_request"": [ { ""type"": { ""kind"": ""primitive"" }, ""name"": ""i32"", ""location"": { ""filename"": ""../../src/lib/fidl_codec/testdata/types.test.fidl"", ""line"": 16, ""column"": 17 }, ""size"": 4, ""max_out_of_line"": 0, ""alignment"": 4, ""offset"": 16, ""max_handles"": 0 } ], ""maybe_request_size"": 24, ""maybe_request_alignment"": 8, ""has_response"": false, ""is_composed"": false } ] } ], ""struct_declarations"": [], ""table_declarations"": [], ""union_declarations"": [], ""xunion_declarations"": [] })FIDL""; std::unique_ptr file = std::make_unique(std::istringstream(bad_schema)); library_files.push_back(std::move(file)); LibraryReadError err; LibraryLoader loader(&library_files, &err); ASSERT_TRUE(err.value == LibraryReadError::ErrorValue::kOk); fidl::MessageBuffer buffer; fidl::Message message = buffer.CreateEmptyMessage(); InterceptRequest( message, [](fidl::InterfacePtr& ptr) { ptr->Int32(kUninitialized); }); fidl_message_header_t header = message.header(); zx_handle_info_t* handle_infos = nullptr; if (message.handles().size() > 0) { handle_infos = new zx_handle_info_t[message.handles().size()]; for (uint32_t i = 0; i < message.handles().size(); ++i) { handle_infos[i].handle = message.handles().data()[i]; handle_infos[i].type = ZX_OBJ_TYPE_NONE; handle_infos[i].rights = 0; } } const std::vector* methods = loader.GetByOrdinal(header.ordinal); ASSERT_NE(methods, nullptr); ASSERT_TRUE(!methods->empty()); const InterfaceMethod* method = (*methods)[0]; // If this is null, you probably have to update the schema above. ASSERT_NE(method, nullptr); std::unique_ptr decoded_request; fidl_codec::DecodeRequest(method, message.bytes().data(), message.bytes().size(), handle_infos, message.handles().size(), &decoded_request); rapidjson::Document actual; if (decoded_request != nullptr) { decoded_request->ExtractJson(actual.GetAllocator(), actual); } ASSERT_STREQ(actual[""i32""].GetString(), ""ef be ad de""); delete[] handle_infos; } // TODO(fidlcat): Remove this test and its dependencies when the union migration will be finished. // Test that we will be able to decode unions as xunion. TEST_F(WireParserTest, UnionsAreXUnions) { std::vector> library_files; // This is a copy of the json for xunionmigration.fidl. However, SendAfterMigration now // refers to OriginalUnion and the xunion_ordinal fields of OriginalUnion have been copied // from the ordinal fields of NowAsXUnion. std::string future_schema = R""FIDL({ ""version"": ""0.0.1"", ""name"": ""test.fidlcodec.examples"", ""library_dependencies"": [], ""bits_declarations"": [], ""const_declarations"": [], ""enum_declarations"": [], ""interface_declarations"": [ { ""name"": ""test.fidlcodec.examples/FidlCodecXUnion"", ""location"": { ""filename"": ""../../src/lib/fidl_codec/testdata/xunionmigration.fidl"", ""line"": 7, ""column"": 10 }, ""methods"": [ { ""ordinal"": 7678173679997419520, ""generated_ordinal"": 5589963516716936935, ""name"": ""SendAfterMigration"", ""location"": { ""filename"": ""../../src/lib/fidl_codec/testdata/xunionmigration.fidl"", ""line"": 8, ""column"": 5 }, ""has_request"": true, ""maybe_request"": [ { ""type"": { ""kind"": ""identifier"", ""identifier"": ""test.fidlcodec.examples/OriginalUnion"", ""nullable"": false }, ""name"": ""u"", ""location"": { ""filename"": ""../../src/lib/fidl_codec/testdata/xunionmigration.fidl"", ""line"": 8, ""column"": 36 }, ""size"": 24, ""max_out_of_line"": 8, ""alignment"": 8, ""offset"": 16, ""max_handles"": 0 }, { ""type"": { ""kind"": ""primitive"", ""subtype"": ""int32"" }, ""name"": ""i"", ""location"": { ""filename"": ""../../src/lib/fidl_codec/testdata/xunionmigration.fidl"", ""line"": 8, ""column"": 45 }, ""size"": 4, ""max_out_of_line"": 0, ""alignment"": 4, ""offset"": 40, ""max_handles"": 0 } ], ""maybe_request_size"": 48, ""maybe_request_alignment"": 8, ""maybe_request_has_padding"": true, ""experimental_maybe_request_has_flexible_envelope"": true, ""has_response"": false, ""is_composed"": false } ] } ], ""service_declarations"": [], ""struct_declarations"": [], ""table_declarations"": [], ""union_declarations"": [ { ""name"": ""test.fidlcodec.examples/OriginalUnion"", ""location"": { ""filename"": ""../../src/lib/fidl_codec/testdata/xunionmigration.fidl"", ""line"": 16, ""column"": 7 }, ""members"": [ { ""name"": ""variant_u8"", ""type"": { ""kind"": ""primitive"", ""subtype"": ""uint8"" }, ""xunion_ordinal"": 917437055, ""location"": { ""filename"": ""../../src/lib/fidl_codec/testdata/xunionmigration.fidl"", ""line"": 17, ""column"": 11 }, ""size"": 1, ""max_out_of_line"": 0, ""alignment"": 1, ""offset"": 4 }, { ""name"": ""variant_u16"", ""type"": { ""kind"": ""primitive"", ""subtype"": ""uint16"" }, ""xunion_ordinal"": 949805239, ""location"": { ""filename"": ""../../src/lib/fidl_codec/testdata/xunionmigration.fidl"", ""line"": 18, ""column"": 12 }, ""size"": 2, ""max_out_of_line"": 0, ""alignment"": 2, ""offset"": 4 } ], ""size"": 8, ""max_out_of_line"": 0, ""alignment"": 4, ""max_handles"": 0 } ], ""xunion_declarations"": [] })FIDL""; std::unique_ptr file = std::make_unique(std::istringstream(future_schema)); library_files.push_back(std::move(file)); LibraryReadError err; LibraryLoader loader(&library_files, &err); ASSERT_TRUE(err.value == LibraryReadError::ErrorValue::kOk); // Encode a message using the unmodified fidl description. That means that we // encode a xunion. fidl::MessageBuffer buffer; fidl::Message message = buffer.CreateEmptyMessage(); InterceptRequest( message, [&](fidl::InterfacePtr& ptr) { ptr->SendAfterMigration(test::fidlcodec::examples::NowAsXUnion::WithVariantU16(1024), 1); }); fidl_message_header_t header = message.header(); const std::vector* methods = loader.GetByOrdinal(header.ordinal); ASSERT_NE(methods, nullptr); ASSERT_TRUE(!methods->empty()); const InterfaceMethod* method = (*methods)[0]; ASSERT_NE(method, nullptr); ASSERT_EQ(""SendAfterMigration"", method->name()); { // Decode the message using the modified description (the xunion is now a union). MessageDecoder decoder(message.bytes().data(), message.bytes().size(), nullptr, 0, /*output_errors=*/true); std::unique_ptr object = decoder.DecodeMessage(*method->request()); ASSERT_FALSE(decoder.HasError()) << ""Could not decode message""; rapidjson::Document actual; if (object != nullptr) { object->ExtractJson(actual.GetAllocator(), actual); } rapidjson::StringBuffer actual_string; rapidjson::Writer actual_w(actual_string); actual.Accept(actual_w); // Without setting the unions_are_xunions flag, we can't decode the message. rapidjson::Document expected; std::string expected_source = R""({""u"":{""unknown$949805239"":""""}, ""i"":""1""})""; expected.Parse(expected_source.c_str()); rapidjson::StringBuffer expected_string; rapidjson::Writer expected_w(expected_string); expected.Accept(expected_w); ASSERT_EQ(expected, actual) << ""expected = "" << expected_string.GetString() << "" ("" << expected_source << "")"" << "" and actual = "" << actual_string.GetString(); } { message.header().flags[0] = FIDL_TXN_HEADER_UNION_FROM_XUNION_FLAG; // Decode the message using the modified description (the xunion is now a union). MessageDecoder decoder(message.bytes().data(), message.bytes().size(), nullptr, 0, /*output_errors=*/true); std::unique_ptr object = decoder.DecodeMessage(*method->request()); ASSERT_FALSE(decoder.HasError()) << ""Could not decode message""; rapidjson::Document actual; if (object != nullptr) { object->ExtractJson(actual.GetAllocator(), actual); } rapidjson::StringBuffer actual_string; rapidjson::Writer actual_w(actual_string); actual.Accept(actual_w); // Because we set the unions_are_xunions flag, we can now decode the message correctly. rapidjson::Document expected; std::string expected_source = R""({""u"":{""variant_u16"":""1024""}, ""i"":""1""})""; expected.Parse(expected_source.c_str()); rapidjson::StringBuffer expected_string; rapidjson::Writer expected_w(expected_string); expected.Accept(expected_w); ASSERT_EQ(expected, actual) << ""expected = "" << expected_string.GetString() << "" ("" << expected_source << "")"" << "" and actual = "" << actual_string.GetString(); } } } // namespace fidl_codec ",16262,True,2902.846777189208,median "class ZSAPLINK_PROGRAM definition public inheriting from ZSAPLINK final create public . public section. methods CHECKEXISTS redefinition . methods CREATEIXMLDOCFROMOBJECT redefinition . methods CREATEOBJECTFROMIXMLDOC redefinition . methods CREATESTRINGFROMOBJECT redefinition . protected section. methods DELETEOBJECT redefinition . methods GETOBJECTTYPE redefinition . private section. methods GET_SOURCE returning value(PROGSOURCE) type RSWSOURCET . methods UPDATE_WB_TREE . methods CREATE_TEXTPOOL importing !TEXTPOOLNODE type ref to IF_IXML_ELEMENT . methods DEQUEUE_ABAP raising ZCX_SAPLINK . methods GET_TEXTPOOL returning value(TEXTNODE) type ref to IF_IXML_ELEMENT . methods CREATE_DOCUMENTATION importing !DOCNODE type ref to IF_IXML_ELEMENT . methods CREATE_SOURCE importing !SOURCE type TABLE_OF_STRINGS !ATTRIBS type TRDIR . methods ENQUEUE_ABAP raising ZCX_SAPLINK . methods GET_DOCUMENTATION returning value(DOCNODE) type ref to IF_IXML_ELEMENT . methods TRANSPORT_COPY importing !AUTHOR type SYUNAME !DEVCLASS type DEVCLASS raising ZCX_SAPLINK . methods GET_DYNPRO returning value(DYNP_NODE) type ref to IF_IXML_ELEMENT . methods CREATE_DYNPRO importing !DYNP_NODE type ref to IF_IXML_ELEMENT . methods GET_PFSTATUS returning value(PFSTAT_NODE) type ref to IF_IXML_ELEMENT . methods CREATE_PFSTATUS importing !PFSTAT_NODE type ref to IF_IXML_ELEMENT . endclass. ""ZSAPLINK_PROGRAM definition *----------------------------------------------------------------------* * class ZSAPLINK_PROGRAM implementation. *----------------------------------------------------------------------* * *----------------------------------------------------------------------* class ZSAPLINK_PROGRAM implementation. method CHECKEXISTS. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ select single name from trdir into objName where NAME = objName. if sy-subrc = 0. exists = 'X'. endif. endmethod. method CREATEIXMLDOCFROMOBJECT. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ data rootNode type ref to if_ixml_element. data sourceNode type ref to if_ixml_element. data textPoolNode type ref to if_ixml_element. data docNode type ref to if_ixml_element. data dynproNode type ref to if_ixml_element. data statusNode type ref to if_ixml_element. data rc type sysubrc. data progAttribs type trdir. data progSource type RSWSOURCET. data sourceString type string. data _objType type string. _objType = getObjectType( ). rootNode = xmlDoc->create_element( _objType ). sourceNode = xmlDoc->create_element( 'source' ). select single * from trdir into progAttribs where NAME = objName. if sy-subrc = 0. setAttributesFromStructure( node = rootNode structure = progAttribs ). progSource = me->get_source( ). sourceString = buildSourceString( sourceTable = progSource ). rc = sourceNode->IF_IXML_NODE~SET_VALUE( sourceString ). textPoolNode = get_textPool( ). rc = rootNOde->append_child( textPoolNode ). docNode = get_documentation( ). rc = rootNOde->append_child( docNode ). dynproNode = get_dynpro( ). rc = rootNode->append_child( dynproNode ). statusNode = get_pfstatus( ). rc = rootNode->append_child( statusNode ). rc = rootNode->append_child( sourceNode ). rc = xmldoc->append_child( rootNode ). ixmlDocument = xmlDoc. else. clear ixmlDocument. raise exception type zcx_saplink exporting textid = zcx_saplink=>not_found object = objname. endif. endmethod. method CREATEOBJECTFROMIXMLDOC. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ data rootnode type ref to if_ixml_element. data progattribs type trdir. data sourcenode type ref to if_ixml_element. data textnode type ref to if_ixml_element. data docnode type ref to if_ixml_element. data dynpnode type ref to if_ixml_element. data statnode type ref to if_ixml_element. data source type string. data sourcetable type table_of_strings. data _objname(30) type c. data aobjname type trobj_name. data _objtype type string. data checkexists type flag. *if sy-uname <> 'USDWM01'. * _objType = getObjectType( ). * xmlDoc = ixmlDocument. * rootNode = xmlDoc->find_from_name( _objType ). * call method GETSTRUCTUREFROMATTRIBUTES * exporting * node = rootNode * changing * structure = progAttribs. * objName = progAttribs-NAME. * ** check existing * select single name from trdir into objName where NAME = objName. * if sy-subrc = 0. * raise exception type zcx_saplink * exporting textid = zcx_saplink=>existing. * endif. * * sourceNode = rootNode->find_from_name( 'source' ). * source = sourceNode->get_value( ). * sourceTable = BUILDTABLEFROMSTRING( source ). * insert report progAttribs-NAME from sourceTable. * * commit work. * * call function 'RS_INSERT_INTO_WORKING_AREA' * EXPORTING * object = 'REPS' * obj_name = aobjName * EXCEPTIONS * wrong_object_name = 1. * if sy-subrc <> 0. * * endif. * *else. _objtype = getobjecttype( ). xmldoc = ixmldocument. rootnode = xmldoc->find_from_name( _objtype ). call method getstructurefromattributes exporting node = rootnode changing structure = progattribs. objname = progattribs-name. * check if object exists * select single name from trdir into objName where NAME = objName. * if sy-subrc = 0 and overwrite <> 'X'. * raise exception type zcx_saplink * exporting textid = zcx_saplink=>existing. * endif. checkexists = checkexists( ). if checkexists is not initial. if overwrite is initial. raise exception type zcx_saplink exporting textid = zcx_saplink=>existing. else. * delete object for new install deleteobject( ). endif. endif. enqueue_abap( ). transport_copy( author = progattribs-cnam devclass = devclass ). sourcenode = rootnode->find_from_name( 'source' ). source = sourcenode->get_value( ). sourcetable = buildtablefromstring( source ). create_source( source = sourcetable attribs = progattribs ). textnode = rootnode->find_from_name( 'textPool' ). create_textpool( textnode ). docnode = rootnode->find_from_name( 'programDocumentation' ). create_documentation( docnode ). dynpnode = rootnode->find_from_name( 'dynpros' ). create_dynpro( dynpnode ). statnode = rootnode->find_from_name( 'pfstatus' ). create_pfstatus( statnode ). dequeue_abap( ). update_wb_tree( ). *endif. * successful install name = objname. endmethod. method CREATESTRINGFROMOBJECT. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ data progSource type RSWSOURCET. progsource = me->get_source( ). string = buildsourcestring( sourcetable = progsource ). endmethod. method CREATE_DOCUMENTATION. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ DATA txtline_node TYPE REF TO if_ixml_element. DATA txtline_filter TYPE REF TO if_ixml_node_filter. DATA txtline_iterator TYPE REF TO if_ixml_node_iterator. DATA lang_node TYPE REF TO if_ixml_element. DATA lang_filter TYPE REF TO if_ixml_node_filter. DATA lang_iterator TYPE REF TO if_ixml_node_iterator. data obj_name type DOKHL-OBJECT. data prog_name type string. data language type string. data obj_langu type DOKHL-LANGU. data lv_str type string. data rc type sy-subrc. DATA lt_lines TYPE TABLE OF tline. FIELD-SYMBOLS: LIKE LINE OF lt_lines. if docnode is not bound. return. endif. prog_name = docNode->get_attribute( name = 'OBJECT' ). obj_name = prog_name. * If no prog name, then there was no program documenation, just return. if prog_name is initial. return. endif. * Get languages from XML FREE: lang_filter, lang_iterator, lang_node. lang_filter = docNode->create_filter_name( `language` ). lang_iterator = docNode->create_iterator_filtered( lang_filter ). lang_node ?= lang_iterator->get_next( ). WHILE lang_node IS NOT INITIAL. refresh lt_lines. language = lang_node->get_attribute( name = 'SPRAS' ). obj_langu = language. * Get TextLines from XML FREE: txtline_filter, txtline_iterator, txtline_node. txtline_filter = lang_node->create_filter_name( `textLine` ). txtline_iterator = lang_node->create_iterator_filtered( txtline_filter ). txtline_node ?= txtline_iterator->get_next( ). WHILE txtline_node IS NOT INITIAL. APPEND INITIAL LINE TO lt_lines ASSIGNING . me->getstructurefromattributes( EXPORTING node = txtline_node CHANGING structure = ). txtline_node ?= txtline_iterator->get_next( ). ENDWHILE. * Delete any documentation that may currently exist. CALL FUNCTION 'DOCU_DEL' EXPORTING id = 'RE' ""<-- Report/program documentation langu = obj_langu object = obj_name typ = 'E' EXCEPTIONS ret_code = 1 OTHERS = 2. * Now update with new documentation text CALL FUNCTION 'DOCU_UPD' EXPORTING id = 'RE' langu = obj_langu object = obj_name typ = 'E' TABLES line = lt_lines EXCEPTIONS ret_code = 1 OTHERS = 2. IF sy-subrc <> 0. RAISE EXCEPTION TYPE zcx_saplink EXPORTING textid = zcx_saplink=>error_message msg = `Program Documentation object import failed`. ENDIF. lang_node ?= lang_iterator->get_next( ). ENDWHILE. endmethod. method CREATE_DYNPRO. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ types: begin of tdyn_head_temp. include type d020s. types: dtext type d020t-dtxt. types: end of tdyn_head_temp. data: idyn_fldl type table of d021s, idyn_flow type table of d022s, idyn_mcod type table of d023s. data: xdyn_head type d020s, xdyn_fldl type d021s, xdyn_flow type d022s, xdyn_mcod type d023s. data: xdyn_text_string type string. data: xdyn_text type d020t-dtxt . data: xdyn_head_temp type tdyn_head_temp. data _objname type trobj_name. data dynpros_node type ref to if_ixml_element. data dynpros_filter type ref to if_ixml_node_filter. data dynpros_iterator type ref to if_ixml_node_iterator. data dynpro_node type ref to if_ixml_element. data dynpro_filter type ref to if_ixml_node_filter. data dynpro_iterator type ref to if_ixml_node_iterator. data dynfldl_node type ref to if_ixml_element. data dynfldl_filter type ref to if_ixml_node_filter. data dynfldl_iterator type ref to if_ixml_node_iterator. data dynmcod_node type ref to if_ixml_element. data dynmcod_filter type ref to if_ixml_node_filter. data dynmcod_iterator type ref to if_ixml_node_iterator. data dynflow_node type ref to if_ixml_element. data xdynpro_flow_source type string. data idynpro_flow_source type table_of_strings. _objname = objname. dynpros_node = dynp_node. check dynpros_node is not initial. free: dynpro_filter, dynpro_iterator, dynpro_node. dynpro_filter = dynpros_node->create_filter_name( 'dynpro' ). dynpro_iterator = dynpros_node->create_iterator_filtered( dynpro_filter ). dynpro_node ?= dynpro_iterator->get_next( ). while dynpro_node is not initial. clear: xdyn_head, xdyn_fldl, xdyn_flow, xdyn_mcod. refresh: idyn_fldl, idyn_flow, idyn_mcod. * Get the header data for the screen. call method getstructurefromattributes exporting node = dynpro_node changing structure = xdyn_head_temp. xdyn_head = xdyn_head_temp. xdyn_text = xdyn_head_temp-dtext. * Retrieve field list free: dynfldl_filter, dynfldl_iterator, dynfldl_node. dynfldl_filter = dynpro_node->create_filter_name( 'dynprofield' ). dynfldl_iterator = dynpro_node->create_iterator_filtered( dynfldl_filter ). dynfldl_node ?= dynfldl_iterator->get_next( ). while dynfldl_node is not initial. call method getstructurefromattributes exporting node = dynfldl_node changing structure = xdyn_fldl. append xdyn_fldl to idyn_fldl. dynfldl_node ?= dynfldl_iterator->get_next( ). endwhile. * Retrieve matchcode data. free: dynmcod_filter, dynmcod_iterator, dynmcod_node. dynmcod_filter = dynpro_node->create_filter_name( 'dynprofield' ). dynmcod_iterator = dynpro_node->create_iterator_filtered( dynmcod_filter ). dynmcod_node ?= dynmcod_iterator->get_next( ). while dynmcod_node is not initial. call method getstructurefromattributes exporting node = dynmcod_node changing structure = xdyn_mcod. append xdyn_mcod to idyn_mcod. dynmcod_node ?= dynmcod_iterator->get_next( ). endwhile. * retieve flow logic source. clear xdynpro_flow_source. refresh idynpro_flow_source. clear xdyn_flow. refresh idyn_flow. free dynflow_node. dynflow_node = dynpro_node->find_from_name( 'dynproflowsource' ). xdynpro_flow_source = dynflow_node->get_value( ). idynpro_flow_source = buildtablefromstring( xdynpro_flow_source ). loop at idynpro_flow_source into xdyn_flow. append xdyn_flow to idyn_flow. endloop. * Build dynpro from data call function 'RPY_DYNPRO_INSERT_NATIVE' exporting * suppress_corr_checks = ' ' * CORRNUM = ' ' header = xdyn_head dynprotext = xdyn_text * SUPPRESS_EXIST_CHECKS = ' ' * USE_CORRNUM_IMMEDIATEDLY = ' ' * SUPPRESS_COMMIT_WORK = ' ' tables fieldlist = idyn_fldl flowlogic = idyn_flow params = idyn_mcod exceptions cancelled = 1 already_exists = 2 program_not_exists = 3 not_executed = 4 others = 5. if sy-subrc <> 0. raise exception type zcx_saplink exporting textid = zcx_saplink=>system_error. endif. dynpro_node ?= dynpro_iterator->get_next( ). endwhile. endmethod. method CREATE_PFSTATUS. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ data: ista type table of rsmpe_stat, ifun type table of rsmpe_funt, imen type table of rsmpe_men, imtx type table of rsmpe_mnlt, iact type table of rsmpe_act, ibut type table of rsmpe_but, ipfk type table of rsmpe_pfk, iset type table of rsmpe_staf, idoc type table of rsmpe_atrt, itit type table of rsmpe_titt, ibiv type table of rsmpe_buts. data: xsta type rsmpe_stat, xfun type rsmpe_funt, xmen type rsmpe_men, xmtx type rsmpe_mnlt, xact type rsmpe_act, xbut type rsmpe_but, xpfk type rsmpe_pfk, xset type rsmpe_staf, xdoc type rsmpe_atrt, xtit type rsmpe_titt, xbiv type rsmpe_buts. data xtrkey type trkey. data xadm type rsmpe_adm. data _program type trdir-name. data _objname type trobj_name. data stat_node type ref to if_ixml_element. data node type ref to if_ixml_element. data filter type ref to if_ixml_node_filter. data iterator type ref to if_ixml_node_iterator. _objname = objname. stat_node = pfstat_node. check stat_node is not initial. * read pfstatus_sta node free: filter, iterator, node. filter = stat_node->create_filter_name( 'pfstatus_sta' ). iterator = stat_node->create_iterator_filtered( filter ). node ?= iterator->get_next( ). while node is not initial. call method getstructurefromattributes exporting node = node changing structure = xsta. append xsta to ista. node ?= iterator->get_next( ). endwhile. * read pfstatus_fun node free: filter, iterator, node. filter = stat_node->create_filter_name( 'pfstatus_fun' ). iterator = stat_node->create_iterator_filtered( filter ). node ?= iterator->get_next( ). while node is not initial. call method getstructurefromattributes exporting node = node changing structure = xfun. append xfun to ifun. node ?= iterator->get_next( ). endwhile. * read pfstatus_men node free: filter, iterator, node. filter = stat_node->create_filter_name( 'pfstatus_men' ). iterator = stat_node->create_iterator_filtered( filter ). node ?= iterator->get_next( ). while node is not initial. call method getstructurefromattributes exporting node = node changing structure = xmen. append xmen to imen. node ?= iterator->get_next( ). endwhile. * read pfstatus_mtx node free: filter, iterator, node. filter = stat_node->create_filter_name( 'pfstatus_mtx' ). iterator = stat_node->create_iterator_filtered( filter ). node ?= iterator->get_next( ). while node is not initial. call method getstructurefromattributes exporting node = node changing structure = xmtx. append xmtx to imtx. node ?= iterator->get_next( ). endwhile. * read pfstatus_act node free: filter, iterator, node. filter = stat_node->create_filter_name( 'pfstatus_act' ). iterator = stat_node->create_iterator_filtered( filter ). node ?= iterator->get_next( ). while node is not initial. call method getstructurefromattributes exporting node = node changing structure = xact. append xact to iact. node ?= iterator->get_next( ). endwhile. * read pfstatus_but node free: filter, iterator, node. filter = stat_node->create_filter_name( 'pfstatus_but' ). iterator = stat_node->create_iterator_filtered( filter ). node ?= iterator->get_next( ). while node is not initial. call method getstructurefromattributes exporting node = node changing structure = xbut. append xbut to ibut. node ?= iterator->get_next( ). endwhile. * read pfstatus_pfk node free: filter, iterator, node. filter = stat_node->create_filter_name( 'pfstatus_pfk' ). iterator = stat_node->create_iterator_filtered( filter ). node ?= iterator->get_next( ). while node is not initial. call method getstructurefromattributes exporting node = node changing structure = xpfk. append xpfk to ipfk. node ?= iterator->get_next( ). endwhile. * read pfstatus_set node free: filter, iterator, node. filter = stat_node->create_filter_name( 'pfstatus_set' ). iterator = stat_node->create_iterator_filtered( filter ). node ?= iterator->get_next( ). while node is not initial. call method getstructurefromattributes exporting node = node changing structure = xset. append xset to iset. node ?= iterator->get_next( ). endwhile. * read pfstatus_doc node free: filter, iterator, node. filter = stat_node->create_filter_name( 'pfstatus_doc' ). iterator = stat_node->create_iterator_filtered( filter ). node ?= iterator->get_next( ). while node is not initial. call method getstructurefromattributes exporting node = node changing structure = xdoc. append xdoc to idoc. node ?= iterator->get_next( ). endwhile. * read pfstatus_tit node free: filter, iterator, node. filter = stat_node->create_filter_name( 'pfstatus_tit' ). iterator = stat_node->create_iterator_filtered( filter ). node ?= iterator->get_next( ). while node is not initial. call method getstructurefromattributes exporting node = node changing structure = xtit. append xtit to itit. node ?= iterator->get_next( ). endwhile. * read pfstatus_biv node free: filter, iterator, node. filter = stat_node->create_filter_name( 'pfstatus_biv' ). iterator = stat_node->create_iterator_filtered( filter ). node ?= iterator->get_next( ). while node is not initial. call method getstructurefromattributes exporting node = node changing structure = xbiv. append xbiv to ibiv. node ?= iterator->get_next( ). endwhile. * Update the gui status _program = _objname. xtrkey-obj_type = 'PROG'. xtrkey-obj_name = _program. xtrkey-sub_type = 'CUAD'. xtrkey-sub_name = _program. call function 'RS_CUA_INTERNAL_WRITE' exporting program = _program language = sy-langu tr_key = xtrkey adm = xadm state = 'I' tables sta = ista fun = ifun men = imen mtx = imtx act = iact but = ibut pfk = ipfk set = iset doc = idoc tit = itit biv = ibiv exceptions not_found = 1 others = 2. if sy-subrc <> 0. raise exception type zcx_saplink exporting textid = zcx_saplink=>system_error. endif. endmethod. method CREATE_SOURCE. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ data _objName type TROBJ_NAME. data progLine type PROGDIR. data titleInfo type trdirti. data reportLine type string. data miniReport type table_of_strings. _objName = objName. call function 'RS_INSERT_INTO_WORKING_AREA' exporting OBJECT = 'REPS' OBJ_NAME = _objName exceptions WRONG_OBJECT_NAME = 1. INSERT REPORT _objName FROM source STATE 'I' program type attribs-subc. ""added to handle includes, etc. MOVE 'I' TO progline-STATE. move-corresponding attribs to progline. progline-idate = sy-datum. progline-itime = sy-uzeit. progline-CDAT = sy-datum. progline-UDAT = sy-datum. progline-SDATE = sy-datum. modify progdir from progline. * Are you kidding me?!? No idea why you need to do this!! CONCATENATE 'REPORT' _objName '.' INTO reportLine SEPARATED BY SPACE. append reportline to miniReport. INSERT REPORT _objName FROM miniReport STATE 'A' program type attribs-subc. ""added to handle includes, etc. MOVE 'A' TO progline-STATE. modify progdir from progline. endmethod. method CREATE_TEXTPOOL. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ data textPoolTable type standard table of textPool. data textPoolRow type textPool. data langIterator type ref to if_ixml_node_iterator. data filter type ref to if_ixml_node_filter. data textFilter type ref to if_ixml_node_filter. data textIterator type ref to if_ixml_node_iterator. data langNode type ref to if_ixml_element. data aTextNode type ref to if_ixml_element. data _objName type TROBJ_NAME. data lang type spras. data langNodeExists type flag. data logonLanguageExists type flag. data _state(1) type c. _objName = objName. CHECK textPoolNode IS NOT INITIAL. filter = textPoolNode->create_filter_name( 'language' ). langIterator = textPoolNode->create_iterator_filtered( filter ). langNode ?= langIterator->get_next( ). while langNode is not initial. langNodeExists = 'X'. CALL FUNCTION 'RS_INSERT_INTO_WORKING_AREA' EXPORTING OBJECT = 'REPT' OBJ_NAME = _objName EXCEPTIONS OTHERS = 0. refresh textPoolTable. textIterator = langNode->create_iterator( ). aTextNode ?= textIterator->get_next( ). *For some reason the 1st one is blank... not sure why. aTextNode ?= textIterator->get_next( ). while aTextNode is not initial. call method GETSTRUCTUREFROMATTRIBUTES exporting node = aTextNode changing structure = textPoolRow. append textPoolRow to textPoolTable. aTextNode ?= textIterator->get_next( ). endwhile. if textPoolTable is not initial. lang = langNode->get_attribute( 'SPRAS' ). if lang = sy-langu. logonLanguageExists = 'X'. _state = 'I'. else. * seems that if a textpool is inserted as inactive for language * other than the logon language, it is lost upon activation * not sure inserting as active is best solution,but seems to work _state = 'A'. endif. insert textpool _objName from textPooltable language lang state _state. endif. langNode ?= langIterator->get_next( ). endwhile. endmethod. method DELETEOBJECT. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ data program type sy-repid. program = objName. CALL FUNCTION 'RS_DELETE_PROGRAM' EXPORTING * CORRNUMBER = program = program * SUPPRESS_CHECKS = ' ' * SUPPRESS_COMMIT = ' ' SUPPRESS_POPUP = 'X' * MASS_DELETE_CALL = ' ' * WITH_CUA = 'X' * WITH_DOCUMENTATION = 'X' * WITH_DYNPRO = 'X' * WITH_INCLUDES = ' ' * WITH_TEXTPOOL = 'X' * WITH_VARIANTS = 'X' * TADIR_DEVCLASS = * SKIP_PROGRESS_IND = ' ' * FORCE_DELETE_USED_INCLUDES = ' ' * IMPORTING * CORRNUMBER = * PROGRAM = * EXCEPTIONS * ENQUEUE_LOCK = 1 * OBJECT_NOT_FOUND = 2 * PERMISSION_FAILURE = 3 * REJECT_DELETION = 4 * OTHERS = 5 . IF sy-subrc <> 0. * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO * WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4. ENDIF. endmethod. method DEQUEUE_ABAP. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ call function 'RS_ACCESS_PERMISSION' exporting global_lock = 'X' mode = 'FREE' object = objName object_class = 'ABAP' exceptions canceled_in_corr = 1 enqueued_by_user = 3 enqueue_system_failure = 4 locked_by_author = 5 illegal_parameter_values = 6 no_modify_permission = 7 no_show_permission = 8 permission_failure = 9. if sy-subrc <> 0. case sy-subrc. when 7 or 8 or 9. raise exception type zcx_saplink exporting textid = zcx_saplink=>not_authorized. when 5. raise exception type zcx_saplink exporting textid = zcx_saplink=>error_message msg = 'object locked'. when others. raise exception type zcx_saplink exporting textid = zcx_saplink=>system_error. endcase. endif. endmethod. method ENQUEUE_ABAP. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ call function 'RS_ACCESS_PERMISSION' exporting * authority_check = authority_check global_lock = 'X' mode = 'INSERT' * master_language = trdir-rload object = objName object_class = 'ABAP' * importing * transport_key = trkey_global * new_master_language = trdir-rload * devclass = devclass_local exceptions canceled_in_corr = 1 enqueued_by_user = 3 enqueue_system_failure = 4 locked_by_author = 5 illegal_parameter_values = 6 no_modify_permission = 7 no_show_permission = 8 permission_failure = 9. if sy-subrc <> 0. case sy-subrc. when 7 or 8 or 9. raise exception type zcx_saplink exporting textid = zcx_saplink=>not_authorized. when 5. raise exception type zcx_saplink exporting textid = zcx_saplink=>error_message msg = 'object locked'. when others. raise exception type zcx_saplink exporting textid = zcx_saplink=>system_error. endcase. endif. endmethod. method GETOBJECTTYPE. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ objectType = 'PROG'. ""ABAP Program endmethod. method GET_DOCUMENTATION. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ data languageNode type ref to if_ixml_element. DATA txtlines_node TYPE REF TO if_ixml_element. DATA rc TYPE sysubrc. DATA _objtype TYPE string. Types: BEGIN OF t_dokhl, id TYPE dokhl-id, object TYPE dokhl-object, langu type dokhl-langu, typ TYPE dokhl-typ, dokversion TYPE dokhl-dokversion, END OF t_dokhl. data lt_dokhl type table of t_dokhl. data ls_dokhl like line of lt_dokhl. DATA lt_lines TYPE TABLE OF tline. DATA ls_lines LIKE LINE OF lt_lines. data lv_str type string. DATA _objname TYPE e071-obj_name. _objname = objname. * Check against database SELECT id object langu typ dokversion INTO corresponding fields of table lt_dokhl FROM dokhl WHERE id = 'RE' AND object = _objname. * Use only most recent version. sort lt_dokhl by id object langu typ ascending dokversion descending. delete adjacent duplicates from lt_dokhl comparing id object typ langu. * Make sure there is at least one record here. clear ls_dokhl. read table lt_dokhl into ls_dokhl index 1. if sy-subrc <> 0. return. endif. docNode = xmlDoc->create_element( 'programDocumentation' ). * Set docNode object attribute lv_str = ls_dokhl-object. rc = docNode->set_attribute( name = 'OBJECT' value = lv_Str ). Loop at lt_dokhl into ls_dokhl. * Create language node, and set attribute languageNode = xmlDoc->create_element( 'language' ). lv_str = ls_dokhl-langu. rc = languageNode->set_attribute( name = 'SPRAS' value = lv_Str ). * Read the documentation text CALL FUNCTION 'DOCU_READ' EXPORTING id = ls_dokhl-id langu = ls_dokhl-langu object = ls_dokhl-object typ = ls_dokhl-typ version = ls_dokhl-dokversion TABLES line = lt_lines. * Write records to XML node LOOP AT lt_lines INTO ls_lines. txtlines_node = xmlDoc->create_element( `textLine` ). me->setattributesfromstructure( node = txtlines_node structure = ls_lines ). rc = languageNode->append_child( txtlines_node ). ENDLOOP. rc = docNode->append_child( languageNode ) . Endloop. endmethod. method GET_DYNPRO. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ types: begin of tdynp, prog type d020s-prog, dnum type d020s-dnum, end of tdynp. data: idyn_fldl type table of d021s, idyn_flow type table of d022s, idyn_mcod type table of d023s. data: xdyn_head type d020s, xdyn_fldl type d021s, xdyn_flow type d022s, xdyn_mcod type d023s. data idynp type table of tdynp. data xdynp type tdynp. data xdyn_text type d020t-dtxt. data xdyn_text_string type string. data _objname type trobj_name. data rc type sy-subrc . data iflowsource type rswsourcet. data xflowsource like line of iflowsource. data flowsourcestring type string. data dynnr_node type ref to if_ixml_element. data dynpromatchnode type ref to if_ixml_element. data dynprofieldsnode type ref to if_ixml_element. data dynproflownode type ref to if_ixml_element. _objname = objname. * Get all dynpros for program object clear xdynp. refresh idynp. select prog dnum into table idynp from d020s where prog = _objname and type <> 'S' "" No Selection Screens and type <> 'J'. "" No selection subscreens check sy-subrc = 0 . dynp_node = xmldoc->create_element( 'dynpros' ). loop at idynp into xdynp. * Retrieve dynpro imformation dynnr_node = xmldoc->create_element( 'dynpro' ). clear: xdyn_head, xdyn_fldl, xdyn_flow, xdyn_mcod. refresh: idyn_fldl, idyn_flow, idyn_mcod. call function 'RPY_DYNPRO_READ_NATIVE' exporting progname = xdynp-prog dynnr = xdynp-dnum * SUPPRESS_EXIST_CHECKS = ' ' * SUPPRESS_CORR_CHECKS = ' ' importing HEADER = xdyn_head dynprotext = xdyn_text tables fieldlist = idyn_fldl flowlogic = idyn_flow params = idyn_mcod * FIELDTEXTS = exceptions cancelled = 1 not_found = 2 permission_error = 3 others = 4. check sy-subrc = 0. * Add heading information for screen. setattributesfromstructure( node = dynnr_node structure = xdyn_head ). * Add the dynpro text also. xdyn_text_string = xdyn_text. rc = dynnr_node->set_attribute( name = 'DTEXT' value = xdyn_text_string ). rc = dynp_node->append_child( dynnr_node ). * Add fields information for screen. if not idyn_fldl[] is initial. loop at idyn_fldl into xdyn_fldl. dynprofieldsnode = xmldoc->create_element( 'dynprofield' ). setattributesfromstructure( node = dynprofieldsnode structure = xdyn_fldl ). rc = dynnr_node->append_child( dynprofieldsnode ). endloop. endif. * Add flow logic of screen if not idyn_flow[] is initial. clear xflowsource. refresh iflowsource. loop at idyn_flow into xdyn_flow. xflowsource = xdyn_flow. append xflowsource to iflowsource. endloop. dynproflownode = xmldoc->create_element( 'dynproflowsource' ). flowsourcestring = buildsourcestring( sourcetable = iflowsource ). rc = dynproflownode->if_ixml_node~set_value( flowsourcestring ). rc = dynnr_node->append_child( dynproflownode ). endif. * Add matchcode information for screen. if not idyn_mcod[] is initial. loop at idyn_mcod into xdyn_mcod. check not xdyn_mcod-type is initial and not xdyn_mcod-content is initial. dynpromatchnode = xmldoc->create_element( 'dynpromatchcode' ). setattributesfromstructure( node = dynpromatchnode structure = xdyn_mcod ). rc = dynnr_node->append_child( dynpromatchnode ). endloop. endif. endloop. endmethod. method GET_PFSTATUS. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ data: ista type table of rsmpe_stat, ifun type table of rsmpe_funt, imen type table of rsmpe_men, imtx type table of rsmpe_mnlt, iact type table of rsmpe_act, ibut type table of rsmpe_but, ipfk type table of rsmpe_pfk, iset type table of rsmpe_staf, idoc type table of rsmpe_atrt, itit type table of rsmpe_titt, ibiv type table of rsmpe_buts. data: xsta type rsmpe_stat, xfun type rsmpe_funt, xmen type rsmpe_men, xmtx type rsmpe_mnlt, xact type rsmpe_act, xbut type rsmpe_but, xpfk type rsmpe_pfk, xset type rsmpe_staf, xdoc type rsmpe_atrt, xtit type rsmpe_titt, xbiv type rsmpe_buts. data sta_node type ref to if_ixml_element. data fun_node type ref to if_ixml_element. data men_node type ref to if_ixml_element. data mtx_node type ref to if_ixml_element. data act_node type ref to if_ixml_element. data but_node type ref to if_ixml_element. data pfk_node type ref to if_ixml_element. data set_node type ref to if_ixml_element. data doc_node type ref to if_ixml_element. data tit_node type ref to if_ixml_element. data biv_node type ref to if_ixml_element. data _objname type trobj_name. data _program type trdir-name. data rc type sy-subrc. _objname = objname. _program = objname. call function 'RS_CUA_INTERNAL_FETCH' exporting program = _program language = sy-langu tables sta = ista fun = ifun men = imen mtx = imtx act = iact but = ibut pfk = ipfk set = iset doc = idoc tit = itit biv = ibiv exceptions not_found = 1 unknown_version = 2 others = 3. check sy-subrc = 0. * if there is a gui status or gui title present, then * create pfstatus node. if ista[] is not initial or itit[] is not initial. pfstat_node = xmldoc->create_element( 'pfstatus' ). endif. * if ista is filled, assume there are one or more * gui statuses if ista[] is not initial. loop at ista into xsta. sta_node = xmldoc->create_element( 'pfstatus_sta' ). setattributesfromstructure( node = sta_node structure = xsta ). rc = pfstat_node->append_child( sta_node ). endloop. loop at ifun into xfun. fun_node = xmldoc->create_element( 'pfstatus_fun' ). setattributesfromstructure( node = fun_node structure = xfun ). rc = pfstat_node->append_child( fun_node ). endloop. loop at imen into xmen. men_node = xmldoc->create_element( 'pfstatus_men' ). setattributesfromstructure( node = men_node structure = xmen ). rc = pfstat_node->append_child( men_node ). endloop. loop at imtx into xmtx. mtx_node = xmldoc->create_element( 'pfstatus_mtx' ). setattributesfromstructure( node = mtx_node structure = xmtx ). rc = pfstat_node->append_child( mtx_node ). endloop. loop at iact into xact. act_node = xmldoc->create_element( 'pfstatus_act' ). setattributesfromstructure( node = act_node structure = xact ). rc = pfstat_node->append_child( act_node ). endloop. loop at ibut into xbut. but_node = xmldoc->create_element( 'pfstatus_but' ). setattributesfromstructure( node = but_node structure = xbut ). rc = pfstat_node->append_child( but_node ). endloop. loop at ipfk into xpfk. pfk_node = xmldoc->create_element( 'pfstatus_pfk' ). setattributesfromstructure( node = pfk_node structure = xpfk ). rc = pfstat_node->append_child( pfk_node ). endloop. loop at iset into xset. set_node = xmldoc->create_element( 'pfstatus_set' ). setattributesfromstructure( node = set_node structure = xset ). rc = pfstat_node->append_child( set_node ). endloop. loop at idoc into xdoc. doc_node = xmldoc->create_element( 'pfstatus_doc' ). setattributesfromstructure( node = doc_node structure = xdoc ). rc = pfstat_node->append_child( doc_node ). endloop. loop at ibiv into xbiv. biv_node = xmldoc->create_element( 'pfstatus_biv' ). setattributesfromstructure( node = biv_node structure = xbiv ). rc = pfstat_node->append_child( biv_node ). endloop. endif. * It itit is filled, assume one or more titles if itit[] is not initial. loop at itit into xtit. tit_node = xmldoc->create_element( 'pfstatus_tit' ). setattributesfromstructure( node = tit_node structure = xtit ). rc = pfstat_node->append_child( tit_node ). endloop. endif. endmethod. method GET_SOURCE. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ data _objName(30) type c. _objName = me->objName. read report _objName into progSource. endmethod. method GET_TEXTPOOL. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ data aText type ref to if_ixml_element. data textPoolTable type standard table of TEXTPOOL. data textPoolRow type textPool. data languageList type instLang. data aLanguage type SPRAS. data _objName(30) type c. data rc type i. data sTemp type string. data languageNode type ref to if_ixml_element. data firstLoop type flag. _objName = objName. CALL FUNCTION 'RS_TEXTLOG_GET_PARAMETERS' changing INSTALLED_LANGUAGES = languageList. firstLoop = abap_true. loop at languageList into aLanguage. read textpool _objName into textPoolTable language aLanguage. if sy-subrc = 0. if firstLoop = abap_true. textNode = xmlDoc->create_element( 'textPool' ). firstLoop = abap_false. endif. languageNode = xmlDoc->create_Element( 'language' ). sTemp = aLanguage. rc = languageNode->set_attribute( name = 'SPRAS' value = sTemp ). loop at textPoolTable into textPoolRow. aText = xmlDoc->create_element( 'textElement' ). setAttributesFromStructure( node = aText structure = textPoolRow ). rc = languageNode->append_child( aText ). endloop. rc = textNode->append_child( languageNode ). endif. endloop. endmethod. method TRANSPORT_COPY. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ CALL FUNCTION 'RS_CORR_INSERT' EXPORTING AUTHOR = author GLOBAL_LOCK = 'X' OBJECT = objName OBJECT_CLASS = 'ABAP' DEVCLASS = devClass * KORRNUM = CORRNUMBER_LOCAL MASTER_LANGUAGE = sy-langu * PROGRAM = PROGRAM_LOCAL MODE = 'INSERT' * IMPORTING * AUTHOR = UNAME * KORRNUM = CORRNUMBER_LOCAL * DEVCLASS = DEVCLASS_LOCAL EXCEPTIONS CANCELLED = 1 PERMISSION_FAILURE = 2 UNKNOWN_OBJECTCLASS = 3. if sy-subrc <> 0. case sy-subrc. when 2. raise exception type zcx_saplink exporting textid = zcx_saplink=>not_authorized. when others. raise exception type zcx_saplink exporting textid = zcx_saplink=>system_error. endcase. endif. endmethod. method UPDATE_WB_TREE. DATA: BEGIN OF pname, root(3) VALUE 'PG_', program(27), END OF pname. DATA: trdir TYPE trdir. pname-program = me->objname. CALL FUNCTION 'WB_TREE_ACTUALIZE' EXPORTING tree_name = pname. trdir-name = me->objname. CALL FUNCTION 'RS_TREE_OBJECT_PLACEMENT' EXPORTING object = trdir-name program = trdir-name operation = 'INSERT' type = 'CP'. endmethod. endclass. ""ZSAPLINK_PROGRAM implementation",13453,True,3123.4065154951463,median "/**************************************************************************** * * Copyright (c) 2013-2015 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name PX4 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. * ****************************************************************************/ /** * @file position_estimator_inav_main.c * Model-identification based position estimator for multirotors * * @author Anton Babushkin * @author Nuno Marques * @author Christoph Tobler */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include ""position_estimator_inav_params.h"" #include ""inertial_filter.h"" #define MIN_VALID_W 0.00001f #define PUB_INTERVAL 10000 // limit publish rate to 100 Hz #define EST_BUF_SIZE 250000 / PUB_INTERVAL // buffer size is 0.5s #define MAX_WAIT_FOR_BARO_SAMPLE 3000000 // wait 3 secs for the baro to respond static bool thread_should_exit = false; /**< Deamon exit flag */ static bool thread_running = false; /**< Deamon status flag */ static int position_estimator_inav_task; /**< Handle of deamon task / thread */ static bool inav_verbose_mode = false; static const hrt_abstime vision_topic_timeout = 500000; // Vision topic timeout = 0.5s static const hrt_abstime mocap_topic_timeout = 500000; // Mocap topic timeout = 0.5s static const hrt_abstime gps_topic_timeout = 500000; // GPS topic timeout = 0.5s static const hrt_abstime flow_topic_timeout = 1000000; // optical flow topic timeout = 1s static const hrt_abstime lidar_timeout = 150000; // lidar timeout = 150ms static const hrt_abstime lidar_valid_timeout = 1000000; // estimate lidar distance during this time after lidar loss static const unsigned updates_counter_len = 1000000; static const float max_flow = 1.0f; // max flow value that can be used, rad/s extern ""C"" __EXPORT int position_estimator_inav_main(int argc, char *argv[]); int position_estimator_inav_thread_main(int argc, char *argv[]); static void usage(const char *reason); static inline int min(int val1, int val2) { return (val1 < val2) ? val1 : val2; } static inline int max(int val1, int val2) { return (val1 > val2) ? val1 : val2; } /** * Print the correct usage. */ static void usage(const char *reason) { if (reason && *reason) { PX4_INFO(""%s"", reason); } PX4_INFO(""usage: position_estimator_inav {start|stop|status} [-v]\\n""); } /** * The position_estimator_inav_thread only briefly exists to start * the background job. The stack size assigned in the * Makefile does only apply to this management task. * * The actual stack size should be set in the call * to task_create(). */ int position_estimator_inav_main(int argc, char *argv[]) { if (argc < 2) { usage(""missing command""); } if (!strcmp(argv[1], ""start"")) { if (thread_running) { warnx(""already running""); /* this is not an error */ return 0; } inav_verbose_mode = false; if ((argc > 2) && (!strcmp(argv[2], ""-v""))) { inav_verbose_mode = true; } thread_should_exit = false; position_estimator_inav_task = px4_task_spawn_cmd(""position_estimator_inav"", SCHED_DEFAULT, SCHED_PRIORITY_MAX - 5, 4600, position_estimator_inav_thread_main, (argv && argc > 2) ? (char *const *) &argv[2] : (char *const *) nullptr); return 0; } if (!strcmp(argv[1], ""stop"")) { if (thread_running) { warnx(""stop""); thread_should_exit = true; } else { warnx(""not started""); } return 0; } if (!strcmp(argv[1], ""status"")) { if (thread_running) { warnx(""is running""); } else { warnx(""not started""); } return 0; } usage(""unrecognized command""); return 1; } #ifdef INAV_DEBUG static void write_debug_log(const char *msg, float dt, float x_est[2], float y_est[2], float z_est[2], float x_est_prev[2], float y_est_prev[2], float z_est_prev[2], float acc[3], float corr_gps[3][2], float w_xy_gps_p, float w_xy_gps_v, float corr_mocap[3][1], float w_mocap_p, float corr_vision[3][2], float w_xy_vision_p, float w_z_vision_p, float w_xy_vision_v) { FILE *f = fopen(PX4_ROOTFSDIR""/fs/microsd/inav.log"", ""a""); if (f) { char *s = malloc(256); unsigned n = snprintf(s, 256, ""%llu %s\\n\\tdt=%.5f x_est=[%.5f %.5f] y_est=[%.5f %.5f] z_est=[%.5f %.5f] x_est_prev=[%.5f %.5f] y_est_prev=[%.5f %.5f] z_est_prev=[%.5f %.5f]\\n"", (unsigned long long)hrt_absolute_time(), msg, (double)dt, (double)x_est[0], (double)x_est[1], (double)y_est[0], (double)y_est[1], (double)z_est[0], (double)z_est[1], (double)x_est_prev[0], (double)x_est_prev[1], (double)y_est_prev[0], (double)y_est_prev[1], (double)z_est_prev[0], (double)z_est_prev[1]); fwrite(s, 1, n, f); n = snprintf(s, 256, ""\\tacc=[%.5f %.5f %.5f] gps_pos_corr=[%.5f %.5f %.5f] gps_vel_corr=[%.5f %.5f %.5f] w_xy_gps_p=%.5f w_xy_gps_v=%.5f mocap_pos_corr=[%.5f %.5f %.5f] w_mocap_p=%.5f\\n"", (double)acc[0], (double)acc[1], (double)acc[2], (double)corr_gps[0][0], (double)corr_gps[1][0], (double)corr_gps[2][0], (double)corr_gps[0][1], (double)corr_gps[1][1], (double)corr_gps[2][1], (double)w_xy_gps_p, (double)w_xy_gps_v, (double)corr_mocap[0][0], (double)corr_mocap[1][0], (double)corr_mocap[2][0], (double)w_mocap_p); fwrite(s, 1, n, f); n = snprintf(s, 256, ""\\tvision_pos_corr=[%.5f %.5f %.5f] vision_vel_corr=[%.5f %.5f %.5f] w_xy_vision_p=%.5f w_z_vision_p=%.5f w_xy_vision_v=%.5f\\n"", (double)corr_vision[0][0], (double)corr_vision[1][0], (double)corr_vision[2][0], (double)corr_vision[0][1], (double)corr_vision[1][1], (double)corr_vision[2][1], (double)w_xy_vision_p, (double)w_z_vision_p, (double)w_xy_vision_v); fwrite(s, 1, n, f); free(s); } fsync(fileno(f)); fclose(f); } #else #define write_debug_log(...) #endif /**************************************************************************** * main ****************************************************************************/ int position_estimator_inav_thread_main(int argc, char *argv[]) { orb_advert_t mavlink_log_pub = nullptr; float x_est[2] = { 0.0f, 0.0f }; // pos, vel float y_est[2] = { 0.0f, 0.0f }; // pos, vel float z_est[2] = { 0.0f, 0.0f }; // pos, vel float est_buf[EST_BUF_SIZE][3][2]; // estimated position buffer float R_buf[EST_BUF_SIZE][3][3]; // rotation matrix buffer float R_gps[3][3]; // rotation matrix for GPS correction moment memset(est_buf, 0, sizeof(est_buf)); memset(R_buf, 0, sizeof(R_buf)); memset(R_gps, 0, sizeof(R_gps)); int buf_ptr = 0; static const float min_eph_epv = 2.0f; // min EPH/EPV, used for weight calculation static const float max_eph_epv = 20.0f; // max EPH/EPV acceptable for estimation float eph = max_eph_epv; float epv = 1.0f; float eph_flow = 1.0f; float eph_vision = 0.2f; float epv_vision = 0.2f; float eph_mocap = 0.05f; float epv_mocap = 0.05f; float x_est_prev[2], y_est_prev[2], z_est_prev[2]; memset(x_est_prev, 0, sizeof(x_est_prev)); memset(y_est_prev, 0, sizeof(y_est_prev)); memset(z_est_prev, 0, sizeof(z_est_prev)); int baro_init_cnt = 0; int baro_init_num = 200; float baro_offset = 0.0f; // baro offset for reference altitude, initialized on start, then adjusted hrt_abstime accel_timestamp = 0; hrt_abstime baro_timestamp = 0; bool ref_inited = false; hrt_abstime ref_init_start = 0; const hrt_abstime ref_init_delay = 1000000; // wait for 1s after 3D fix struct map_projection_reference_s ref; memset(&ref, 0, sizeof(ref)); uint16_t accel_updates = 0; uint16_t baro_updates = 0; uint16_t gps_updates = 0; uint16_t attitude_updates = 0; uint16_t flow_updates = 0; uint16_t vision_updates = 0; uint16_t mocap_updates = 0; hrt_abstime updates_counter_start = hrt_absolute_time(); hrt_abstime pub_last = hrt_absolute_time(); hrt_abstime t_prev = 0; /* store error when sensor updates, but correct on each time step to avoid jumps in estimated value */ float acc[] = { 0.0f, 0.0f, 0.0f }; // N E D float acc_bias[] = { 0.0f, 0.0f, 0.0f }; // body frame float corr_baro = 0.0f; // D float corr_gps[3][2] = { { 0.0f, 0.0f }, // N (pos, vel) { 0.0f, 0.0f }, // E (pos, vel) { 0.0f, 0.0f }, // D (pos, vel) }; float w_gps_xy = 1.0f; float w_gps_z = 1.0f; float corr_vision[3][2] = { { 0.0f, 0.0f }, // N (pos, vel) { 0.0f, 0.0f }, // E (pos, vel) { 0.0f, 0.0f }, // D (pos, vel) }; float corr_mocap[3][1] = { { 0.0f }, // N (pos) { 0.0f }, // E (pos) { 0.0f }, // D (pos) }; const int mocap_heading = 2; float dist_ground = 0.0f; //variables for lidar altitude estimation float corr_lidar = 0.0f; float lidar_offset = 0.0f; int lidar_offset_count = 0; bool lidar_first = true; bool use_lidar = false; bool use_lidar_prev = false; float corr_flow[] = { 0.0f, 0.0f }; // N E float w_flow = 0.0f; hrt_abstime lidar_time = 0; // time of last lidar measurement (not filtered) hrt_abstime lidar_valid_time = 0; // time of last lidar measurement used for correction (filtered) int n_flow = 0; float gyro_offset_filtered[] = { 0.0f, 0.0f, 0.0f }; float flow_gyrospeed[] = { 0.0f, 0.0f, 0.0f }; float flow_gyrospeed_filtered[] = { 0.0f, 0.0f, 0.0f }; float att_gyrospeed_filtered[] = { 0.0f, 0.0f, 0.0f }; float yaw_comp[] = { 0.0f, 0.0f }; hrt_abstime flow_time = 0; float flow_min_dist = 0.2f; bool gps_valid = false; // GPS is valid bool lidar_valid = false; // lidar is valid bool flow_valid = false; // flow is valid bool flow_accurate = false; // flow should be accurate (this flag not updated if flow_valid == false) bool vision_valid = false; // vision is valid bool mocap_valid = false; // mocap is valid /* declare and safely initialize all structs */ struct actuator_controls_s actuator; memset(&actuator, 0, sizeof(actuator)); struct actuator_armed_s armed; memset(&armed, 0, sizeof(armed)); struct sensor_combined_s sensor; memset(&sensor, 0, sizeof(sensor)); struct vehicle_gps_position_s gps; memset(&gps, 0, sizeof(gps)); struct vehicle_attitude_s att; memset(&att, 0, sizeof(att)); struct vehicle_local_position_s local_pos; memset(&local_pos, 0, sizeof(local_pos)); struct optical_flow_s flow; memset(&flow, 0, sizeof(flow)); struct vehicle_local_position_s vision; memset(&vision, 0, sizeof(vision)); struct att_pos_mocap_s mocap; memset(&mocap, 0, sizeof(mocap)); struct vehicle_global_position_s global_pos; memset(&global_pos, 0, sizeof(global_pos)); struct distance_sensor_s lidar; memset(&lidar, 0, sizeof(lidar)); struct vehicle_rates_setpoint_s rates_setpoint; memset(&rates_setpoint, 0, sizeof(rates_setpoint)); /* subscribe */ int parameter_update_sub = orb_subscribe(ORB_ID(parameter_update)); int actuator_sub = orb_subscribe(ORB_ID_VEHICLE_ATTITUDE_CONTROLS); int armed_sub = orb_subscribe(ORB_ID(actuator_armed)); int sensor_combined_sub = orb_subscribe(ORB_ID(sensor_combined)); int vehicle_attitude_sub = orb_subscribe(ORB_ID(vehicle_attitude)); int optical_flow_sub = orb_subscribe(ORB_ID(optical_flow)); int vehicle_gps_position_sub = orb_subscribe(ORB_ID(vehicle_gps_position)); int vision_position_sub = orb_subscribe(ORB_ID(vehicle_vision_position)); int att_pos_mocap_sub = orb_subscribe(ORB_ID(att_pos_mocap)); int distance_sensor_sub = orb_subscribe(ORB_ID(distance_sensor)); int vehicle_rate_sp_sub = orb_subscribe(ORB_ID(vehicle_rates_setpoint)); /* advertise */ orb_advert_t vehicle_local_position_pub = orb_advertise(ORB_ID(vehicle_local_position), &local_pos); orb_advert_t vehicle_global_position_pub = nullptr; struct position_estimator_inav_params params; memset(¶ms, 0, sizeof(params)); struct position_estimator_inav_param_handles pos_inav_param_handles; /* initialize parameter handles */ inav_parameters_init(&pos_inav_param_handles); /* first parameters read at start up */ struct parameter_update_s param_update; orb_copy(ORB_ID(parameter_update), parameter_update_sub, ¶m_update); /* read from param topic to clear updated flag */ /* first parameters update */ inav_parameters_update(&pos_inav_param_handles, ¶ms); px4_pollfd_struct_t fds_init[1] = {}; fds_init[0].fd = sensor_combined_sub; fds_init[0].events = POLLIN; /* wait for initial baro value */ bool wait_baro = true; TerrainEstimator terrain_estimator; thread_running = true; hrt_abstime baro_wait_for_sample_time = hrt_absolute_time(); while (wait_baro && !thread_should_exit) { int ret = px4_poll(&fds_init[0], 1, 1000); if (ret < 0) { /* poll error */ mavlink_log_info(&mavlink_log_pub, ""[inav] poll error on init""); } else if (hrt_absolute_time() - baro_wait_for_sample_time > MAX_WAIT_FOR_BARO_SAMPLE) { wait_baro = false; mavlink_log_info(&mavlink_log_pub, ""[inav] timed out waiting for a baro sample""); } else if (ret > 0) { if (fds_init[0].revents & POLLIN) { orb_copy(ORB_ID(sensor_combined), sensor_combined_sub, &sensor); bool baro_updated = (sensor.baro_timestamp_relative != sensor.RELATIVE_TIMESTAMP_INVALID); if (wait_baro && sensor.timestamp + sensor.baro_timestamp_relative != baro_timestamp && baro_updated) { baro_timestamp = sensor.timestamp + sensor.baro_timestamp_relative; baro_wait_for_sample_time = hrt_absolute_time(); /* mean calculation over several measurements */ if (baro_init_cnt < baro_init_num) { if (PX4_ISFINITE(sensor.baro_alt_meter)) { baro_offset += sensor.baro_alt_meter; baro_init_cnt++; } } else { wait_baro = false; baro_offset /= (float) baro_init_cnt; local_pos.z_valid = true; local_pos.v_z_valid = true; } } } } else { PX4_WARN(""INAV poll timeout""); } } /* main loop */ px4_pollfd_struct_t fds[1]; fds[0].fd = vehicle_attitude_sub; fds[0].events = POLLIN; while (!thread_should_exit) { int ret = px4_poll(fds, 1, 20); // wait maximal 20 ms = 50 Hz minimum rate hrt_abstime t = hrt_absolute_time(); if (ret < 0) { /* poll error */ mavlink_log_info(&mavlink_log_pub, ""[inav] poll error on init""); continue; } else if (ret > 0) { /* act on attitude updates */ /* vehicle attitude */ orb_copy(ORB_ID(vehicle_attitude), vehicle_attitude_sub, &att); attitude_updates++; bool updated; /* parameter update */ orb_check(parameter_update_sub, &updated); if (updated) { struct parameter_update_s update; orb_copy(ORB_ID(parameter_update), parameter_update_sub, &update); inav_parameters_update(&pos_inav_param_handles, ¶ms); } /* actuator */ orb_check(actuator_sub, &updated); if (updated) { orb_copy(ORB_ID_VEHICLE_ATTITUDE_CONTROLS, actuator_sub, &actuator); } /* armed */ orb_check(armed_sub, &updated); if (updated) { orb_copy(ORB_ID(actuator_armed), armed_sub, &armed); } /* sensor combined */ orb_check(sensor_combined_sub, &updated); matrix::Dcmf R = matrix::Quatf(att.q); if (updated) { orb_copy(ORB_ID(sensor_combined), sensor_combined_sub, &sensor); if (sensor.timestamp + sensor.accelerometer_timestamp_relative != accel_timestamp) { /* correct accel bias */ sensor.accelerometer_m_s2[0] -= acc_bias[0]; sensor.accelerometer_m_s2[1] -= acc_bias[1]; sensor.accelerometer_m_s2[2] -= acc_bias[2]; /* transform acceleration vector from body frame to NED frame */ for (int i = 0; i < 3; i++) { acc[i] = 0.0f; for (int j = 0; j < 3; j++) { acc[i] += R(i, j) * sensor.accelerometer_m_s2[j]; } } acc[2] += CONSTANTS_ONE_G; accel_timestamp = sensor.timestamp + sensor.accelerometer_timestamp_relative; accel_updates++; } if (sensor.timestamp + sensor.baro_timestamp_relative != baro_timestamp) { corr_baro = baro_offset - sensor.baro_alt_meter - z_est[0]; baro_timestamp = sensor.timestamp + sensor.baro_timestamp_relative; baro_updates++; } } /* lidar alt estimation */ orb_check(distance_sensor_sub, &updated); /* update lidar separately, needed by terrain estimator */ if (updated) { orb_copy(ORB_ID(distance_sensor), distance_sensor_sub, &lidar); lidar.current_distance += params.lidar_calibration_offset; } if (updated) { //check if altitude estimation for lidar is enabled and new sensor data if (params.enable_lidar_alt_est && lidar.current_distance > lidar.min_distance && lidar.current_distance < lidar.max_distance && (R(2, 2) > 0.7f)) { if (!use_lidar_prev && use_lidar) { lidar_first = true; } use_lidar_prev = use_lidar; lidar_time = t; dist_ground = lidar.current_distance * R(2, 2); //vertical distance if (lidar_first) { lidar_first = false; lidar_offset = dist_ground + z_est[0]; mavlink_log_info(&mavlink_log_pub, ""[inav] LIDAR: new ground offset""); warnx(""[inav] LIDAR: new ground offset""); } corr_lidar = lidar_offset - dist_ground - z_est[0]; if (fabsf(corr_lidar) > params.lidar_err) { //check for spike corr_lidar = 0; lidar_valid = false; lidar_offset_count++; if (lidar_offset_count > 3) { //if consecutive bigger/smaller measurements -> new ground offset -> reinit lidar_first = true; lidar_offset_count = 0; } } else { corr_lidar = lidar_offset - dist_ground - z_est[0]; lidar_valid = true; lidar_offset_count = 0; lidar_valid_time = t; } } else { lidar_valid = false; } } /* optical flow */ orb_check(optical_flow_sub, &updated); if (updated && lidar_valid) { orb_copy(ORB_ID(optical_flow), optical_flow_sub, &flow); flow_time = t; float flow_q = flow.quality / 255.0f; float dist_bottom = lidar.current_distance; if (dist_bottom > flow_min_dist && flow_q > params.flow_q_min && R(2, 2) > 0.7f) { /* distance to surface */ //float flow_dist = dist_bottom / PX4_R(att.R, 2, 2); //use this if using sonar float flow_dist = dist_bottom; //use this if using lidar /* check if flow if too large for accurate measurements */ /* calculate estimated velocity in body frame */ float body_v_est[2] = { 0.0f, 0.0f }; for (int i = 0; i < 2; i++) { body_v_est[i] = R(0, i) * x_est[1] + R(1, i) * y_est[1] + R(2, i) * z_est[1]; } /* set this flag if flow should be accurate according to current velocity and attitude rate estimate */ flow_accurate = fabsf(body_v_est[1] / flow_dist - att.rollspeed) < max_flow && fabsf(body_v_est[0] / flow_dist + att.pitchspeed) < max_flow; /*calculate offset of flow-gyro using already calibrated gyro from autopilot*/ flow_gyrospeed[0] = flow.gyro_x_rate_integral / (float)flow.integration_timespan * 1000000.0f; flow_gyrospeed[1] = flow.gyro_y_rate_integral / (float)flow.integration_timespan * 1000000.0f; flow_gyrospeed[2] = flow.gyro_z_rate_integral / (float)flow.integration_timespan * 1000000.0f; //moving average if (n_flow >= 100) { gyro_offset_filtered[0] = flow_gyrospeed_filtered[0] - att_gyrospeed_filtered[0]; gyro_offset_filtered[1] = flow_gyrospeed_filtered[1] - att_gyrospeed_filtered[1]; gyro_offset_filtered[2] = flow_gyrospeed_filtered[2] - att_gyrospeed_filtered[2]; n_flow = 0; flow_gyrospeed_filtered[0] = 0.0f; flow_gyrospeed_filtered[1] = 0.0f; flow_gyrospeed_filtered[2] = 0.0f; att_gyrospeed_filtered[0] = 0.0f; att_gyrospeed_filtered[1] = 0.0f; att_gyrospeed_filtered[2] = 0.0f; } else { flow_gyrospeed_filtered[0] = (flow_gyrospeed[0] + n_flow * flow_gyrospeed_filtered[0]) / (n_flow + 1); flow_gyrospeed_filtered[1] = (flow_gyrospeed[1] + n_flow * flow_gyrospeed_filtered[1]) / (n_flow + 1); flow_gyrospeed_filtered[2] = (flow_gyrospeed[2] + n_flow * flow_gyrospeed_filtered[2]) / (n_flow + 1); att_gyrospeed_filtered[0] = (att.pitchspeed + n_flow * att_gyrospeed_filtered[0]) / (n_flow + 1); att_gyrospeed_filtered[1] = (att.rollspeed + n_flow * att_gyrospeed_filtered[1]) / (n_flow + 1); att_gyrospeed_filtered[2] = (att.yawspeed + n_flow * att_gyrospeed_filtered[2]) / (n_flow + 1); n_flow++; } /*yaw compensation (flow sensor is not in center of rotation) -> params in QGC*/ yaw_comp[0] = - params.flow_module_offset_y * (flow_gyrospeed[2] - gyro_offset_filtered[2]); yaw_comp[1] = params.flow_module_offset_x * (flow_gyrospeed[2] - gyro_offset_filtered[2]); /* * Convert raw flow from the optical_flow uORB topic (rad) to angular flow (rad/s) * Note that the optical_flow uORB topic defines positive delta angles as produced by RH rotations * around the correspdonding body axes. */ float flow_ang[2]; /* check for vehicle rates setpoint - it below threshold -> dont subtract -> better hover */ orb_check(vehicle_rate_sp_sub, &updated); if (updated) { orb_copy(ORB_ID(vehicle_rates_setpoint), vehicle_rate_sp_sub, &rates_setpoint); } float rate_threshold = 0.15f; /* calculate the angular flow rate produced by a negative velocity along the X body axis */ if (fabsf(rates_setpoint.pitch) < rate_threshold) { //warnx(""[inav] test ohne comp""); flow_ang[0] = (-flow.pixel_flow_y_integral / (float)flow.integration_timespan * 1000000.0f) * params.flow_k;//for now the flow has to be scaled (to small) } else { //warnx(""[inav] test mit comp""); //calculate flow [rad/s] and compensate for rotations (and offset of flow-gyro) flow_ang[0] = (-(flow.pixel_flow_y_integral - flow.gyro_y_rate_integral) / (float)flow.integration_timespan * 1000000.0f + gyro_offset_filtered[0]) * params.flow_k;//for now the flow has to be scaled (to small) } /* calculate the angular flow rate produced by a negative velocity along the Y body axis */ if (fabsf(rates_setpoint.roll) < rate_threshold) { flow_ang[1] = (flow.pixel_flow_x_integral / (float)flow.integration_timespan * 1000000.0f) * params.flow_k;//for now the flow has to be scaled (to small) } else { //calculate flow [rad/s] and compensate for rotations (and offset of flow-gyro) flow_ang[1] = ((flow.pixel_flow_x_integral - flow.gyro_x_rate_integral) / (float)flow.integration_timespan * 1000000.0f + gyro_offset_filtered[1]) * params.flow_k;//for now the flow has to be scaled (to small) } /* flow measurements vector */ float flow_m[3]; if (fabsf(rates_setpoint.yaw) < rate_threshold) { flow_m[0] = -flow_ang[0] * flow_dist; flow_m[1] = -flow_ang[1] * flow_dist; } else { flow_m[0] = -flow_ang[0] * flow_dist - yaw_comp[0] * params.flow_k; flow_m[1] = -flow_ang[1] * flow_dist - yaw_comp[1] * params.flow_k; } flow_m[2] = z_est[1]; /* velocity in NED */ float flow_v[2] = { 0.0f, 0.0f }; /* project measurements vector to NED basis, skip Z component */ for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { flow_v[i] += R(i, j) * flow_m[j]; } } /* velocity correction */ corr_flow[0] = flow_v[0] - x_est[1]; corr_flow[1] = flow_v[1] - y_est[1]; /* adjust correction weight */ float flow_q_weight = (flow_q - params.flow_q_min) / (1.0f - params.flow_q_min); w_flow = R(2, 2) * flow_q_weight / fmaxf(1.0f, flow_dist); /* if flow is not accurate, reduce weight for it */ // TODO make this more fuzzy if (!flow_accurate) { w_flow *= 0.05f; } /* under ideal conditions, on 1m distance assume EPH = 10cm */ eph_flow = 0.1f / w_flow; flow_valid = true; } else { w_flow = 0.0f; flow_valid = false; } flow_updates++; } /* check no vision circuit breaker is set */ if (params.no_vision != CBRK_NO_VISION_KEY) { /* vehicle vision position */ orb_check(vision_position_sub, &updated); if (updated) { orb_copy(ORB_ID(vehicle_vision_position), vision_position_sub, &vision); static float last_vision_x = 0.0f; static float last_vision_y = 0.0f; static float last_vision_z = 0.0f; /* reset position estimate on first vision update */ if (!vision_valid) { x_est[0] = vision.x; x_est[1] = vision.vx; y_est[0] = vision.y; y_est[1] = vision.vy; /* only reset the z estimate if the z weight parameter is not zero */ if (params.w_z_vision_p > MIN_VALID_W) { z_est[0] = vision.z; z_est[1] = vision.vz; } vision_valid = true; last_vision_x = vision.x; last_vision_y = vision.y; last_vision_z = vision.z; warnx(""VISION estimate valid""); mavlink_log_info(&mavlink_log_pub, ""[inav] VISION estimate valid""); } /* calculate correction for position */ corr_vision[0][0] = vision.x - x_est[0]; corr_vision[1][0] = vision.y - y_est[0]; corr_vision[2][0] = vision.z - z_est[0]; static hrt_abstime last_vision_time = 0; float vision_dt = (vision.timestamp - last_vision_time) / 1e6f; last_vision_time = vision.timestamp; if (vision_dt > 0.000001f && vision_dt < 0.2f) { vision.vx = (vision.x - last_vision_x) / vision_dt; vision.vy = (vision.y - last_vision_y) / vision_dt; vision.vz = (vision.z - last_vision_z) / vision_dt; last_vision_x = vision.x; last_vision_y = vision.y; last_vision_z = vision.z; /* calculate correction for velocity */ corr_vision[0][1] = vision.vx - x_est[1]; corr_vision[1][1] = vision.vy - y_est[1]; corr_vision[2][1] = vision.vz - z_est[1]; } else { /* assume zero motion */ corr_vision[0][1] = 0.0f - x_est[1]; corr_vision[1][1] = 0.0f - y_est[1]; corr_vision[2][1] = 0.0f - z_est[1]; } vision_updates++; } } /* vehicle mocap position */ orb_check(att_pos_mocap_sub, &updated); if (updated) { orb_copy(ORB_ID(att_pos_mocap), att_pos_mocap_sub, &mocap); if (!params.disable_mocap) { /* reset position estimate on first mocap update */ if (!mocap_valid) { x_est[0] = mocap.x; y_est[0] = mocap.y; z_est[0] = mocap.z; mocap_valid = true; warnx(""MOCAP data valid""); mavlink_log_info(&mavlink_log_pub, ""[inav] MOCAP data valid""); } /* calculate correction for position */ corr_mocap[0][0] = mocap.x - x_est[0]; corr_mocap[1][0] = mocap.y - y_est[0]; corr_mocap[2][0] = mocap.z - z_est[0]; mocap_updates++; } } /* vehicle GPS position */ orb_check(vehicle_gps_position_sub, &updated); if (updated) { orb_copy(ORB_ID(vehicle_gps_position), vehicle_gps_position_sub, &gps); bool reset_est = false; /* hysteresis for GPS quality */ if (gps_valid) { if (gps.eph > max_eph_epv || gps.epv > max_eph_epv || gps.fix_type < 3) { gps_valid = false; mavlink_log_info(&mavlink_log_pub, ""[inav] GPS signal lost""); warnx(""[inav] GPS signal lost""); } } else { if (gps.eph < max_eph_epv * 0.7f && gps.epv < max_eph_epv * 0.7f && gps.fix_type >= 3) { gps_valid = true; reset_est = true; mavlink_log_info(&mavlink_log_pub, ""[inav] GPS signal found""); warnx(""[inav] GPS signal found""); } } if (gps_valid) { double lat = gps.lat * 1e-7; double lon = gps.lon * 1e-7; float alt = gps.alt * 1e-3; /* initialize reference position if needed */ if (!ref_inited) { if (ref_init_start == 0) { ref_init_start = t; } else if (t > ref_init_start + ref_init_delay) { ref_inited = true; /* set position estimate to (0, 0, 0), use GPS velocity for XY */ x_est[0] = 0.0f; x_est[1] = gps.vel_n_m_s; y_est[0] = 0.0f; y_est[1] = gps.vel_e_m_s; local_pos.ref_lat = lat; local_pos.ref_lon = lon; local_pos.ref_alt = alt + z_est[0]; local_pos.ref_timestamp = t; /* initialize projection */ map_projection_init(&ref, lat, lon); // XXX replace this print warnx(""init ref: lat=%.7f, lon=%.7f, alt=%8.4f"", (double)lat, (double)lon, (double)alt); mavlink_log_info(&mavlink_log_pub, ""[inav] init ref: %.7f, %.7f, %8.4f"", (double)lat, (double)lon, (double)alt); } } if (ref_inited) { /* project GPS lat lon to plane */ float gps_proj[2]; map_projection_project(&ref, lat, lon, &(gps_proj[0]), &(gps_proj[1])); /* reset position estimate when GPS becomes good */ if (reset_est) { x_est[0] = gps_proj[0]; x_est[1] = gps.vel_n_m_s; y_est[0] = gps_proj[1]; y_est[1] = gps.vel_e_m_s; } /* calculate index of estimated values in buffer */ int est_i = buf_ptr - 1 - min(EST_BUF_SIZE - 1, max(0, (int)(params.delay_gps * 1000000.0f / PUB_INTERVAL))); if (est_i < 0) { est_i += EST_BUF_SIZE; } /* calculate correction for position */ corr_gps[0][0] = gps_proj[0] - est_buf[est_i][0][0]; corr_gps[1][0] = gps_proj[1] - est_buf[est_i][1][0]; corr_gps[2][0] = local_pos.ref_alt - alt - est_buf[est_i][2][0]; /* calculate correction for velocity */ if (gps.vel_ned_valid) { corr_gps[0][1] = gps.vel_n_m_s - est_buf[est_i][0][1]; corr_gps[1][1] = gps.vel_e_m_s - est_buf[est_i][1][1]; corr_gps[2][1] = gps.vel_d_m_s - est_buf[est_i][2][1]; } else { corr_gps[0][1] = 0.0f; corr_gps[1][1] = 0.0f; corr_gps[2][1] = 0.0f; } /* save rotation matrix at this moment */ memcpy(R_gps, R_buf[est_i], sizeof(R_gps)); w_gps_xy = min_eph_epv / fmaxf(min_eph_epv, gps.eph); w_gps_z = min_eph_epv / fmaxf(min_eph_epv, gps.epv); } } else { /* no GPS lock */ memset(corr_gps, 0, sizeof(corr_gps)); ref_init_start = 0; } gps_updates++; } } matrix::Dcm R = matrix::Quatf(att.q); /* check for timeout on FLOW topic */ if ((flow_valid || lidar_valid) && t > (flow_time + flow_topic_timeout)) { flow_valid = false; warnx(""FLOW timeout""); mavlink_log_info(&mavlink_log_pub, ""[inav] FLOW timeout""); } /* check for timeout on GPS topic */ if (gps_valid && (t > (gps.timestamp + gps_topic_timeout))) { gps_valid = false; warnx(""GPS timeout""); mavlink_log_info(&mavlink_log_pub, ""[inav] GPS timeout""); } /* check for timeout on vision topic */ if (vision_valid && (t > (vision.timestamp + vision_topic_timeout))) { vision_valid = false; warnx(""VISION timeout""); mavlink_log_info(&mavlink_log_pub, ""[inav] VISION timeout""); } /* check for timeout on mocap topic */ if (mocap_valid && (t > (mocap.timestamp + mocap_topic_timeout))) { mocap_valid = false; warnx(""MOCAP timeout""); mavlink_log_info(&mavlink_log_pub, ""[inav] MOCAP timeout""); } /* check for lidar measurement timeout */ if (lidar_valid && (t > (lidar_time + lidar_timeout))) { lidar_valid = false; warnx(""LIDAR timeout""); mavlink_log_info(&mavlink_log_pub, ""[inav] LIDAR timeout""); } float dt = t_prev > 0 ? (t - t_prev) / 1000000.0f : 0.0f; dt = fmaxf(fminf(0.02, dt), 0.0002); // constrain dt from 0.2 to 20 ms t_prev = t; /* increase EPH/EPV on each step */ if (eph < 0.000001f) { //get case where eph is 0 -> would stay 0 eph = 0.001; } if (eph < max_eph_epv) { eph *= 1.0f + dt; } if (epv < 0.000001f) { //get case where epv is 0 -> would stay 0 epv = 0.001; } if (epv < max_eph_epv) { epv += 0.005f * dt; // add 1m to EPV each 200s (baro drift) } /* use GPS if it's valid and reference position initialized */ bool use_gps_xy = ref_inited && gps_valid && params.w_xy_gps_p > MIN_VALID_W; bool use_gps_z = ref_inited && gps_valid && params.w_z_gps_p > MIN_VALID_W; /* use VISION if it's valid and has a valid weight parameter */ bool use_vision_xy = vision_valid && params.w_xy_vision_p > MIN_VALID_W; bool use_vision_z = vision_valid && params.w_z_vision_p > MIN_VALID_W; /* use MOCAP if it's valid and has a valid weight parameter */ bool use_mocap = mocap_valid && params.w_mocap_p > MIN_VALID_W && params.att_ext_hdg_m == mocap_heading; //check if external heading is mocap if (params.disable_mocap) { //disable mocap if fake gps is used use_mocap = false; } /* use flow if it's valid and (accurate or no GPS available) */ bool use_flow = flow_valid && (flow_accurate || !use_gps_xy); /* use LIDAR if it's valid and lidar altitude estimation is enabled */ use_lidar = lidar_valid && params.enable_lidar_alt_est; bool can_estimate_xy = (eph < max_eph_epv) || use_gps_xy || use_flow || use_vision_xy || use_mocap; bool dist_bottom_valid = (t < lidar_valid_time + lidar_valid_timeout); float w_xy_gps_p = params.w_xy_gps_p * w_gps_xy; float w_xy_gps_v = params.w_xy_gps_v * w_gps_xy; float w_z_gps_p = params.w_z_gps_p * w_gps_z; float w_z_gps_v = params.w_z_gps_v * w_gps_z; float w_xy_vision_p = params.w_xy_vision_p; float w_xy_vision_v = params.w_xy_vision_v; float w_z_vision_p = params.w_z_vision_p; float w_mocap_p = params.w_mocap_p; /* reduce GPS weight if optical flow is good */ if (use_flow && flow_accurate) { w_xy_gps_p *= params.w_gps_flow; w_xy_gps_v *= params.w_gps_flow; } /* baro offset correction */ if (use_gps_z) { float offs_corr = corr_gps[2][0] * w_z_gps_p * dt; baro_offset += offs_corr; corr_baro += offs_corr; } /* accelerometer bias correction for GPS (use buffered rotation matrix) */ float accel_bias_corr[3] = { 0.0f, 0.0f, 0.0f }; if (use_gps_xy) { accel_bias_corr[0] -= corr_gps[0][0] * w_xy_gps_p * w_xy_gps_p; accel_bias_corr[0] -= corr_gps[0][1] * w_xy_gps_v; accel_bias_corr[1] -= corr_gps[1][0] * w_xy_gps_p * w_xy_gps_p; accel_bias_corr[1] -= corr_gps[1][1] * w_xy_gps_v; } if (use_gps_z) { accel_bias_corr[2] -= corr_gps[2][0] * w_z_gps_p * w_z_gps_p; accel_bias_corr[2] -= corr_gps[2][1] * w_z_gps_v; } /* transform error vector from NED frame to body frame */ for (int i = 0; i < 3; i++) { float c = 0.0f; for (int j = 0; j < 3; j++) { c += R_gps[j][i] * accel_bias_corr[j]; } if (PX4_ISFINITE(c)) { acc_bias[i] += c * params.w_acc_bias * dt; } } /* accelerometer bias correction for VISION (use buffered rotation matrix) */ accel_bias_corr[0] = 0.0f; accel_bias_corr[1] = 0.0f; accel_bias_corr[2] = 0.0f; if (use_vision_xy) { accel_bias_corr[0] -= corr_vision[0][0] * w_xy_vision_p * w_xy_vision_p; accel_bias_corr[0] -= corr_vision[0][1] * w_xy_vision_v; accel_bias_corr[1] -= corr_vision[1][0] * w_xy_vision_p * w_xy_vision_p; accel_bias_corr[1] -= corr_vision[1][1] * w_xy_vision_v; } if (use_vision_z) { accel_bias_corr[2] -= corr_vision[2][0] * w_z_vision_p * w_z_vision_p; } /* accelerometer bias correction for MOCAP (use buffered rotation matrix) */ accel_bias_corr[0] = 0.0f; accel_bias_corr[1] = 0.0f; accel_bias_corr[2] = 0.0f; if (use_mocap) { accel_bias_corr[0] -= corr_mocap[0][0] * w_mocap_p * w_mocap_p; accel_bias_corr[1] -= corr_mocap[1][0] * w_mocap_p * w_mocap_p; accel_bias_corr[2] -= corr_mocap[2][0] * w_mocap_p * w_mocap_p; } /* transform error vector from NED frame to body frame */ for (int i = 0; i < 3; i++) { float c = 0.0f; for (int j = 0; j < 3; j++) { c += R(j, i) * accel_bias_corr[j]; } if (PX4_ISFINITE(c)) { acc_bias[i] += c * params.w_acc_bias * dt; } } /* accelerometer bias correction for flow and baro (assume that there is no delay) */ accel_bias_corr[0] = 0.0f; accel_bias_corr[1] = 0.0f; accel_bias_corr[2] = 0.0f; if (use_flow) { accel_bias_corr[0] -= corr_flow[0] * params.w_xy_flow; accel_bias_corr[1] -= corr_flow[1] * params.w_xy_flow; } if (use_lidar) { accel_bias_corr[2] -= corr_lidar * params.w_z_lidar * params.w_z_lidar; } else { accel_bias_corr[2] -= corr_baro * params.w_z_baro * params.w_z_baro; } /* transform error vector from NED frame to body frame */ for (int i = 0; i < 3; i++) { float c = 0.0f; for (int j = 0; j < 3; j++) { c += R(j, i) * accel_bias_corr[j]; } if (PX4_ISFINITE(c)) { acc_bias[i] += c * params.w_acc_bias * dt; } } /* inertial filter prediction for altitude */ inertial_filter_predict(dt, z_est, acc[2]); if (!(PX4_ISFINITE(z_est[0]) && PX4_ISFINITE(z_est[1]))) { write_debug_log(""BAD ESTIMATE AFTER Z PREDICTION"", dt, x_est, y_est, z_est, x_est_prev, y_est_prev, z_est_prev, acc, corr_gps, w_xy_gps_p, w_xy_gps_v, corr_mocap, w_mocap_p, corr_vision, w_xy_vision_p, w_z_vision_p, w_xy_vision_v); memcpy(z_est, z_est_prev, sizeof(z_est)); } /* inertial filter correction for altitude */ if (use_lidar) { inertial_filter_correct(corr_lidar, dt, z_est, 0, params.w_z_lidar); } else { inertial_filter_correct(corr_baro, dt, z_est, 0, params.w_z_baro); } if (use_gps_z) { epv = fminf(epv, gps.epv); inertial_filter_correct(corr_gps[2][0], dt, z_est, 0, w_z_gps_p); inertial_filter_correct(corr_gps[2][1], dt, z_est, 1, w_z_gps_v); } if (use_vision_z) { epv = fminf(epv, epv_vision); inertial_filter_correct(corr_vision[2][0], dt, z_est, 0, w_z_vision_p); } if (use_mocap) { epv = fminf(epv, epv_mocap); inertial_filter_correct(corr_mocap[2][0], dt, z_est, 0, w_mocap_p); } if (!(PX4_ISFINITE(z_est[0]) && PX4_ISFINITE(z_est[1]))) { write_debug_log(""BAD ESTIMATE AFTER Z CORRECTION"", dt, x_est, y_est, z_est, x_est_prev, y_est_prev, z_est_prev, acc, corr_gps, w_xy_gps_p, w_xy_gps_v, corr_mocap, w_mocap_p, corr_vision, w_xy_vision_p, w_z_vision_p, w_xy_vision_v); memcpy(z_est, z_est_prev, sizeof(z_est)); memset(corr_gps, 0, sizeof(corr_gps)); memset(corr_vision, 0, sizeof(corr_vision)); memset(corr_mocap, 0, sizeof(corr_mocap)); corr_baro = 0; } else { memcpy(z_est_prev, z_est, sizeof(z_est)); } if (can_estimate_xy) { /* inertial filter prediction for position */ inertial_filter_predict(dt, x_est, acc[0]); inertial_filter_predict(dt, y_est, acc[1]); if (!(PX4_ISFINITE(x_est[0]) && PX4_ISFINITE(x_est[1]) && PX4_ISFINITE(y_est[0]) && PX4_ISFINITE(y_est[1]))) { write_debug_log(""BAD ESTIMATE AFTER PREDICTION"", dt, x_est, y_est, z_est, x_est_prev, y_est_prev, z_est_prev, acc, corr_gps, w_xy_gps_p, w_xy_gps_v, corr_mocap, w_mocap_p, corr_vision, w_xy_vision_p, w_z_vision_p, w_xy_vision_v); memcpy(x_est, x_est_prev, sizeof(x_est)); memcpy(y_est, y_est_prev, sizeof(y_est)); } /* inertial filter correction for position */ if (use_flow) { eph = fminf(eph, eph_flow); inertial_filter_correct(corr_flow[0], dt, x_est, 1, params.w_xy_flow * w_flow); inertial_filter_correct(corr_flow[1], dt, y_est, 1, params.w_xy_flow * w_flow); } if (use_gps_xy) { eph = fminf(eph, gps.eph); inertial_filter_correct(corr_gps[0][0], dt, x_est, 0, w_xy_gps_p); inertial_filter_correct(corr_gps[1][0], dt, y_est, 0, w_xy_gps_p); if (gps.vel_ned_valid && t < gps.timestamp + gps_topic_timeout) { inertial_filter_correct(corr_gps[0][1], dt, x_est, 1, w_xy_gps_v); inertial_filter_correct(corr_gps[1][1], dt, y_est, 1, w_xy_gps_v); } } if (use_vision_xy) { eph = fminf(eph, eph_vision); inertial_filter_correct(corr_vision[0][0], dt, x_est, 0, w_xy_vision_p); inertial_filter_correct(corr_vision[1][0], dt, y_est, 0, w_xy_vision_p); if (w_xy_vision_v > MIN_VALID_W) { inertial_filter_correct(corr_vision[0][1], dt, x_est, 1, w_xy_vision_v); inertial_filter_correct(corr_vision[1][1], dt, y_est, 1, w_xy_vision_v); } } if (use_mocap) { eph = fminf(eph, eph_mocap); inertial_filter_correct(corr_mocap[0][0], dt, x_est, 0, w_mocap_p); inertial_filter_correct(corr_mocap[1][0], dt, y_est, 0, w_mocap_p); } if (!(PX4_ISFINITE(x_est[0]) && PX4_ISFINITE(x_est[1]) && PX4_ISFINITE(y_est[0]) && PX4_ISFINITE(y_est[1]))) { write_debug_log(""BAD ESTIMATE AFTER CORRECTION"", dt, x_est, y_est, z_est, x_est_prev, y_est_prev, z_est_prev, acc, corr_gps, w_xy_gps_p, w_xy_gps_v, corr_mocap, w_mocap_p, corr_vision, w_xy_vision_p, w_z_vision_p, w_xy_vision_v); memcpy(x_est, x_est_prev, sizeof(x_est)); memcpy(y_est, y_est_prev, sizeof(y_est)); memset(corr_gps, 0, sizeof(corr_gps)); memset(corr_vision, 0, sizeof(corr_vision)); memset(corr_mocap, 0, sizeof(corr_mocap)); memset(corr_flow, 0, sizeof(corr_flow)); } else { memcpy(x_est_prev, x_est, sizeof(x_est)); memcpy(y_est_prev, y_est, sizeof(y_est)); } } else { /* gradually reset xy velocity estimates */ inertial_filter_correct(-x_est[1], dt, x_est, 1, params.w_xy_res_v); inertial_filter_correct(-y_est[1], dt, y_est, 1, params.w_xy_res_v); } /* run terrain estimator */ terrain_estimator.predict(dt, &att, &sensor, &lidar); terrain_estimator.measurement_update(hrt_absolute_time(), &gps, &lidar, &att); if (inav_verbose_mode) { /* print updates rate */ if (t > updates_counter_start + updates_counter_len) { float updates_dt = (t - updates_counter_start) * 0.000001f; warnx( ""updates rate: accelerometer = %.1f/s, baro = %.1f/s, gps = %.1f/s, attitude = %.1f/s, flow = %.1f/s, vision = %.1f/s, mocap = %.1f/s"", (double)(accel_updates / updates_dt), (double)(baro_updates / updates_dt), (double)(gps_updates / updates_dt), (double)(attitude_updates / updates_dt), (double)(flow_updates / updates_dt), (double)(vision_updates / updates_dt), (double)(mocap_updates / updates_dt)); updates_counter_start = t; accel_updates = 0; baro_updates = 0; gps_updates = 0; attitude_updates = 0; flow_updates = 0; vision_updates = 0; mocap_updates = 0; } } if (t > pub_last + PUB_INTERVAL) { pub_last = t; /* push current estimate to buffer */ est_buf[buf_ptr][0][0] = x_est[0]; est_buf[buf_ptr][0][1] = x_est[1]; est_buf[buf_ptr][1][0] = y_est[0]; est_buf[buf_ptr][1][1] = y_est[1]; est_buf[buf_ptr][2][0] = z_est[0]; est_buf[buf_ptr][2][1] = z_est[1]; /* push current rotation matrix to buffer */ memcpy(R_buf[buf_ptr], &R._data[0][0], sizeof(R._data)); buf_ptr++; if (buf_ptr >= EST_BUF_SIZE) { buf_ptr = 0; } /* publish local position */ local_pos.xy_valid = can_estimate_xy; local_pos.v_xy_valid = can_estimate_xy; local_pos.xy_global = local_pos.xy_valid && use_gps_xy; local_pos.z_global = local_pos.z_valid && use_gps_z; local_pos.x = x_est[0]; local_pos.vx = x_est[1]; local_pos.y = y_est[0]; local_pos.vy = y_est[1]; local_pos.z = z_est[0]; local_pos.vz = z_est[1]; matrix::Eulerf euler(R); local_pos.yaw = euler.psi(); local_pos.dist_bottom_valid = dist_bottom_valid; local_pos.eph = eph; local_pos.epv = epv; // TODO provide calculated values for these local_pos.evh = 0.0f; local_pos.evv = 0.0f; // this estimator does not provide a separate vertical position time derivative estimate, so use the vertical velocity local_pos.z_deriv = z_est[1]; if (local_pos.dist_bottom_valid) { local_pos.dist_bottom = dist_ground; local_pos.dist_bottom_rate = - z_est[1]; } local_pos.timestamp = t; orb_publish(ORB_ID(vehicle_local_position), vehicle_local_position_pub, &local_pos); if (local_pos.xy_global && local_pos.z_global) { /* publish global position */ global_pos.timestamp = t; global_pos.time_utc_usec = gps.time_utc_usec; double est_lat, est_lon; map_projection_reproject(&ref, local_pos.x, local_pos.y, &est_lat, &est_lon); global_pos.lat = est_lat; global_pos.lon = est_lon; global_pos.alt = local_pos.ref_alt - local_pos.z; global_pos.vel_n = local_pos.vx; global_pos.vel_e = local_pos.vy; global_pos.vel_d = local_pos.vz; // this estimator does not provide a separate vertical position time derivative estimate, so use the vertical velocity global_pos.pos_d_deriv = local_pos.vz; global_pos.yaw = local_pos.yaw; global_pos.eph = eph; global_pos.epv = epv; // TODO provide calculated values for these global_pos.evh = 0.0f; global_pos.evv = 0.0f; if (terrain_estimator.is_valid()) { global_pos.terrain_alt = global_pos.alt - terrain_estimator.get_distance_to_ground(); global_pos.terrain_alt_valid = true; } else { global_pos.terrain_alt_valid = false; } global_pos.pressure_alt = sensor.baro_alt_meter; if (vehicle_global_position_pub == nullptr) { vehicle_global_position_pub = orb_advertise(ORB_ID(vehicle_global_position), &global_pos); } else { orb_publish(ORB_ID(vehicle_global_position), vehicle_global_position_pub, &global_pos); } } } } warnx(""stopped""); mavlink_log_info(&mavlink_log_pub, ""[inav] stopped""); thread_running = false; return 0; } int inav_parameters_init(struct position_estimator_inav_param_handles *h) { h->w_z_baro = param_find(""INAV_W_Z_BARO""); h->w_z_gps_p = param_find(""INAV_W_Z_GPS_P""); h->w_z_gps_v = param_find(""INAV_W_Z_GPS_V""); h->w_z_vision_p = param_find(""INAV_W_Z_VIS_P""); h->w_z_lidar = param_find(""INAV_W_Z_LIDAR""); h->w_xy_gps_p = param_find(""INAV_W_XY_GPS_P""); h->w_xy_gps_v = param_find(""INAV_W_XY_GPS_V""); h->w_xy_vision_p = param_find(""INAV_W_XY_VIS_P""); h->w_xy_vision_v = param_find(""INAV_W_XY_VIS_V""); h->w_mocap_p = param_find(""INAV_W_MOC_P""); h->w_xy_flow = param_find(""INAV_W_XY_FLOW""); h->w_xy_res_v = param_find(""INAV_W_XY_RES_V""); h->w_gps_flow = param_find(""INAV_W_GPS_FLOW""); h->w_acc_bias = param_find(""INAV_W_ACC_BIAS""); h->flow_k = param_find(""INAV_FLOW_K""); h->flow_q_min = param_find(""INAV_FLOW_Q_MIN""); h->lidar_err = param_find(""INAV_LIDAR_ERR""); h->land_t = param_find(""INAV_LAND_T""); h->land_disp = param_find(""INAV_LAND_DISP""); h->land_thr = param_find(""INAV_LAND_THR""); h->no_vision = param_find(""CBRK_NO_VISION""); h->delay_gps = param_find(""INAV_DELAY_GPS""); h->flow_module_offset_x = param_find(""INAV_FLOW_DIST_X""); h->flow_module_offset_y = param_find(""INAV_FLOW_DIST_Y""); h->disable_mocap = param_find(""INAV_DISAB_MOCAP""); h->enable_lidar_alt_est = param_find(""INAV_LIDAR_EST""); h->lidar_calibration_offset = param_find(""INAV_LIDAR_OFF""); h->att_ext_hdg_m = param_find(""ATT_EXT_HDG_M""); return 0; } int inav_parameters_update(const struct position_estimator_inav_param_handles *h, struct position_estimator_inav_params *p) { param_get(h->w_z_baro, &(p->w_z_baro)); param_get(h->w_z_gps_p, &(p->w_z_gps_p)); param_get(h->w_z_gps_v, &(p->w_z_gps_v)); param_get(h->w_z_vision_p, &(p->w_z_vision_p)); param_get(h->w_z_lidar, &(p->w_z_lidar)); param_get(h->w_xy_gps_p, &(p->w_xy_gps_p)); param_get(h->w_xy_gps_v, &(p->w_xy_gps_v)); param_get(h->w_xy_vision_p, &(p->w_xy_vision_p)); param_get(h->w_xy_vision_v, &(p->w_xy_vision_v)); param_get(h->w_mocap_p, &(p->w_mocap_p)); param_get(h->w_xy_flow, &(p->w_xy_flow)); param_get(h->w_xy_res_v, &(p->w_xy_res_v)); param_get(h->w_gps_flow, &(p->w_gps_flow)); param_get(h->w_acc_bias, &(p->w_acc_bias)); param_get(h->flow_k, &(p->flow_k)); param_get(h->flow_q_min, &(p->flow_q_min)); param_get(h->lidar_err, &(p->lidar_err)); param_get(h->land_t, &(p->land_t)); param_get(h->land_disp, &(p->land_disp)); param_get(h->land_thr, &(p->land_thr)); param_get(h->no_vision, &(p->no_vision)); param_get(h->delay_gps, &(p->delay_gps)); param_get(h->flow_module_offset_x, &(p->flow_module_offset_x)); param_get(h->flow_module_offset_y, &(p->flow_module_offset_y)); param_get(h->disable_mocap, &(p->disable_mocap)); param_get(h->enable_lidar_alt_est, &(p->enable_lidar_alt_est)); param_get(h->lidar_calibration_offset, &(p->lidar_calibration_offset)); param_get(h->att_ext_hdg_m, &(p->att_ext_hdg_m)); return 0; } ",16187,True,3193.856012271936,median ".//============================================================================ .// $RCSfile: q.class.pei.arc,v $ .// .// Description: .// This archetype file contains the functions for generating .// preexisting instances initialization code. .// .// Notice: .// (C) Copyright 1998-2013 Mentor Graphics Corporation .// All rights reserved. .// .// This document contains confidential and proprietary information and .// property of Mentor Graphics Corp. No part of this document may be .// reproduced without the express written permission of Mentor Graphics Corp. .//============================================================================ .// .// .//============================================================================ .// Initialize the instance subsystem. .// Update the instance and link records with array index values .// and container counts. .// The mapping of the instances to a particular array index is .// arbitrary. .//============================================================================ .function PEIInstanceSubsystemInit .param inst_ref_set o_objs .// .for each o_obj in o_objs .select many i_inss related by o_obj->CSME_CIE[R2961]->I_INS[R2962] .// Check for preexisting instance population requirement. .// The class must have instances and also be colored. .assign i = cardinality i_inss .select one te_class related by o_obj->TE_CLASS[R2019] .if ( ( i > 0 ) and ( te_class.PEIsDefinedInData ) ) .assign te_class.PEIsDefinedInData = TRUE .else .assign te_class.PEIsDefinedInData = FALSE .end if .// .assign i = 0 .for each i_ins in i_inss .assign i_ins.Name = ""${i}"" .assign i = i + 1 .end for .end for .end function .// .// .//============================================================================ .// Count the preexisting instances of the given type. .// Return the number of preexisting instances for obj. .//============================================================================ .function PEINumberOfPreexistingInstances .param inst_ref o_obj .select many i_inss related by o_obj->CSME_CIE[R2961]->I_INS[R2962] .assign attr_result = cardinality i_inss .// .assign msg = ""PEINumberOfPreexistingInstances is ${attr_result} "" .// .assign msg = msg + ""for ${o_obj.Name} (${o_obj.Key_Lett})"" .// .print ""${msg}"" .end function .// .// .//============================================================================= .// Generate initializers for preexisting instances. .// We generate the initializers in array index order. C initializers .// will assume sequential ordering. .//============================================================================= .function PEIRenderInitializers .param inst_ref o_obj .assign attr_assset = """" .select any te_set from instances of TE_SET .select one te_class related by o_obj->TE_CLASS[R2019] .if ( te_class.PEIsDefinedInData ) .assign inst_count = 0 .select many i_inss related by o_obj->CSME_CIE[R2961]->I_INS[R2962] .assign i_inss_cardinality = cardinality i_inss .while ( inst_count < i_inss_cardinality ) .for each i_ins in i_inss .if ( i_ins.Name == ""$t{inst_count}"" ) .invoke initializercode = PEIRenderInitializerBody( i_ins, o_obj ) .assign attr_assset = attr_assset + initializercode.assset { ${initializercode.result} }\\ .if ( last i_inss ) .else , .end if .break for .end if .end for .assign inst_count = inst_count + 1 .end while .// inst_count .// If there is a need for relationship set containers, build them up. .if ( attr_assset != """" ) .invoke rel_set_name = PEIGetRelationshipSetContainerName( te_class ) .assign attr_assset = ""static ${te_set.element_type} ${rel_set_name.result}[] = {\\n"" + attr_assset .assign attr_assset = ""/* PEI relationship set containers. */\\n"" + attr_assset .assign attr_assset = attr_assset + ""\\n};\\n"" .end if .end if .end function .// .// .//============================================================================= .// Generate body of one preexisting instance initializer. .// First, the initial state initializer is output. .// The class instance attribute data variable values are generated .// in the same order in which they appear in the application analysis OIM. .// The relationship optimization initializers are then generated. .//============================================================================= .function PEIRenderInitializerBody .param inst_ref i_ins .param inst_ref o_obj .assign attr_result = """" .assign attr_assset = """" .// .// Generate state machine state (if needed). .// .invoke cs_init = PEIRenderInitializerBodyCurrentState( i_ins, o_obj ) .assign attr_result = attr_result + cs_init.result .if ( """" != attr_result ) .assign attr_result = attr_result + "", "" .end if .// .// Generate the attribute value initializers. .// .select any te_attr related by o_obj->TE_CLASS[R2019]-TE_ATTR[R2061] where ( selected.prevID == 0 ) .if ( not_empty te_attr ) .select one o_attr related by te_attr->O_ATTR[R2033] .while ( not_empty te_attr ) .if ( te_attr.translate ) .select any i_avl related by i_ins->I_AVL[R2909] where ( selected.Attr_ID == o_attr.Attr_ID ) .invoke avlcode = PEIRenderInitializerBodyAttribute( o_attr, i_avl ) .assign attr_result = attr_result + avlcode.result .end if .// .// Advance to the next object attribute, if any. .select one te_attr related by te_attr->TE_ATTR[R2087.'succeeds'] .// .// Generate comma separator. .if ( not_empty te_attr ) .if ( te_attr.translate ) .assign attr_result = attr_result + "", "" .end if .end if .end while .end if .// .// Generate the association linkage (if needed). .// .invoke ass_init = PEIRenderInitializerBodyAssociation( i_ins, o_obj ) .assign attr_result = attr_result + ass_init.result .assign attr_assset = attr_assset + ass_init.assset .// .end function .// .// .//============================================================================= .// Generate initialization for a single attribute value. .// Return the value as a string quoted correctly (if needed). .//============================================================================= .function PEIRenderInitializerBodyAttribute .param inst_ref o_attr .param inst_ref i_avl .assign attr_result = ""0"" .// Get the attribute data type. Strings need to be quoted. .invoke r = GetAttributeCodeGenType( o_attr ) .assign te_dt = r.result .if ( 4 == te_dt.Core_Typ ) .// string .if ( empty i_avl ) .// In absence of a populated attribute, use the attribute default value. .if ( """" != o_attr.DefaultValue ) .assign attr_result = o_attr.DefaultValue .else .assign attr_result = """""""""""" .end if .else .assign attr_result = """"""${i_avl.Value}"""""" .end if .else .if ( empty i_avl ) .assign attr_result = ""0"" .else .assign attr_result = i_avl.Value .end if .end if .end function .// .// .//============================================================================= .// Generate the optimized association linkage for this instance. .// Select the relationship set for this object. Loop through each one .// generating linkage anywhere storage is provided (for pointer refs). .// Get the multiplicity so we know whether we need sets or simple .// pointers. .// Do the right thing for each flavor of association, simple, reflexive, .// associative and sub/super. .// Return the static initializer body material. .//============================================================================= .function PEIRenderInitializerBodyAssociation .param inst_ref i_ins .param inst_ref o_obj .// .assign multiplicity = 0 .assign attr_assset = """" .assign attr_result = """" .select many te_rels related by o_obj->R_OIR[R201]->R_REL[R201]->TE_REL[R2034] .if ( not_empty te_rels ) .// Pre-order the relationships ascending by their relationship number. .// Note: This decouples code generation from SQL table .// insertion ordering internals. .invoke SortSetAscendingByAttr_Numb( te_rels ) .assign rel_count = 0 .assign rel_cardinality = cardinality te_rels .// .while ( rel_count < rel_cardinality ) .for each te_rel in te_rels .if ( te_rel.Order == rel_count ) .select one rel related by te_rel->R_REL[R2034] .if ( not te_rel.storage_needed ) .break for .end if .// Simple relationship? .select one simple_rel related by rel->R_SIMP[R206] .if ( not_empty simple_rel ) .select one participant related by simple_rel->R_PART[R207] .select one formalizer related by simple_rel->R_FORM[R208] .if ( empty formalizer ) .print ""\\n\\tRelationship R${rel.Numb} is not formalized!\\n"" .exit 101 .end if .// Deal with reflexives. .if ( participant.Obj_ID == formalizer.Obj_ID ) .invoke s = PEIRelInitSimpleReflexive( i_ins, o_obj, rel, participant, formalizer ) .assign attr_result = attr_result + s.result .assign attr_assset = attr_assset + s.assset .else .// Get multiplicity to pass to the code generator. .if ( o_obj.Obj_ID == participant.Obj_ID ) .assign multiplicity = formalizer.Mult .else .assign multiplicity = participant.Mult .end if .invoke s = PEIRelInitSimple( i_ins, o_obj, rel, multiplicity ) .assign attr_result = attr_result + s.result .assign attr_assset = attr_assset + s.assset .end if .// reflexive .else .// elif Subtype-Supertype relationship? .select one r_subsup related by rel->R_SUBSUP[R206] .if ( not_empty r_subsup ) .invoke s = PEIRelInitSubSuper( i_ins, o_obj, rel, r_subsup ) .assign attr_result = attr_result + s.result .else .// elif Associative relationship? .select one assrel related by rel->R_ASSOC[R206] .if ( not_empty assrel ) .invoke s = PEIRelInitAssociative( i_ins, o_obj, rel, assrel ) .assign attr_result = attr_result + s.result .assign attr_assset = attr_assset + s.assset .else .// elif Composed relationship? .select one composed_rel related by rel->R_COMP[R206] .if ( not_empty composed_rel ) .print ""\\nWARNING: R${rel.Numb} is COMPOSITION - No code generated.\\n"" .invoke s = PEIRelInitComposed( o_obj, rel ) .assign attr_result = attr_result + s.result .else .// elif Error: New subtype of R_REL or a corrupted model SQL... .print ""ERROR: Unknown association type:R${rel.Numb} for class '${o_obj.Name}' (${o_obj.Key_Lett})"" .exit 101 .end if .// not_empty composed_rel .end if .// not_empty associative_rel .end if .// not_empty subtype_supertype_rel .end if .// not_empty simp_rel .break for .end if .end for .assign rel_count = rel_count + 1 .end while .// rel_count < rel_cardinality .end if .// not_empty rel_set .end function .// .// .//============================================================================= .// Generate the optimized relationship linkage for a simple association. .// of multiplicity ONE. .//============================================================================= .function PEIRelInitSimple .param inst_ref i_ins .param inst_ref o_obj .param inst_ref r_rel .param integer multiplicity .// .assign attr_result = """" .assign attr_assset = """" .select any related_i_ins from instances of I_INS .// .// Find related instance index. .// Traverse the instance to link to instance chain .// to get the instance ArrayIndex. .if ( multiplicity == 0 ) .// ONE .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .select one related_i_ins related by i_lnk->I_LIP[R2901]->I_INS[R2958] .if ( empty related_i_ins ) .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .select one related_i_ins related by i_lnk->I_LIP[R2902]->I_INS[R2958] .end if .if ( not_empty related_i_ins ) .select one related_o_obj related by related_i_ins->CSME_CIE[R2962]->O_OBJ[R2961] .select one related_te_class related by related_o_obj->TE_CLASS[R2019] .assign attr_result = "", &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}]"" .else .// not participating .assign attr_result = "", 0"" .end if .// not empty .else .// MANY .// Build linked list of containers pointing to related instances. .select many i_lnks related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .select many related1_i_ins related by i_lnks->I_LIP[R2901]->I_INS[R2958] .select many i_lnks related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .select many related2_i_inss related by i_lnks->I_LIP[R2902]->I_INS[R2958] .assign related_i_inss = related1_i_ins | related2_i_inss .invoke s = PEIRenderRelationshipManyOptimization( related_i_inss, o_obj ) .assign attr_result = attr_result + s.result .assign attr_assset = attr_assset + s.assset .end if .// .end function .// .// .//============================================================================= .// Generate the optimized relationship linkage for a simple reflexive .// association. .// In the reflexive case, the part and form are aligned with R2901 and R2902. .//============================================================================= .function PEIRelInitSimpleReflexive .param inst_ref i_ins .param inst_ref o_obj .param inst_ref r_rel .param inst_ref r_part .param inst_ref r_form .// .assign attr_result = """" .assign attr_assset = """" .select one related_te_class related by o_obj->TE_CLASS[R2019] .select any related_i_ins from instances of I_INS .// .// Link the formalizer to the participant. .// .if ( r_part.Mult == 0 ) .// ONE .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .select one related_i_ins related by i_lnk->I_LIP[R2901]->I_INS[R2958] .if ( not_empty related_i_ins ) .assign attr_result = attr_result + "", &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}]"" .else .// Not participating. .assign attr_result = attr_result + "", 0"" .end if .else .// MANY .// Build linked list of containers pointing to related instances. .select many i_lnks related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .select many related_i_inss related by i_lnks->I_LIP[R2901]->I_INS[R2958] .invoke s = PEIRenderRelationshipManyOptimization( related_i_inss, o_obj ) .assign attr_result = attr_result + s.result .assign attr_assset = attr_assset + s.assset .end if .// .// Now link the participant to the formalizer(s). .// .if ( r_form.Mult == 0 ) .// ONE .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .select one related_i_ins related by i_lnk->I_LIP[R2902]->I_INS[R2958] .if ( not_empty related_i_ins ) .assign attr_result = attr_result + "", &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}]"" .else .// Not participating. .assign attr_result = attr_result + "", 0"" .end if .else .// MANY .// Build linked list of containers pointing to related instances. .select many i_lnks related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .select many related_i_inss related by i_lnks->I_LIP[R2902]->I_INS[R2958] .invoke s = PEIRenderRelationshipManyOptimization( related_i_inss, o_obj ) .assign attr_result = attr_result + s.result .assign attr_assset = attr_assset + s.assset .end if .// .end function .// .// .//============================================================================= .// Generate the optimized relationship linkage for an associative .// relationship. .// In the reflexive case, R2901 and R2902 will jive with AONE and AOTH. .// In the non-reflexive, we compare the instance Obj_ID with the .// AONE/AOTH Obj_ID. .//============================================================================= .function PEIRelInitAssociative .param inst_ref i_ins .param inst_ref o_obj .param inst_ref r_rel .param inst_ref r_assoc .// .assign attr_result = """" .assign attr_assset = """" .select one aone related by r_assoc->R_AONE[R209] .select one aoth related by r_assoc->R_AOTH[R210] .select one assr related by r_assoc->R_ASSR[R211] .// .// The other associated instance. .// .if ( o_obj.Obj_ID == aoth.Obj_ID ) .// Optimize relationship to associator. .if ( ( aone.Mult == 0 ) and ( assr.Mult == 0 ) ) .// ONE .select any i_lnk from instances of I_LNK where ( false ) .if ( aone.Obj_ID == aoth.Obj_ID ) .// reflexive .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .else .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .if ( empty i_lnk ) .select one related_o_obj related by i_ins->CSME_CIE[R2962]->O_OBJ[R2961] .if ( related_o_obj.Obj_ID == aoth.Obj_ID ) .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .end if .end if .// not empty .end if .// reflexive .if ( not_empty i_lnk ) .select one related_i_ins related by i_lnk->I_LIP[R2903]->I_INS[R2958] .select one related_o_obj related by related_i_ins->CSME_CIE[R2962]->O_OBJ[R2961] .select one related_te_class related by related_o_obj->TE_CLASS[R2019] .assign attr_result = attr_result + "", &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}]"" .else .// not participating .assign attr_result = attr_result + "", 0"" .end if .// not empty .else .// MANY .// Build linked list of containers pointing to related instances. .select many i_lnks from instances of I_LNK where ( false ) .select many related_i_inss from instances of I_INS where ( false ) .if ( aone.Obj_ID == aoth.Obj_ID ) .// reflexive .select many i_lnks related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .else .select many one_i_lnks related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .select many two_i_lnks related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .assign i_lnks = one_i_lnks | two_i_lnks .end if .select many related_i_inss related by i_lnks->I_LIP[R2903]->I_INS[R2958] .invoke s = PEIRenderRelationshipManyOptimization( related_i_inss, o_obj ) .assign attr_result = attr_result + s.result .assign attr_assset = attr_assset + s.assset .end if .end if .// .// The one associated instance. .// .if ( o_obj.Obj_ID == aone.Obj_ID ) .// Optimize relationship to associator. .if ( ( aoth.Mult == 0 ) and ( assr.Mult == 0 ) ) .// ONE .select any i_lnk from instances of I_LNK where ( false ) .if ( aone.Obj_ID == aoth.Obj_ID ) .// reflexive .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .else .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .if ( empty i_lnk ) .select one related_o_obj related by i_ins->CSME_CIE[R2962]->O_OBJ[R2961] .if ( related_o_obj.Obj_ID == aone.Obj_ID ) .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .end if .end if .end if .// reflexive .if ( not_empty i_lnk ) .select one related_i_ins related by i_lnk->I_LIP[R2903]->I_INS[R2958] .select one related_o_obj related by related_i_ins->CSME_CIE[R2962]->O_OBJ[R2961] .select one related_te_class related by related_o_obj->TE_CLASS[R2019] .assign attr_result = attr_result + "", &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}]"" .else .// not participating .assign attr_result = attr_result + "", 0"" .end if .// not empty .else .// MANY .// Build linked list of containers pointing to related instances. .select many i_lnks from instances of I_LNK where ( false ) .select many related_i_inss from instances of I_INS where ( false ) .if ( aone.Obj_ID == aoth.Obj_ID ) .select many i_lnks related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .else .select many one_i_lnks related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .select many two_i_lnks related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .assign i_lnks = one_i_lnks | two_i_lnks .end if .select many related_i_inss related by i_lnks->I_LIP[R2903]->I_INS[R2958] .invoke s = PEIRenderRelationshipManyOptimization( related_i_inss, o_obj ) .assign attr_result = attr_result + s.result .assign attr_assset = attr_assset + s.assset .end if .end if .// .// The associative instance. .// .if ( o_obj.Obj_ID == assr.Obj_ID ) .// Optimize relationship to both associates. .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2903] where ( selected.Rel_ID == r_rel.Rel_ID ) .if ( not_empty i_lnk ) .select one related_i_ins related by i_lnk->I_LIP[R2901]->I_INS[R2958] .select one related_o_obj related by related_i_ins->CSME_CIE[R2962]->O_OBJ[R2961] .select one related_te_class related by related_o_obj->TE_CLASS[R2019] .select one related2_i_ins related by i_lnk->I_LIP[R2902]->I_INS[R2958] .select one related2_o_obj related by related2_i_ins->CSME_CIE[R2962]->O_OBJ[R2961] .select one related2_te_class related by related2_o_obj->TE_CLASS[R2019] .if ( ( aone.Obj_ID == aoth.Obj_ID ) or ( related2_o_obj.Obj_ID == aone.Obj_ID ) ) .assign attr_result = attr_result + "", &${related2_te_class.GeneratedName}_instances[${related2_i_ins.Name}]"" .assign attr_result = attr_result + "", &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}]"" .else .assign attr_result = attr_result + "", &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}]"" .assign attr_result = attr_result + "", &${related2_te_class.GeneratedName}_instances[${related2_i_ins.Name}]"" .end if .else .// not participating .assign attr_result = attr_result + "", 0, 0"" .end if .// not empty .end if .end function .// .// .//============================================================================= .// Generate the optimized relationship linkage for a Subtype/Supertype .// association. .//============================================================================= .function PEIRelInitSubSuper .param inst_ref i_ins .param inst_ref o_obj .param inst_ref r_rel .param inst_ref r_subsup .assign attr_result = """" .// .// Find related instance index. .// Traverse the instance to link to instance chain .// to get the instance ArrayIndex. .select one super related by r_subsup->R_SUPER[R212] .if ( o_obj.Obj_ID == super.Obj_ID ) .// Supertype .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .select one related_i_ins related by i_lnk->I_LIP[R2902]->I_INS[R2958] .if ( empty i_lnk ) .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .select one related_i_ins related by i_lnk->I_LIP[R2901]->I_INS[R2958] .end if .if ( not_empty i_lnk ) .select one related_o_obj related by related_i_ins->CSME_CIE[R2962]->O_OBJ[R2961] .select one related_te_class related by related_o_obj->TE_CLASS[R2019] .assign attr_result = "", (void *) &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}], ${related_te_class.system_class_number}"" .else .// not participating .assign attr_result = "", 0, 0"" .end if .else .// Subtype .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .if ( not_empty i_lnk ) .select one related_i_ins related by i_lnk->I_LIP[R2901]->I_INS[R2958] .select one related_o_obj related by related_i_ins->CSME_CIE[R2962]->O_OBJ[R2961] .select one related_te_class related by related_o_obj->TE_CLASS[R2019] .assign attr_result = "", &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}]"" .else .// not participating .assign attr_result = "", 0"" .end if .end if .end function .// .// .//============================================================================= .// Generate the optimized relationship linkage for a composed association. .//============================================================================= .function PEIRelInitComposed .param inst_ref o_obj .param inst_ref r_rel .assign attr_result = """" .end function .// .// .//============================================================================= .// Generate an initializer for the current state attribute if needed. .//============================================================================= .function PEIRenderInitializerBodyCurrentState .param inst_ref i_ins .param inst_ref o_obj .assign attr_result = """" .select one te_state related by i_ins->SM_STATE[R2915]->TE_STATE[R2037] .if ( not_empty te_state ) .assign attr_result = te_state.enumerator .end if .end function .// .// .//============================================================================= .// Render relationship MANY optimization. .// This helper is used to render the code used to optimize a relationship .// set. The set variable is generated for inside the instance structure. .// The linked list body pointing to related instances is also generated. .//============================================================================= .function PEIRenderRelationshipManyOptimization .param inst_ref_set i_inss .param inst_ref o_obj .// .assign attr_result = """" .assign attr_assset = """" .select any te_sys from instances of TE_SYS .// i_inss, o_obj .assign instance_count = cardinality i_inss .if ( instance_count > 0 ) .select one te_class related by o_obj->TE_CLASS[R2019] .assign ContainerIndex = te_class.ContainerIndex .// A container index starting greater than zero means we are not the .// first (instance) to be adding linked lists. Precede with comma. .if ( ContainerIndex > 0 ) .assign attr_assset = "",\\n"" .end if .invoke rel_set_name = PEIGetRelationshipSetContainerName( te_class ) .assign attr_result = "", { &${rel_set_name.result}[${ContainerIndex}] }"" .for each related_i_ins in i_inss .assign ContainerIndex = ContainerIndex + 1 .select one related_o_obj related by related_i_ins->CSME_CIE[R2962]->O_OBJ[R2961] .select one related_te_class related by related_o_obj->TE_CLASS[R2019] .if ( last i_inss ) .if ( te_sys.CollectionsFlavor == 20 ) .assign icount = cardinality i_inss .if ( icount > 1 ) .assign attr_assset = attr_assset + "" { 0, (void *) &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}], &${rel_set_name.result}[${ContainerIndex} - 2] }"" .else .assign attr_assset = attr_assset + "" { 0, (void *) &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}], 0 }"" .end if .// cardinality i_inss > 1 .else .assign attr_assset = attr_assset + "" { 0, (void *) &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}] }"" .end if .elif ( first i_inss ) .if ( te_sys.CollectionsFlavor == 20 ) .assign attr_assset = attr_assset + "" { &${rel_set_name.result}[${ContainerIndex}], (void *) &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}], 0 },\\n"" .else .assign attr_assset = attr_assset + "" { &${rel_set_name.result}[${ContainerIndex}], (void *) &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}] },\\n"" .end if .else .if ( te_sys.CollectionsFlavor == 20 ) .assign attr_assset = attr_assset + "" { &${rel_set_name.result}[${ContainerIndex}], (void *) &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}], &${rel_set_name.result}[${ContainerIndex} - 2] },\\n"" .else .assign attr_assset = attr_assset + "" { &${rel_set_name.result}[${ContainerIndex}], (void *) &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}] },\\n"" .end if .end if .end for .assign te_class.ContainerIndex = ContainerIndex .else .// Empty relationship set. .assign attr_result = "", { 0 }"" .end if .end function .// ",8154,False,1926.3238428754262,median "[[features.testing]] == Testing Spring Boot provides a number of utilities and annotations to help when testing your application. Test support is provided by two modules: `spring-boot-test` contains core items, and `spring-boot-test-autoconfigure` supports auto-configuration for tests. Most developers use the `spring-boot-starter-test` ""`Starter`"", which imports both Spring Boot test modules as well as JUnit Jupiter, AssertJ, Hamcrest, and a number of other useful libraries. [TIP] ==== If you have tests that use JUnit 4, JUnit 5's vintage engine can be used to run them. To use the vintage engine, add a dependency on `junit-vintage-engine`, as shown in the following example: [source,xml,indent=0,subs=""verbatim""] ---- org.junit.vintage junit-vintage-engine test org.hamcrest hamcrest-core ---- ==== `hamcrest-core` is excluded in favor of `org.hamcrest:hamcrest` that is part of `spring-boot-starter-test`. [[features.testing.test-scope-dependencies]] === Test Scope Dependencies The `spring-boot-starter-test` ""`Starter`"" (in the `test` `scope`) contains the following provided libraries: * https://junit.org/junit5/[JUnit 5]: The de-facto standard for unit testing Java applications. * {spring-framework-docs}/testing.html#integration-testing[Spring Test] & Spring Boot Test: Utilities and integration test support for Spring Boot applications. * https://assertj.github.io/doc/[AssertJ]: A fluent assertion library. * https://github.com/hamcrest/JavaHamcrest[Hamcrest]: A library of matcher objects (also known as constraints or predicates). * https://site.mockito.org/[Mockito]: A Java mocking framework. * https://github.com/skyscreamer/JSONassert[JSONassert]: An assertion library for JSON. * https://github.com/jayway/JsonPath[JsonPath]: XPath for JSON. We generally find these common libraries to be useful when writing tests. If these libraries do not suit your needs, you can add additional test dependencies of your own. [[features.testing.spring-applications]] === Testing Spring Applications One of the major advantages of dependency injection is that it should make your code easier to unit test. You can instantiate objects by using the `new` operator without even involving Spring. You can also use _mock objects_ instead of real dependencies. Often, you need to move beyond unit testing and start integration testing (with a Spring `ApplicationContext`). It is useful to be able to perform integration testing without requiring deployment of your application or needing to connect to other infrastructure. The Spring Framework includes a dedicated test module for such integration testing. You can declare a dependency directly to `org.springframework:spring-test` or use the `spring-boot-starter-test` ""`Starter`"" to pull it in transitively. If you have not used the `spring-test` module before, you should start by reading the {spring-framework-docs}/testing.html#testing[relevant section] of the Spring Framework reference documentation. [[features.testing.spring-boot-applications]] === Testing Spring Boot Applications A Spring Boot application is a Spring `ApplicationContext`, so nothing very special has to be done to test it beyond what you would normally do with a vanilla Spring context. NOTE: External properties, logging, and other features of Spring Boot are installed in the context by default only if you use `SpringApplication` to create it. Spring Boot provides a `@SpringBootTest` annotation, which can be used as an alternative to the standard `spring-test` `@ContextConfiguration` annotation when you need Spring Boot features. The annotation works by <>. In addition to `@SpringBootTest` a number of other annotations are also provided for <> of an application. TIP: If you are using JUnit 4, don't forget to also add `@RunWith(SpringRunner.class)` to your test, otherwise the annotations will be ignored. If you are using JUnit 5, there's no need to add the equivalent `@ExtendWith(SpringExtension.class)` as `@SpringBootTest` and the other `@...Test` annotations are already annotated with it. By default, `@SpringBootTest` will not start a server. You can use the `webEnvironment` attribute of `@SpringBootTest` to further refine how your tests run: * `MOCK`(Default) : Loads a web `ApplicationContext` and provides a mock web environment. Embedded servers are not started when using this annotation. If a web environment is not available on your classpath, this mode transparently falls back to creating a regular non-web `ApplicationContext`. It can be used in conjunction with <> for mock-based testing of your web application. * `RANDOM_PORT`: Loads a `WebServerApplicationContext` and provides a real web environment. Embedded servers are started and listen on a random port. * `DEFINED_PORT`: Loads a `WebServerApplicationContext` and provides a real web environment. Embedded servers are started and listen on a defined port (from your `application.properties`) or on the default port of `8080`. * `NONE`: Loads an `ApplicationContext` by using `SpringApplication` but does not provide _any_ web environment (mock or otherwise). NOTE: If your test is `@Transactional`, it rolls back the transaction at the end of each test method by default. However, as using this arrangement with either `RANDOM_PORT` or `DEFINED_PORT` implicitly provides a real servlet environment, the HTTP client and server run in separate threads and, thus, in separate transactions. Any transaction initiated on the server does not roll back in this case. NOTE: `@SpringBootTest` with `webEnvironment = WebEnvironment.RANDOM_PORT` will also start the management server on a separate random port if your application uses a different port for the management server. [[features.testing.spring-boot-applications.detecting-web-app-type]] ==== Detecting Web Application Type If Spring MVC is available, a regular MVC-based application context is configured. If you have only Spring WebFlux, we'll detect that and configure a WebFlux-based application context instead. If both are present, Spring MVC takes precedence. If you want to test a reactive web application in this scenario, you must set the configprop:spring.main.web-application-type[] property: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/detectingwebapptype/MyWebFluxTests.java[] ---- [[features.testing.spring-boot-applications.detecting-configuration]] ==== Detecting Test Configuration If you are familiar with the Spring Test Framework, you may be used to using `@ContextConfiguration(classes=...)` in order to specify which Spring `@Configuration` to load. Alternatively, you might have often used nested `@Configuration` classes within your test. When testing Spring Boot applications, this is often not required. Spring Boot's `@*Test` annotations search for your primary configuration automatically whenever you do not explicitly define one. The search algorithm works up from the package that contains the test until it finds a class annotated with `@SpringBootApplication` or `@SpringBootConfiguration`. As long as you <> in a sensible way, your main configuration is usually found. [NOTE] ==== If you use a <>, you should avoid adding configuration settings that are specific to a particular area on the <>. The underlying component scan configuration of `@SpringBootApplication` defines exclude filters that are used to make sure slicing works as expected. If you are using an explicit `@ComponentScan` directive on your `@SpringBootApplication`-annotated class, be aware that those filters will be disabled. If you are using slicing, you should define them again. ==== If you want to customize the primary configuration, you can use a nested `@TestConfiguration` class. Unlike a nested `@Configuration` class, which would be used instead of your application's primary configuration, a nested `@TestConfiguration` class is used in addition to your application's primary configuration. NOTE: Spring's test framework caches application contexts between tests. Therefore, as long as your tests share the same configuration (no matter how it is discovered), the potentially time-consuming process of loading the context happens only once. [[features.testing.spring-boot-applications.excluding-configuration]] ==== Excluding Test Configuration If your application uses component scanning (for example, if you use `@SpringBootApplication` or `@ComponentScan`), you may find top-level configuration classes that you created only for specific tests accidentally get picked up everywhere. As we <>, `@TestConfiguration` can be used on an inner class of a test to customize the primary configuration. When placed on a top-level class, `@TestConfiguration` indicates that classes in `src/test/java` should not be picked up by scanning. You can then import that class explicitly where it is required, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/excludingconfiguration/MyTests.java[] ---- NOTE: If you directly use `@ComponentScan` (that is, not through `@SpringBootApplication`) you need to register the `TypeExcludeFilter` with it. See {spring-boot-module-api}/context/TypeExcludeFilter.html[the Javadoc] for details. [[features.testing.spring-boot-applications.using-application-arguments]] ==== Using Application Arguments If your application expects <>, you can have `@SpringBootTest` inject them using the `args` attribute. [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/usingapplicationarguments/MyApplicationArgumentTests.java[] ---- [[features.testing.spring-boot-applications.with-mock-environment]] ==== Testing with a mock environment By default, `@SpringBootTest` does not start the server. If you have web endpoints that you want to test against this mock environment, you can additionally configure {spring-framework-docs}/testing.html#spring-mvc-test-framework[`MockMvc`] as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/withmockenvironment/MyMockMvcTests.java[] ---- TIP: If you want to focus only on the web layer and not start a complete `ApplicationContext`, consider <>. Alternatively, you can configure a {spring-framework-docs}/testing.html#webtestclient-tests[`WebTestClient`] as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/withmockenvironment/MyMockWebTestClientTests.java[] ---- [TIP] ==== Testing within a mocked environment is usually faster than running with a full Servlet container. However, since mocking occurs at the Spring MVC layer, code that relies on lower-level Servlet container behavior cannot be directly tested with MockMvc. For example, Spring Boot's error handling is based on the ""`error page`"" support provided by the Servlet container. This means that, whilst you can test your MVC layer throws and handles exceptions as expected, you cannot directly test that a specific <> is rendered. If you need to test these lower-level concerns, you can start a fully running server as described in the next section. ==== [[features.testing.spring-boot-applications.with-running-server]] ==== Testing with a running server If you need to start a full running server, we recommend that you use random ports. If you use `@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)`, an available port is picked at random each time your test runs. The `@LocalServerPort` annotation can be used to <> into your test. For convenience, tests that need to make REST calls to the started server can additionally `@Autowire` a {spring-framework-docs}/testing.html#webtestclient-tests[`WebTestClient`], which resolves relative links to the running server and comes with a dedicated API for verifying responses, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/withrunningserver/MyRandomPortWebTestClientTests.java[] ---- This setup requires `spring-webflux` on the classpath. If you can't or won't add webflux, Spring Boot also provides a `TestRestTemplate` facility: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/withrunningserver/MyRandomPortTestRestTemplateTests.java[] ---- [[features.testing.spring-boot-applications.customizing-web-test-client]] ==== Customizing WebTestClient To customize the `WebTestClient` bean, configure a `WebTestClientBuilderCustomizer` bean. Any such beans are called with the `WebTestClient.Builder` that is used to create the `WebTestClient`. [[features.testing.spring-boot-applications.jmx]] ==== Using JMX As the test context framework caches context, JMX is disabled by default to prevent identical components to register on the same domain. If such test needs access to an `MBeanServer`, consider marking it dirty as well: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/jmx/MyJmxTests.java[] ---- [[features.testing.spring-boot-applications.metrics]] ==== Using Metrics Regardless of your classpath, meter registries, except the in-memory backed, are not auto-configured when using `@SpringBootTest`. If you need to export metrics to a different backend as part of an integration test, annotate it with `@AutoConfigureMetrics`. [[features.testing.spring-boot-applications.mocking-beans]] ==== Mocking and Spying Beans When running tests, it is sometimes necessary to mock certain components within your application context. For example, you may have a facade over some remote service that is unavailable during development. Mocking can also be useful when you want to simulate failures that might be hard to trigger in a real environment. Spring Boot includes a `@MockBean` annotation that can be used to define a Mockito mock for a bean inside your `ApplicationContext`. You can use the annotation to add new beans or replace a single existing bean definition. The annotation can be used directly on test classes, on fields within your test, or on `@Configuration` classes and fields. When used on a field, the instance of the created mock is also injected. Mock beans are automatically reset after each test method. [NOTE] ==== If your test uses one of Spring Boot's test annotations (such as `@SpringBootTest`), this feature is automatically enabled. To use this feature with a different arrangement, listeners must be explicitly added, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/mockingbeans/listener/MyTests.java[] ---- ==== The following example replaces an existing `RemoteService` bean with a mock implementation: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/mockingbeans/bean/MyTests.java[] ---- NOTE: `@MockBean` cannot be used to mock the behavior of a bean that's exercised during application context refresh. By the time the test is executed, the application context refresh has completed and it is too late to configure the mocked behavior. We recommend using a `@Bean` method to create and configure the mock in this situation. Additionally, you can use `@SpyBean` to wrap any existing bean with a Mockito `spy`. See the {spring-boot-test-module-api}/mock/mockito/SpyBean.html[Javadoc] for full details. NOTE: CGLib proxies, such as those created for scoped beans, declare the proxied methods as `final`. This stops Mockito from functioning correctly as it cannot mock or spy on `final` methods in its default configuration. If you want to mock or spy on such a bean, configure Mockito to use its inline mock maker by adding `org.mockito:mockito-inline` to your application's test dependencies. This allows Mockito to mock and spy on `final` methods. NOTE: While Spring's test framework caches application contexts between tests and reuses a context for tests sharing the same configuration, the use of `@MockBean` or `@SpyBean` influences the cache key, which will most likely increase the number of contexts. TIP: If you are using `@SpyBean` to spy on a bean with `@Cacheable` methods that refer to parameters by name, your application must be compiled with `-parameters`. This ensures that the parameter names are available to the caching infrastructure once the bean has been spied upon. TIP: When you are using `@SpyBean` to spy on a bean that is proxied by Spring, you may need to remove Spring's proxy in some situations, for example when setting expectations using `given` or `when`. Use `AopTestUtils.getTargetObject(yourProxiedSpy)` to do so. [[features.testing.spring-boot-applications.autoconfigured-tests]] ==== Auto-configured Tests Spring Boot's auto-configuration system works well for applications but can sometimes be a little too much for tests. It often helps to load only the parts of the configuration that are required to test a ""`slice`"" of your application. For example, you might want to test that Spring MVC controllers are mapping URLs correctly, and you do not want to involve database calls in those tests, or you might want to test JPA entities, and you are not interested in the web layer when those tests run. The `spring-boot-test-autoconfigure` module includes a number of annotations that can be used to automatically configure such ""`slices`"". Each of them works in a similar way, providing a `@...Test` annotation that loads the `ApplicationContext` and one or more `@AutoConfigure...` annotations that can be used to customize auto-configuration settings. NOTE: Each slice restricts component scan to appropriate components and loads a very restricted set of auto-configuration classes. If you need to exclude one of them, most `@...Test` annotations provide an `excludeAutoConfiguration` attribute. Alternatively, you can use `@ImportAutoConfiguration#exclude`. NOTE: Including multiple ""`slices`"" by using several `@...Test` annotations in one test is not supported. If you need multiple ""`slices`"", pick one of the `@...Test` annotations and include the `@AutoConfigure...` annotations of the other ""`slices`"" by hand. TIP: It is also possible to use the `@AutoConfigure...` annotations with the standard `@SpringBootTest` annotation. You can use this combination if you are not interested in ""`slicing`"" your application but you want some of the auto-configured test beans. [[features.testing.spring-boot-applications.json-tests]] ==== Auto-configured JSON Tests To test that object JSON serialization and deserialization is working as expected, you can use the `@JsonTest` annotation. `@JsonTest` auto-configures the available supported JSON mapper, which can be one of the following libraries: * Jackson `ObjectMapper`, any `@JsonComponent` beans and any Jackson ``Module``s * `Gson` * `Jsonb` TIP: A list of the auto-configurations that are enabled by `@JsonTest` can be <>. If you need to configure elements of the auto-configuration, you can use the `@AutoConfigureJsonTesters` annotation. Spring Boot includes AssertJ-based helpers that work with the JSONAssert and JsonPath libraries to check that JSON appears as expected. The `JacksonTester`, `GsonTester`, `JsonbTester`, and `BasicJsonTester` classes can be used for Jackson, Gson, Jsonb, and Strings respectively. Any helper fields on the test class can be `@Autowired` when using `@JsonTest`. The following example shows a test class for Jackson: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/jsontests/MyJsonTests.java[] ---- NOTE: JSON helper classes can also be used directly in standard unit tests. To do so, call the `initFields` method of the helper in your `@Before` method if you do not use `@JsonTest`. If you're using Spring Boot's AssertJ-based helpers to assert on a number value at a given JSON path, you might not be able to use `isEqualTo` depending on the type. Instead, you can use AssertJ's `satisfies` to assert that the value matches the given condition. For instance, the following example asserts that the actual number is a float value close to `0.15` within an offset of `0.01`. [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/jsontests/MyJsonAssertJTests.java[tag=*] ---- [[features.testing.spring-boot-applications.spring-mvc-tests]] ==== Auto-configured Spring MVC Tests To test whether Spring MVC controllers are working as expected, use the `@WebMvcTest` annotation. `@WebMvcTest` auto-configures the Spring MVC infrastructure and limits scanned beans to `@Controller`, `@ControllerAdvice`, `@JsonComponent`, `Converter`, `GenericConverter`, `Filter`, `HandlerInterceptor`, `WebMvcConfigurer`, and `HandlerMethodArgumentResolver`. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@WebMvcTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. TIP: A list of the auto-configuration settings that are enabled by `@WebMvcTest` can be <>. TIP: If you need to register extra components, such as the Jackson `Module`, you can import additional configuration classes by using `@Import` on your test. Often, `@WebMvcTest` is limited to a single controller and is used in combination with `@MockBean` to provide mock implementations for required collaborators. `@WebMvcTest` also auto-configures `MockMvc`. Mock MVC offers a powerful way to quickly test MVC controllers without needing to start a full HTTP server. TIP: You can also auto-configure `MockMvc` in a non-`@WebMvcTest` (such as `@SpringBootTest`) by annotating it with `@AutoConfigureMockMvc`. The following example uses `MockMvc`: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/springmvctests/MyControllerTests.java[] ---- TIP: If you need to configure elements of the auto-configuration (for example, when servlet filters should be applied) you can use attributes in the `@AutoConfigureMockMvc` annotation. If you use HtmlUnit or Selenium, auto-configuration also provides an HtmlUnit `WebClient` bean and/or a Selenium `WebDriver` bean. The following example uses HtmlUnit: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/springmvctests/MyHtmlUnitTests.java[] ---- NOTE: By default, Spring Boot puts `WebDriver` beans in a special ""`scope`"" to ensure that the driver exits after each test and that a new instance is injected. If you do not want this behavior, you can add `@Scope(""singleton"")` to your `WebDriver` `@Bean` definition. WARNING: The `webDriver` scope created by Spring Boot will replace any user defined scope of the same name. If you define your own `webDriver` scope you may find it stops working when you use `@WebMvcTest`. If you have Spring Security on the classpath, `@WebMvcTest` will also scan `WebSecurityConfigurer` beans. Instead of disabling security completely for such tests, you can use Spring Security's test support. More details on how to use Spring Security's `MockMvc` support can be found in this _<>_ how-to section. TIP: Sometimes writing Spring MVC tests is not enough; Spring Boot can help you run <>. [[features.testing.spring-boot-applications.spring-webflux-tests]] ==== Auto-configured Spring WebFlux Tests To test that {spring-framework-docs}/web-reactive.html[Spring WebFlux] controllers are working as expected, you can use the `@WebFluxTest` annotation. `@WebFluxTest` auto-configures the Spring WebFlux infrastructure and limits scanned beans to `@Controller`, `@ControllerAdvice`, `@JsonComponent`, `Converter`, `GenericConverter`, `WebFilter`, and `WebFluxConfigurer`. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@WebFluxTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. TIP: A list of the auto-configurations that are enabled by `@WebFluxTest` can be <>. TIP: If you need to register extra components, such as Jackson `Module`, you can import additional configuration classes using `@Import` on your test. Often, `@WebFluxTest` is limited to a single controller and used in combination with the `@MockBean` annotation to provide mock implementations for required collaborators. `@WebFluxTest` also auto-configures {spring-framework-docs}/testing.html#webtestclient[`WebTestClient`], which offers a powerful way to quickly test WebFlux controllers without needing to start a full HTTP server. TIP: You can also auto-configure `WebTestClient` in a non-`@WebFluxTest` (such as `@SpringBootTest`) by annotating it with `@AutoConfigureWebTestClient`. The following example shows a class that uses both `@WebFluxTest` and a `WebTestClient`: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/springwebfluxtests/MyControllerTests.java[] ---- TIP: This setup is only supported by WebFlux applications as using `WebTestClient` in a mocked web application only works with WebFlux at the moment. NOTE: `@WebFluxTest` cannot detect routes registered via the functional web framework. For testing `RouterFunction` beans in the context, consider importing your `RouterFunction` yourself via `@Import` or using `@SpringBootTest`. NOTE: `@WebFluxTest` cannot detect custom security configuration registered via a `@Bean` of type `SecurityWebFilterChain`. To include that in your test, you will need to import the configuration that registers the bean via `@Import` or use `@SpringBootTest`. TIP: Sometimes writing Spring WebFlux tests is not enough; Spring Boot can help you run <>. [[features.testing.spring-boot-applications.autoconfigured-spring-data-cassandra]] ==== Auto-configured Data Cassandra Tests You can use `@DataCassandraTest` to test Cassandra applications. By default, it configures a `CassandraTemplate`, scans for `@Table` classes, and configures Spring Data Cassandra repositories. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataCassandraTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. (For more about using Cassandra with Spring Boot, see ""<>"", earlier in this chapter.) TIP: A list of the auto-configuration settings that are enabled by `@DataCassandraTest` can be <>. The following example shows a typical setup for using Cassandra tests in Spring Boot: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdatacassandra/MyDataCassandraTests.java[] ---- [[features.testing.spring-boot-applications.autoconfigured-spring-data-jpa]] ==== Auto-configured Data JPA Tests You can use the `@DataJpaTest` annotation to test JPA applications. By default, it scans for `@Entity` classes and configures Spring Data JPA repositories. If an embedded database is available on the classpath, it configures one as well. SQL queries are logged by default by setting the `spring.jpa.show-sql` property to `true`. This can be disabled using the `showSql()` attribute of the annotation. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataJpaTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. TIP: A list of the auto-configuration settings that are enabled by `@DataJpaTest` can be <>. By default, data JPA tests are transactional and roll back at the end of each test. See the {spring-framework-docs}/testing.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details. If that is not what you want, you can disable transaction management for a test or for the whole class as follows: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdatajpa/MyNonTransactionalTests.java[] ---- Data JPA tests may also inject a {spring-boot-test-autoconfigure-module-code}/orm/jpa/TestEntityManager.java[`TestEntityManager`] bean, which provides an alternative to the standard JPA `EntityManager` that is specifically designed for tests. If you want to use `TestEntityManager` outside of `@DataJpaTest` instances, you can also use the `@AutoConfigureTestEntityManager` annotation. A `JdbcTemplate` is also available if you need that. The following example shows the `@DataJpaTest` annotation in use: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdatajpa/withoutdb/MyRepositoryTests.java[] ---- In-memory embedded databases generally work well for tests, since they are fast and do not require any installation. If, however, you prefer to run tests against a real database you can use the `@AutoConfigureTestDatabase` annotation, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdatajpa/withdb/MyRepositoryTests.java[] ---- [[features.testing.spring-boot-applications.autoconfigured-jdbc]] ==== Auto-configured JDBC Tests `@JdbcTest` is similar to `@DataJpaTest` but is for tests that only require a `DataSource` and do not use Spring Data JDBC. By default, it configures an in-memory embedded database and a `JdbcTemplate`. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@JdbcTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. TIP: A list of the auto-configurations that are enabled by `@JdbcTest` can be <>. By default, JDBC tests are transactional and roll back at the end of each test. See the {spring-framework-docs}/testing.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details. If that is not what you want, you can disable transaction management for a test or for the whole class, as follows: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredjdbc/MyTransactionalTests.java[] ---- If you prefer your test to run against a real database, you can use the `@AutoConfigureTestDatabase` annotation in the same way as for `DataJpaTest`. (See ""<>"".) [[features.testing.spring-boot-applications.autoconfigured-spring-data-jdbc]] ==== Auto-configured Data JDBC Tests `@DataJdbcTest` is similar to `@JdbcTest` but is for tests that use Spring Data JDBC repositories. By default, it configures an in-memory embedded database, a `JdbcTemplate`, and Spring Data JDBC repositories. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataJdbcTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. TIP: A list of the auto-configurations that are enabled by `@DataJdbcTest` can be <>. By default, Data JDBC tests are transactional and roll back at the end of each test. See the {spring-framework-docs}/testing.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details. If that is not what you want, you can disable transaction management for a test or for the whole test class as <>. If you prefer your test to run against a real database, you can use the `@AutoConfigureTestDatabase` annotation in the same way as for `DataJpaTest`. (See ""<>"".) [[features.testing.spring-boot-applications.autoconfigured-jooq]] ==== Auto-configured jOOQ Tests You can use `@JooqTest` in a similar fashion as `@JdbcTest` but for jOOQ-related tests. As jOOQ relies heavily on a Java-based schema that corresponds with the database schema, the existing `DataSource` is used. If you want to replace it with an in-memory database, you can use `@AutoConfigureTestDatabase` to override those settings. (For more about using jOOQ with Spring Boot, see ""<>"", earlier in this chapter.) Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@JooqTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. TIP: A list of the auto-configurations that are enabled by `@JooqTest` can be <>. `@JooqTest` configures a `DSLContext`. The following example shows the `@JooqTest` annotation in use: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredjooq/MyJooqTests.java[] ---- JOOQ tests are transactional and roll back at the end of each test by default. If that is not what you want, you can disable transaction management for a test or for the whole test class as <>. [[features.testing.spring-boot-applications.autoconfigured-spring-data-mongodb]] ==== Auto-configured Data MongoDB Tests You can use `@DataMongoTest` to test MongoDB applications. By default, it configures an in-memory embedded MongoDB (if available), configures a `MongoTemplate`, scans for `@Document` classes, and configures Spring Data MongoDB repositories. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataMongoTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. (For more about using MongoDB with Spring Boot, see ""<>"", earlier in this chapter.) TIP: A list of the auto-configuration settings that are enabled by `@DataMongoTest` can be <>. The following class shows the `@DataMongoTest` annotation in use: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdatamongodb/withoutdb/MyDataMongoDbTests.java[] ---- In-memory embedded MongoDB generally works well for tests, since it is fast and does not require any developer installation. If, however, you prefer to run tests against a real MongoDB server, you should exclude the embedded MongoDB auto-configuration, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdatamongodb/withdb/MyDataMongoDbTests.java[] ---- [[features.testing.spring-boot-applications.autoconfigured-spring-data-neo4j]] ==== Auto-configured Data Neo4j Tests You can use `@DataNeo4jTest` to test Neo4j applications. By default, it scans for `@Node` classes, and configures Spring Data Neo4j repositories. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataNeo4jTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. (For more about using Neo4J with Spring Boot, see ""<>"", earlier in this chapter.) TIP: A list of the auto-configuration settings that are enabled by `@DataNeo4jTest` can be <>. The following example shows a typical setup for using Neo4J tests in Spring Boot: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdataneo4j/propagation/MyDataNeo4jTests.java[] ---- By default, Data Neo4j tests are transactional and roll back at the end of each test. See the {spring-framework-docs}/testing.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details. If that is not what you want, you can disable transaction management for a test or for the whole class, as follows: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdataneo4j/nopropagation/MyDataNeo4jTests.java[] ---- NOTE: Transactional tests are not supported with reactive access. If you are using this style, you must configure `@DataNeo4jTest` tests as described above. [[features.testing.spring-boot-applications.autoconfigured-spring-data-redis]] ==== Auto-configured Data Redis Tests You can use `@DataRedisTest` to test Redis applications. By default, it scans for `@RedisHash` classes and configures Spring Data Redis repositories. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataRedisTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. (For more about using Redis with Spring Boot, see ""<>"", earlier in this chapter.) TIP: A list of the auto-configuration settings that are enabled by `@DataRedisTest` can be <>. The following example shows the `@DataRedisTest` annotation in use: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdataredis/MyDataRedisTests.java[] ---- [[features.testing.spring-boot-applications.autoconfigured-spring-data-ldap]] ==== Auto-configured Data LDAP Tests You can use `@DataLdapTest` to test LDAP applications. By default, it configures an in-memory embedded LDAP (if available), configures an `LdapTemplate`, scans for `@Entry` classes, and configures Spring Data LDAP repositories. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataLdapTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. (For more about using LDAP with Spring Boot, see ""<>"", earlier in this chapter.) TIP: A list of the auto-configuration settings that are enabled by `@DataLdapTest` can be <>. The following example shows the `@DataLdapTest` annotation in use: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdataldap/inmemory/MyDataLdapTests.java[] ---- In-memory embedded LDAP generally works well for tests, since it is fast and does not require any developer installation. If, however, you prefer to run tests against a real LDAP server, you should exclude the embedded LDAP auto-configuration, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdataldap/server/MyDataLdapTests.java[] ---- [[features.testing.spring-boot-applications.autoconfigured-rest-client]] ==== Auto-configured REST Clients You can use the `@RestClientTest` annotation to test REST clients. By default, it auto-configures Jackson, GSON, and Jsonb support, configures a `RestTemplateBuilder`, and adds support for `MockRestServiceServer`. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@RestClientTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. TIP: A list of the auto-configuration settings that are enabled by `@RestClientTest` can be <>. The specific beans that you want to test should be specified by using the `value` or `components` attribute of `@RestClientTest`, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredrestclient/MyRestClientTests.java[] ---- [[features.testing.spring-boot-applications.autoconfigured-spring-restdocs]] ==== Auto-configured Spring REST Docs Tests You can use the `@AutoConfigureRestDocs` annotation to use {spring-restdocs}[Spring REST Docs] in your tests with Mock MVC, REST Assured, or WebTestClient. It removes the need for the JUnit extension in Spring REST Docs. `@AutoConfigureRestDocs` can be used to override the default output directory (`target/generated-snippets` if you are using Maven or `build/generated-snippets` if you are using Gradle). It can also be used to configure the host, scheme, and port that appears in any documented URIs. [[features.testing.spring-boot-applications.autoconfigured-spring-restdocs.with-mock-mvc]] ===== Auto-configured Spring REST Docs Tests with Mock MVC `@AutoConfigureRestDocs` customizes the `MockMvc` bean to use Spring REST Docs when testing Servlet-based web applications. You can inject it by using `@Autowired` and use it in your tests as you normally would when using Mock MVC and Spring REST Docs, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringrestdocs/withmockmvc/MyUserDocumentationTests.java[] ---- If you require more control over Spring REST Docs configuration than offered by the attributes of `@AutoConfigureRestDocs`, you can use a `RestDocsMockMvcConfigurationCustomizer` bean, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringrestdocs/withmockmvc/MyRestDocsConfiguration.java[] ---- If you want to make use of Spring REST Docs support for a parameterized output directory, you can create a `RestDocumentationResultHandler` bean. The auto-configuration calls `alwaysDo` with this result handler, thereby causing each `MockMvc` call to automatically generate the default snippets. The following example shows a `RestDocumentationResultHandler` being defined: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringrestdocs/withmockmvc/MyResultHandlerConfiguration.java[] ---- [[features.testing.spring-boot-applications.autoconfigured-spring-restdocs.with-web-test-client]] ===== Auto-configured Spring REST Docs Tests with WebTestClient `@AutoConfigureRestDocs` can also be used with `WebTestClient` when testing reactive web applications. You can inject it by using `@Autowired` and use it in your tests as you normally would when using `@WebFluxTest` and Spring REST Docs, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringrestdocs/withwebtestclient/MyUsersDocumentationTests.java[] ---- If you require more control over Spring REST Docs configuration than offered by the attributes of `@AutoConfigureRestDocs`, you can use a `RestDocsWebTestClientConfigurationCustomizer` bean, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringrestdocs/withwebtestclient/MyRestDocsConfiguration.java[] ---- [[features.testing.spring-boot-applications.autoconfigured-spring-restdocs.with-rest-assured]] ===== Auto-configured Spring REST Docs Tests with REST Assured `@AutoConfigureRestDocs` makes a `RequestSpecification` bean, preconfigured to use Spring REST Docs, available to your tests. You can inject it by using `@Autowired` and use it in your tests as you normally would when using REST Assured and Spring REST Docs, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringrestdocs/withrestassured/MyUserDocumentationTests.java[] ---- If you require more control over Spring REST Docs configuration than offered by the attributes of `@AutoConfigureRestDocs`, a `RestDocsRestAssuredConfigurationCustomizer` bean can be used, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringrestdocs/withrestassured/MyRestDocsConfiguration.java[] ---- [[features.testing.spring-boot-applications.autoconfigured-webservices]] ==== Auto-configured Spring Web Services Tests You can use `@WebServiceClientTest` to test applications that use call web services using the Spring Web Services project. By default, it configures a mock `WebServiceServer` bean and automatically customizes your `WebServiceTemplateBuilder`. (For more about using Web Services with Spring Boot, see ""<>"", earlier in this chapter.) TIP: A list of the auto-configuration settings that are enabled by `@WebServiceClientTest` can be <>. The following example shows the `@WebServiceClientTest` annotation in use: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredwebservices/MyWebServiceClientTests.java[] ---- [[features.testing.spring-boot-applications.additional-autoconfiguration-and-slicing]] ==== Additional Auto-configuration and Slicing Each slice provides one or more `@AutoConfigure...` annotations that namely defines the auto-configurations that should be included as part of a slice. Additional auto-configurations can be added on a test-by-test basis by creating a custom `@AutoConfigure...` annotation or by adding `@ImportAutoConfiguration` to the test as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/additionalautoconfigurationandslicing/MyJdbcTests.java[] ---- NOTE: Make sure to not use the regular `@Import` annotation to import auto-configurations as they are handled in a specific way by Spring Boot. Alternatively, additional auto-configurations can be added for any use of a slice annotation by registering them in `META-INF/spring.factories` as shown in the following example: [indent=0] ---- org.springframework.boot.test.autoconfigure.jdbc.JdbcTest=com.example.IntegrationAutoConfiguration ---- TIP: A slice or `@AutoConfigure...` annotation can be customized this way as long as it is meta-annotated with `@ImportAutoConfiguration`. [[features.testing.spring-boot-applications.user-configuration-and-slicing]] ==== User Configuration and Slicing If you <> in a sensible way, your `@SpringBootApplication` class is <> as the configuration of your tests. It then becomes important not to litter the application's main class with configuration settings that are specific to a particular area of its functionality. Assume that you are using Spring Batch and you rely on the auto-configuration for it. You could define your `@SpringBootApplication` as follows: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/userconfigurationandslicing/MyApplication.java[] ---- Because this class is the source configuration for the test, any slice test actually tries to start Spring Batch, which is definitely not what you want to do. A recommended approach is to move that area-specific configuration to a separate `@Configuration` class at the same level as your application, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/userconfigurationandslicing/MyBatchConfiguration.java[] ---- NOTE: Depending on the complexity of your application, you may either have a single `@Configuration` class for your customizations or one class per domain area. The latter approach lets you enable it in one of your tests, if necessary, with the `@Import` annotation. Test slices exclude `@Configuration` classes from scanning. For example, for a `@WebMvcTest`, the following configuration will not include the given `WebMvcConfigurer` bean in the application context loaded by the test slice: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/userconfigurationandslicing/MyWebConfiguration.java[] ---- The configuration below will, however, cause the custom `WebMvcConfigurer` to be loaded by the test slice. [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/userconfigurationandslicing/MyWebMvcConfigurer.java[] ---- Another source of confusion is classpath scanning. Assume that, while you structured your code in a sensible way, you need to scan an additional package. Your application may resemble the following code: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/userconfigurationandslicing/scan/MyApplication.java[] ---- Doing so effectively overrides the default component scan directive with the side effect of scanning those two packages regardless of the slice that you chose. For instance, a `@DataJpaTest` seems to suddenly scan components and user configurations of your application. Again, moving the custom directive to a separate class is a good way to fix this issue. TIP: If this is not an option for you, you can create a `@SpringBootConfiguration` somewhere in the hierarchy of your test so that it is used instead. Alternatively, you can specify a source for your test, which disables the behavior of finding a default one. [[features.testing.spring-boot-applications.spock]] ==== Using Spock to Test Spring Boot Applications If you wish to use Spock to test a Spring Boot application, you should add a dependency on Spock's `spock-spring` module to your application's build. `spock-spring` integrates Spring's test framework into Spock. See https://spockframework.org/spock/docs/2.0-M4/modules.html#_spring_module[the documentation for Spock's Spring module] for further details. NOTE: As of Spring Boot 2.5.x and its support for Groovy 3.x you have two options to make use of Spock: Either use the latest Spock 2.0 milestone or release that is compatible with Groovy 3.x or stick with Spock 1.3 and downgrade Spring Boot's Groovy version to 2.5.x. [[features.testing.utilities]] === Test Utilities A few test utility classes that are generally useful when testing your application are packaged as part of `spring-boot`. [[features.testing.utilities.config-data-application-context-initializer]] ==== ConfigDataApplicationContextInitializer `ConfigDataApplicationContextInitializer` is an `ApplicationContextInitializer` that you can apply to your tests to load Spring Boot `application.properties` files. You can use it when you do not need the full set of features provided by `@SpringBootTest`, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/utilities/configdataapplicationcontextinitializer/MyConfigFileTests.java[] ---- NOTE: Using `ConfigDataApplicationContextInitializer` alone does not provide support for `@Value(""${...}"")` injection. Its only job is to ensure that `application.properties` files are loaded into Spring's `Environment`. For `@Value` support, you need to either additionally configure a `PropertySourcesPlaceholderConfigurer` or use `@SpringBootTest`, which auto-configures one for you. [[features.testing.utilities.test-property-values]] ==== TestPropertyValues `TestPropertyValues` lets you quickly add properties to a `ConfigurableEnvironment` or `ConfigurableApplicationContext`. You can call it with `key=value` strings, as follows: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/utilities/testpropertyvalues/MyEnvironmentTests.java[] ---- [[features.testing.utilities.output-capture]] ==== OutputCapture `OutputCapture` is a JUnit `Extension` that you can use to capture `System.out` and `System.err` output. To use add `@ExtendWith(OutputCaptureExtension.class)` and inject `CapturedOutput` as an argument to your test class constructor or test method as follows: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/utilities/outputcapture/MyOutputCaptureTests.java[] ---- [[features.testing.utilities.test-rest-template]] ==== TestRestTemplate `TestRestTemplate` is a convenience alternative to Spring's `RestTemplate` that is useful in integration tests. You can get a vanilla template or one that sends Basic HTTP authentication (with a username and password). In either case, the template is fault tolerant. This means that it behaves in a test-friendly way by not throwing exceptions on 4xx and 5xx errors. Instead, such errors can be detected via the returned `ResponseEntity` and its status code. TIP: Spring Framework 5.0 provides a new `WebTestClient` that works for <> and both <>. It provides a fluent API for assertions, unlike `TestRestTemplate`. It is recommended, but not mandatory, to use the Apache HTTP Client (version 4.3.2 or better). If you have that on your classpath, the `TestRestTemplate` responds by configuring the client appropriately. If you do use Apache's HTTP client, some additional test-friendly features are enabled: * Redirects are not followed (so you can assert the response location). * Cookies are ignored (so the template is stateless). `TestRestTemplate` can be instantiated directly in your integration tests, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/utilities/testresttemplate/MyTests.java[] ---- Alternatively, if you use the `@SpringBootTest` annotation with `WebEnvironment.RANDOM_PORT` or `WebEnvironment.DEFINED_PORT`, you can inject a fully configured `TestRestTemplate` and start using it. If necessary, additional customizations can be applied through the `RestTemplateBuilder` bean. Any URLs that do not specify a host and port automatically connect to the embedded server, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/utilities/testresttemplate/MySpringBootTests.java[] ---- ",12421,True,2630.4525243859475,median "/* The MIT License (MIT) Copyright (c) 2020 Lancaster University. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include ""MicroBitLog.h"" #include ""CodalDmesg.h"" #include using namespace codal; static ManagedString padString(ManagedString s, int digits) { ManagedString zero = ""0""; while(s.length() != digits) s = zero + s; return s; } static void writeNum(char *buf, uint32_t n) { int i = 0; int sh = 28; while (sh >= 0) { int d = (n >> sh) & 0xf; buf[i++] = d > 9 ? 'A' + d - 10 : '0' + d; sh -= 4; } buf[i] = 0; } /** * Constructor. */ MicroBitLog::MicroBitLog(MicroBitUSBFlashManager &flash, NRF52Serial &serial, int journalPages) : flash(flash), serial(serial), cache(flash, CONFIG_MICROBIT_LOG_CACHE_BLOCK_SIZE, 4) { this->journalPages = journalPages; this->status = 0; this->journalHead = 0; this->startAddress = 0; this->journalStart = 0; this->dataStart = 0; this->headingStart = 0; this->headingLength = 0; this->headingCount = 0; this->logEnd = 0; this->headingsChanged = false; this->rowData = NULL; this->timeStampFormat = TimeStampFormat::None; } /** * Attempt to load an exisitng filesystem, or format a new one if not found. */ void MicroBitLog::init() { // If we're already initialized, do nothing. if (status & MICROBIT_LOG_STATUS_INITIALIZED) return; if (isPresent()) { // We have a valid file system. JournalEntry j; journalPages = (dataStart - startAddress) / flash.getPageSize() - 1; journalHead = journalStart; dataEnd = dataStart; // Load the last entry in the journal. uint32_t journalEntryAddress = journalHead; bool valid = false; while(journalEntryAddress < dataStart) { cache.read(journalEntryAddress, j.length, MICROBIT_LOG_JOURNAL_ENTRY_SIZE); // If we have a valid reading follwed by an unused entry, we're done. if (j.containsOnly(0xFF) && valid) break; // Parse valid entries. We continue processing to the last valid entry, just in case. if (!j.containsOnly(0x00)) { journalHead = journalEntryAddress; dataEnd = dataStart + strtoul(j.length, NULL, 16); valid = true; } journalEntryAddress += MICROBIT_LOG_JOURNAL_ENTRY_SIZE; } // Walk the page indicated by dataEnd, and increment until an unused byte (0xFF) is found. uint8_t d = 0; while(dataEnd < logEnd) { cache.read(dataEnd, &d, 1); if (d == 0xFF) break; dataEnd++; } // Determine if we have any column headers defined // If so, parse them. uint32_t start = startAddress + sizeof(MicroBitLogMetaData); char c; // Skip any leading zeroes (erased old data) cache.read(start, &c, 1); while(c == 0) { start++; cache.read(start, &c, 1); } // Read read until we see a 0xFF character (unused memory) uint32_t end = start; while(c != 0xff) { end++; cache.read(end, &c, 1); } headingLength = (int)(end-start); // If we have a valid set of headers recorded, parse them in. if (headingLength > 0) { headingStart = start; headingCount = 0; char *headers = (char *) malloc(headingLength); cache.read(start, headers, headingLength); // Count the number of comma separated headers. // Also terminate each entry as a string as we go. for (uint32_t i=0; itimeStampFormat); mutex.notify(); } /** * Determines the format of the timestamp data to be added (if any). * If requested, time stamps will be automatically added to each row of data * as an integer value rounded down to the unit specified. * * @param format The format of timestamp to use. */ void MicroBitLog::setTimeStamp(TimeStampFormat format) { init(); this->timeStampFormat = format; // If we do not have a timestamp column associated with the requested time unit, create one. ManagedString units; switch (format) { case TimeStampFormat::None: return; case TimeStampFormat::Milliseconds: units = ""milliseconds""; break; case TimeStampFormat::Seconds: units = ""seconds""; break; case TimeStampFormat::Minutes: units = ""minutes""; break; case TimeStampFormat::Hours: units = ""hours""; break; case TimeStampFormat::Days: units = ""hours""; break; } timeStampHeading = ""Time ("" + units + "")""; // Attempt to add the column, if it does not already exist. // Add at the front, unless data has already been written. addHeading(timeStampHeading, ManagedString::EmptyString, dataStart == dataEnd); } /** * Defines if data logging should also be streamed over the serial port. * * @param enable True to enable serial port streaming, false to disable. */ void MicroBitLog::setSerialMirroring(bool enable) { if (enable) status |= MICROBIT_LOG_STATUS_SERIAL_MIRROR; else status &= ~MICROBIT_LOG_STATUS_SERIAL_MIRROR; } /** * Creates a new row in the log, ready to be populated by logData() * * @return DEVICE_OK on success. */ int MicroBitLog::beginRow() { init(); // If beginRow is called during an open transaction, implicity perform an endRow before proceeding. if (status & MICROBIT_LOG_STATUS_ROW_STARTED) endRow(); // Reset all values, ready to populate with a new row. for (uint32_t i=0; i 1) { fraction = units % 100; units = units / 100; billions = billions / 100; } ManagedString u(units); ManagedString f(fraction); ManagedString s; f = padString(f, 2); if (billions) { s = s + billions; u = padString(u, 9); } s = s + u; // Add two decimal places for anything other than milliseconds. if ((int)timeStampFormat > 1) s = s + ""."" + f; logData(timeStampHeading, s); } // If new columns have been added since the last row, update persistent storage accordingly. ManagedString sep = "",""; if (headingsChanged) { // If this is the first time we have logged any headings, place them just after the metadata block if (headingStart == 0) headingStart = startAddress + sizeof(MicroBitLogMetaData); // create new headers ManagedString h; ManagedBuffer zero(headingLength); for (uint32_t i=0; i"" and optionally "",\\t\\n"") * * @param s the data to clean * @param len the number of characters to clean * @param removeSeperators if set to false, only ""-->"" symbols are erased, otherwise "",\\t\\n"" characters are also removed. * @return a cleaned version of the string supplied, if any changes are necessary. Otherwise, an empty string is returned. */ ManagedString MicroBitLog::cleanBuffer(const char *s, int len, bool removeSeparators) { ManagedString out; for (int i=0; i') { if (out.length() == 0) out = ManagedString(s, len); *(char *)(out.toCharArray()+i) = CONFIG_MICROBIT_LOG_INVALID_CHAR_VALUE; *(char *)(out.toCharArray()+i+1) = CONFIG_MICROBIT_LOG_INVALID_CHAR_VALUE; *(char *)(out.toCharArray()+i+2) = CONFIG_MICROBIT_LOG_INVALID_CHAR_VALUE; } if (s[i] == '\\t' || (removeSeparators && (s[i] == ',' || s[i] == '\\n'))) { if (out.length() == 0) out = ManagedString(s, len); *(char *)(out.toCharArray()+i) = CONFIG_MICROBIT_LOG_INVALID_CHAR_VALUE; } } return out; } /** * Inject the given row into the log as text, ignoring key/value pairs. * @param s the string to inject. */ int MicroBitLog::logString(const char *s) { mutex.wait(); init(); uint32_t oldDataEnd = dataEnd; uint32_t l = strlen(s); const char *data = s; // If this is the first log entry written, ensure that the file visibility is activated. // (it may have been disabled following a full erase) if (dataStart == dataEnd) setVisibility(true); // If we can't write a whole line of data, then treat the log as full. if (l > logEnd - dataEnd) { if (!(status & MICROBIT_LOG_STATUS_FULL)) { cache.write(logEnd+1, ""FUL"", 3); status |= MICROBIT_LOG_STATUS_FULL; } mutex.notify(); Event(MICROBIT_ID_LOG, MICROBIT_LOG_EVT_LOG_FULL); return DEVICE_NO_RESOURCES; } ManagedString cleaned = cleanBuffer(data, l, false); if (cleaned.length()) data = cleaned.toCharArray(); // If requested, log the data over the serial port if (status & MICROBIT_LOG_STATUS_SERIAL_MIRROR && l > 0) serial.send((uint8_t *)data, l); while (l > 0) { uint32_t spaceOnPage = flash.getPageSize() - (dataEnd % flash.getPageSize()); //DMESG(""SPACE_ON_PAGE: %d"", spaceOnPage); int lengthToWrite = min(l, spaceOnPage); // If we're going to fill (or overspill) the current page, erase the next one ready for use. if (spaceOnPage <= l && dataEnd+spaceOnPage < logEnd) { uint32_t nextPage = ((dataEnd / flash.getPageSize()) + 1) * flash.getPageSize(); //DMESG("" ERASING PAGE %p"", nextPage); flash.erase(nextPage); } // Perform a write through cache update //DMESG("" WRITING [ADDRESS: %p] [LENGTH: %d] "", dataEnd, lengthToWrite); cache.write(dataEnd, data, lengthToWrite); // move on pointers dataEnd += lengthToWrite; data += lengthToWrite; l -= lengthToWrite; } // Write a new entry into the log journal if we crossed a cache block boundary if ((dataEnd / CONFIG_MICROBIT_LOG_CACHE_BLOCK_SIZE) != (oldDataEnd / CONFIG_MICROBIT_LOG_CACHE_BLOCK_SIZE)) { uint32_t oldJournalHead = journalHead; oldDataEnd = dataEnd; // Record that we've moved on the journal log by one entry journalHead += MICROBIT_LOG_JOURNAL_ENTRY_SIZE; // If we've moved onto another page, ensure it is erased. if (journalHead % flash.getPageSize() == 0) { //DMESG(""JOURNAL PAGE BOUNDARY: %p"", journalHead); // If we've rolled over the last page, cycle around. if (journalHead == dataStart) { //DMESG(""JOURNAL WRAPAROUND""); journalHead = journalStart; } //DMESG(""ERASING JOURNAL PAGE: %p"", journalHead); cache.erase(journalHead); flash.erase(journalHead); } // Write journal entry JournalEntry je; writeNum(je.length, ((dataEnd-dataStart) / CONFIG_MICROBIT_LOG_CACHE_BLOCK_SIZE) * CONFIG_MICROBIT_LOG_CACHE_BLOCK_SIZE); cache.write(journalHead, &je, MICROBIT_LOG_JOURNAL_ENTRY_SIZE); // Invalidate the old one JournalEntry empty; empty.clear(); //DMESG("" INVALIDATING: %p"", oldJournalHead); cache.write(oldJournalHead, &empty, MICROBIT_LOG_JOURNAL_ENTRY_SIZE); } mutex.notify(); // Return NO_RESOURCES if we ran out of FLASH space. if (l == 0) return DEVICE_OK; Event(MICROBIT_ID_LOG, MICROBIT_LOG_EVT_LOG_FULL); return DEVICE_NO_RESOURCES; } /** * Inject the given row into the log as text, ignoring key/value pairs. * @param s the string to inject. */ int MicroBitLog::logString(ManagedString s) { logString(s.toCharArray()); return DEVICE_OK; } /** * Add the given heading to the list of headings in use. If the heading already exists, * this method has no effect. * * @param key the heading to add * @param value the initial value to add, or ManagedString::EmptyString * @param head true to add the given field at the front of the list, false to add at the end. */ void MicroBitLog::addHeading(ManagedString key, ManagedString value, bool head) { for (uint32_t i=0; i= startAddress + 2*flash.getPageSize() && dataStart < logEnd && logEnd < flash.getFlashEnd() && memcmp(metaData.version, MICROBIT_LOG_VERSION, 17) == 0); } /** * Determines if this log is full * * @return true if the log is full, false otherwise. */ bool MicroBitLog::isFull() { return (status & MICROBIT_LOG_STATUS_FULL); } /** * Destructor. */ MicroBitLog::~MicroBitLog() { } const uint8_t MicroBitLog::header[2048] = {0x3c,0x6d,0x65,0x74,0x61,0x20,0x63,0x68,0x61,0x72,0x73,0x65,0x74,0x3d,0x75,0x74,0x66,0x2d,0x38,0x3e,0x3c,0x73,0x74,0x79,0x6c,0x65,0x3e,0x2e,0x62,0x62,0x7b,0x64,0x69,0x73,0x70,0x6c,0x61,0x79,0x3a,0x66,0x6c,0x65,0x78,0x7d,0x2e,0x62,0x62,0x3e,0x2a,0x2b,0x2a,0x7b,0x6d,0x61,0x72,0x67,0x69,0x6e,0x2d,0x6c,0x65,0x66,0x74,0x3a,0x31,0x30,0x70,0x78,0x7d,0x62,0x75,0x74,0x74,0x6f,0x6e,0x7b,0x64,0x69,0x73,0x70,0x6c,0x61,0x79,0x3a,0x62,0x6c,0x6f,0x63,0x6b,0x7d,0x62,0x6f,0x64,0x79,0x7b,0x66,0x6f,0x6e,0x74,0x2d,0x66,0x61,0x6d,0x69,0x6c,0x79,0x3a,0x73,0x61,0x6e,0x73,0x2d,0x73,0x65,0x72,0x69,0x66,0x3b,0x6d,0x61,0x72,0x67,0x69,0x6e,0x3a,0x31,0x65,0x6d,0x7d,0x74,0x61,0x62,0x6c,0x65,0x7b,0x62,0x6f,0x72,0x64,0x65,0x72,0x2d,0x63,0x6f,0x6c,0x6c,0x61,0x70,0x73,0x65,0x3a,0x63,0x6f,0x6c,0x6c,0x61,0x70,0x73,0x65,0x3b,0x6d,0x61,0x72,0x67,0x69,0x6e,0x2d,0x74,0x6f,0x70,0x3a,0x31,0x65,0x6d,0x3b,0x74,0x65,0x78,0x74,0x2d,0x61,0x6c,0x69,0x67,0x6e,0x3a,0x72,0x69,0x67,0x68,0x74,0x7d,0x74,0x72,0x3a,0x66,0x69,0x72,0x73,0x74,0x2d,0x63,0x68,0x69,0x6c,0x64,0x7b,0x66,0x6f,0x6e,0x74,0x2d,0x77,0x65,0x69,0x67,0x68,0x74,0x3a,0x37,0x30,0x30,0x7d,0x74,0x64,0x7b,0x62,0x6f,0x72,0x64,0x65,0x72,0x3a,0x31,0x70,0x78,0x20,0x73,0x6f,0x6c,0x69,0x64,0x20,0x23,0x64,0x64,0x64,0x3b,0x70,0x61,0x64,0x64,0x69,0x6e,0x67,0x3a,0x38,0x70,0x78,0x3b,0x6d,0x69,0x6e,0x2d,0x77,0x69,0x64,0x74,0x68,0x3a,0x38,0x63,0x68,0x7d,0x69,0x66,0x72,0x61,0x6d,0x65,0x7b,0x64,0x69,0x73,0x70,0x6c,0x61,0x79,0x3a,0x6e,0x6f,0x6e,0x65,0x7d,0x3c,0x2f,0x73,0x74,0x79,0x6c,0x65,0x3e,0x3c,0x6c,0x69,0x6e,0x6b,0x20,0x72,0x65,0x6c,0x3d,0x73,0x74,0x79,0x6c,0x65,0x73,0x68,0x65,0x65,0x74,0x20,0x68,0x72,0x65,0x66,0x3d,0x68,0x74,0x74,0x70,0x73,0x3a,0x2f,0x2f,0x6d,0x69,0x63,0x72,0x6f,0x62,0x69,0x74,0x2e,0x6f,0x72,0x67,0x2f,0x64,0x6c,0x2f,0x32,0x2f,0x64,0x6c,0x2e,0x63,0x73,0x73,0x3e,0x3c,0x73,0x63,0x72,0x69,0x70,0x74,0x3e,0x6c,0x65,0x74,0x20,0x77,0x3d,0x77,0x69,0x6e,0x64,0x6f,0x77,0x2c,0x64,0x3d,0x64,0x6f,0x63,0x75,0x6d,0x65,0x6e,0x74,0x2c,0x6c,0x3d,0x77,0x2e,0x6c,0x6f,0x63,0x61,0x74,0x69,0x6f,0x6e,0x2c,0x6e,0x3d,0x6e,0x75,0x6c,0x6c,0x2c,0x63,0x73,0x76,0x3d,0x22,0x22,0x2c,0x74,0x61,0x67,0x3d,0x64,0x6f,0x63,0x75,0x6d,0x65,0x6e,0x74,0x2e,0x63,0x72,0x65,0x61,0x74,0x65,0x45,0x6c,0x65,0x6d,0x65,0x6e,0x74,0x2e,0x62,0x69,0x6e,0x64,0x28,0x64,0x6f,0x63,0x75,0x6d,0x65,0x6e,0x74,0x29,0x3b,0x77,0x2e,0x64,0x6c,0x3d,0x7b,0x64,0x6f,0x77,0x6e,0x6c,0x6f,0x61,0x64,0x3a,0x66,0x75,0x6e,0x63,0x74,0x69,0x6f,0x6e,0x28,0x29,0x7b,0x6c,0x65,0x74,0x20,0x65,0x3d,0x74,0x61,0x67,0x28,0x22,0x61,0x22,0x29,0x3b,0x65,0x2e,0x64,0x6f,0x77,0x6e,0x6c,0x6f,0x61,0x64,0x3d,0x22,0x6d,0x69,0x63,0x72,0x6f,0x62,0x69,0x74,0x2e,0x63,0x73,0x76,0x22,0x2c,0x65,0x2e,0x68,0x72,0x65,0x66,0x3d,0x55,0x52,0x4c,0x2e,0x63,0x72,0x65,0x61,0x74,0x65,0x4f,0x62,0x6a,0x65,0x63,0x74,0x55,0x52,0x4c,0x28,0x6e,0x65,0x77,0x20,0x42,0x6c,0x6f,0x62,0x28,0x5b,0x63,0x73,0x76,0x5d,0x2c,0x7b,0x74,0x79,0x70,0x65,0x3a,0x22,0x74,0x65,0x78,0x74,0x2f,0x70,0x6c,0x61,0x69,0x6e,0x22,0x7d,0x29,0x29,0x2c,0x65,0x2e,0x63,0x6c,0x69,0x63,0x6b,0x28,0x29,0x2c,0x65,0x2e,0x72,0x65,0x6d,0x6f,0x76,0x65,0x28,0x29,0x7d,0x2c,0x63,0x6f,0x70,0x79,0x3a,0x66,0x75,0x6e,0x63,0x74,0x69,0x6f,0x6e,0x28,0x29,0x7b,0x6e,0x61,0x76,0x69,0x67,0x61,0x74,0x6f,0x72,0x2e,0x63,0x6c,0x69,0x70,0x62,0x6f,0x61,0x72,0x64,0x2e,0x77,0x72,0x69,0x74,0x65,0x54,0x65,0x78,0x74,0x28,0x63,0x73,0x76,0x2e,0x72,0x65,0x70,0x6c,0x61,0x63,0x65,0x28,0x2f,0x5c,0x2c,0x2f,0x67,0x2c,0x22,0x5c,0x74,0x22,0x29,0x29,0x7d,0x2c,0x75,0x70,0x64,0x61,0x74,0x65,0x3a,0x61,0x6c,0x65,0x72,0x74,0x2e,0x62,0x69,0x6e,0x64,0x28,0x6e,0x2c,0x22,0x55,0x6e,0x70,0x6c,0x75,0x67,0x20,0x79,0x6f,0x75,0x72,0x20,0x6d,0x69,0x63,0x72,0x6f,0x3a,0x62,0x69,0x74,0x2c,0x20,0x74,0x68,0x65,0x6e,0x20,0x70,0x6c,0x75,0x67,0x20,0x69,0x74,0x20,0x62,0x61,0x63,0x6b,0x20,0x69,0x6e,0x20,0x61,0x6e,0x64,0x20,0x77,0x61,0x69,0x74,0x22,0x29,0x2c,0x63,0x6c,0x65,0x61,0x72,0x3a,0x61,0x6c,0x65,0x72,0x74,0x2e,0x62,0x69,0x6e,0x64,0x28,0x6e,0x2c,0x22,0x54,0x68,0x65,0x20,0x6c,0x6f,0x67,0x20,0x69,0x73,0x20,0x63,0x6c,0x65,0x61,0x72,0x65,0x64,0x20,0x77,0x68,0x65,0x6e,0x20,0x79,0x6f,0x75,0x20,0x72,0x65,0x66,0x6c,0x61,0x73,0x68,0x20,0x79,0x6f,0x75,0x72,0x20,0x6d,0x69,0x63,0x72,0x6f,0x3a,0x62,0x69,0x74,0x22,0x29,0x2c,0x6c,0x6f,0x61,0x64,0x3a,0x66,0x75,0x6e,0x63,0x74,0x69,0x6f,0x6e,0x28,0x29,0x7b,0x6c,0x65,0x74,0x20,0x72,0x3d,0x64,0x2e,0x71,0x75,0x65,0x72,0x79,0x53,0x65,0x6c,0x65,0x63,0x74,0x6f,0x72,0x28,0x22,0x23,0x77,0x22,0x29,0x2c,0x61,0x3d,0x64,0x2e,0x64,0x6f,0x63,0x75,0x6d,0x65,0x6e,0x74,0x45,0x6c,0x65,0x6d,0x65,0x6e,0x74,0x2e,0x6f,0x75,0x74,0x65,0x72,0x48,0x54,0x4d,0x4c,0x2e,0x73,0x70,0x6c,0x69,0x74,0x28,0x22,0x46,0x53,0x5f,0x53,0x54,0x41,0x52,0x54,0x22,0x29,0x5b,0x32,0x5d,0x3b,0x69,0x66,0x28,0x2f,0x5e,0x55,0x42,0x49,0x54,0x5f,0x4c,0x4f,0x47,0x5f,0x46,0x53,0x5f,0x56,0x5f,0x30,0x30,0x31,0x2f,0x2e,0x74,0x65,0x73,0x74,0x28,0x61,0x29,0x29,0x7b,0x76,0x61,0x72,0x20,0x6e,0x3d,0x70,0x61,0x72,0x73,0x65,0x49,0x6e,0x74,0x28,0x61,0x2e,0x73,0x75,0x62,0x73,0x74,0x72,0x28,0x32,0x39,0x2c,0x31,0x30,0x29,0x2c,0x31,0x36,0x29,0x2d,0x32,0x30,0x34,0x38,0x3b,0x6c,0x65,0x74,0x20,0x65,0x3d,0x30,0x3b,0x66,0x6f,0x72,0x28,0x3b,0x36,0x35,0x35,0x33,0x33,0x21,0x3d,0x61,0x2e,0x63,0x68,0x61,0x72,0x43,0x6f,0x64,0x65,0x41,0x74,0x28,0x6e,0x2b,0x65,0x29,0x3b,0x29,0x65,0x2b,0x2b,0x3b,0x63,0x73,0x76,0x3d,0x61,0x2e,0x73,0x75,0x62,0x73,0x74,0x72,0x28,0x6e,0x2c,0x65,0x29,0x3b,0x6c,0x65,0x74,0x20,0x74,0x3d,0x30,0x3b,0x66,0x6f,0x72,0x28,0x6c,0x65,0x74,0x20,0x65,0x3d,0x30,0x3b,0x65,0x3c,0x61,0x2e,0x6c,0x65,0x6e,0x67,0x74,0x68,0x3b,0x2b,0x2b,0x65,0x29,0x74,0x3d,0x33,0x31,0x2a,0x74,0x2b,0x61,0x2e,0x63,0x68,0x61,0x72,0x43,0x6f,0x64,0x65,0x41,0x74,0x28,0x65,0x29,0x2c,0x74,0x7c,0x3d,0x30,0x3b,0x76,0x61,0x72,0x20,0x6f,0x3d,0x6c,0x2e,0x68,0x72,0x65,0x66,0x2e,0x73,0x70,0x6c,0x69,0x74,0x28,0x22,0x3f,0x22,0x29,0x5b,0x31,0x5d,0x3b,0x69,0x66,0x28,0x76,0x6f,0x69,0x64,0x20,0x30,0x21,0x3d,0x3d,0x6f,0x29,0x6f,0x21,0x3d,0x74,0x26,0x26,0x70,0x61,0x72,0x65,0x6e,0x74,0x2e,0x70,0x6f,0x73,0x74,0x4d,0x65,0x73,0x73,0x61,0x67,0x65,0x28,0x22,0x64,0x69,0x66,0x66,0x22,0x2c,0x22,0x2a,0x22,0x29,0x3b,0x65,0x6c,0x73,0x65,0x7b,0x6f,0x3d,0x70,0x61,0x72,0x73,0x65,0x49,0x6e,0x74,0x28,0x61,0x2e,0x73,0x75,0x62,0x73,0x74,0x72,0x28,0x31,0x38,0x2c,0x31,0x30,0x29,0x2c,0x31,0x36,0x29,0x3b,0x22,0x46,0x55,0x4c,0x22,0x3d,0x3d,0x3d,0x61,0x2e,0x73,0x75,0x62,0x73,0x74,0x72,0x28,0x6f,0x2d,0x32,0x30,0x34,0x38,0x2b,0x31,0x2c,0x33,0x29,0x26,0x26,0x28,0x72,0x2e,0x61,0x70,0x70,0x65,0x6e,0x64,0x43,0x68,0x69,0x6c,0x64,0x28,0x74,0x61,0x67,0x28,0x22,0x70,0x22,0x29,0x29,0x2e,0x69,0x6e,0x6e,0x65,0x72,0x54,0x65,0x78,0x74,0x3d,0x22,0x4c,0x4f,0x47,0x20,0x46,0x55,0x4c,0x4c,0x22,0x29,0x3b,0x6c,0x65,0x74,0x20,0x6e,0x3d,0x72,0x2e,0x61,0x70,0x70,0x65,0x6e,0x64,0x43,0x68,0x69,0x6c,0x64,0x28,0x74,0x61,0x67,0x28,0x22,0x74,0x61,0x62,0x6c,0x65,0x22,0x29,0x29,0x3b,0x63,0x73,0x76,0x2e,0x73,0x70,0x6c,0x69,0x74,0x28,0x22,0x5c,0x6e,0x22,0x29,0x2e,0x66,0x6f,0x72,0x45,0x61,0x63,0x68,0x28,0x66,0x75,0x6e,0x63,0x74,0x69,0x6f,0x6e,0x28,0x65,0x29,0x7b,0x6c,0x65,0x74,0x20,0x74,0x3d,0x6e,0x2e,0x69,0x6e,0x73,0x65,0x72,0x74,0x52,0x6f,0x77,0x28,0x29,0x3b,0x65,0x26,0x26,0x65,0x2e,0x73,0x70,0x6c,0x69,0x74,0x28,0x22,0x2c,0x22,0x29,0x2e,0x66,0x6f,0x72,0x45,0x61,0x63,0x68,0x28,0x66,0x75,0x6e,0x63,0x74,0x69,0x6f,0x6e,0x28,0x65,0x29,0x7b,0x74,0x2e,0x69,0x6e,0x73,0x65,0x72,0x74,0x43,0x65,0x6c,0x6c,0x28,0x29,0x2e,0x69,0x6e,0x6e,0x65,0x72,0x54,0x65,0x78,0x74,0x3d,0x65,0x7d,0x29,0x7d,0x29,0x2c,0x77,0x2e,0x6f,0x6e,0x6d,0x65,0x73,0x73,0x61,0x67,0x65,0x3d,0x66,0x75,0x6e,0x63,0x74,0x69,0x6f,0x6e,0x28,0x65,0x29,0x7b,0x22,0x64,0x69,0x66,0x66,0x22,0x3d,0x3d,0x65,0x2e,0x64,0x61,0x74,0x61,0x26,0x26,0x6c,0x2e,0x72,0x65,0x6c,0x6f,0x61,0x64,0x28,0x29,0x7d,0x3b,0x6c,0x65,0x74,0x20,0x65,0x3b,0x73,0x65,0x74,0x49,0x6e,0x74,0x65,0x72,0x76,0x61,0x6c,0x28,0x66,0x75,0x6e,0x63,0x74,0x69,0x6f,0x6e,0x28,0x29,0x7b,0x65,0x26,0x26,0x65,0x2e,0x72,0x65,0x6d,0x6f,0x76,0x65,0x28,0x29,0x2c,0x65,0x3d,0x72,0x2e,0x61,0x70,0x70,0x65,0x6e,0x64,0x43,0x68,0x69,0x6c,0x64,0x28,0x74,0x61,0x67,0x28,0x22,0x69,0x66,0x72,0x61,0x6d,0x65,0x22,0x29,0x29,0x2c,0x65,0x2e,0x73,0x72,0x63,0x3d,0x6c,0x2e,0x68,0x72,0x65,0x66,0x2b,0x22,0x3f,0x22,0x2b,0x74,0x7d,0x2c,0x35,0x65,0x33,0x29,0x7d,0x7d,0x7d,0x7d,0x3c,0x2f,0x73,0x63,0x72,0x69,0x70,0x74,0x3e,0x3c,0x73,0x63,0x72,0x69,0x70,0x74,0x20,0x73,0x72,0x63,0x3d,0x68,0x74,0x74,0x70,0x73,0x3a,0x2f,0x2f,0x6d,0x69,0x63,0x72,0x6f,0x62,0x69,0x74,0x2e,0x6f,0x72,0x67,0x2f,0x64,0x6c,0x2f,0x32,0x2f,0x64,0x6c,0x2e,0x6a,0x73,0x3e,0x3c,0x2f,0x73,0x63,0x72,0x69,0x70,0x74,0x3e,0x3c,0x74,0x69,0x74,0x6c,0x65,0x3e,0x6d,0x69,0x63,0x72,0x6f,0x3a,0x62,0x69,0x74,0x20,0x64,0x61,0x74,0x61,0x20,0x6c,0x6f,0x67,0x3c,0x2f,0x74,0x69,0x74,0x6c,0x65,0x3e,0x3c,0x62,0x6f,0x64,0x79,0x20,0x6f,0x6e,0x6c,0x6f,0x61,0x64,0x3d,0x64,0x6c,0x2e,0x6c,0x6f,0x61,0x64,0x28,0x29,0x3e,0x3c,0x64,0x69,0x76,0x20,0x69,0x64,0x3d,0x77,0x3e,0x3c,0x68,0x31,0x3e,0x6d,0x69,0x63,0x72,0x6f,0x3a,0x62,0x69,0x74,0x20,0x64,0x61,0x74,0x61,0x20,0x6c,0x6f,0x67,0x3c,0x2f,0x68,0x31,0x3e,0x3c,0x64,0x69,0x76,0x20,0x63,0x6c,0x61,0x73,0x73,0x3d,0x62,0x62,0x3e,0x3c,0x62,0x75,0x74,0x74,0x6f,0x6e,0x20,0x6f,0x6e,0x63,0x6c,0x69,0x63,0x6b,0x3d,0x64,0x6c,0x2e,0x64,0x6f,0x77,0x6e,0x6c,0x6f,0x61,0x64,0x28,0x29,0x3e,0x44,0x6f,0x77,0x6e,0x6c,0x6f,0x61,0x64,0x3c,0x2f,0x62,0x75,0x74,0x74,0x6f,0x6e,0x3e,0x3c,0x62,0x75,0x74,0x74,0x6f,0x6e,0x20,0x6f,0x6e,0x63,0x6c,0x69,0x63,0x6b,0x3d,0x64,0x6c,0x2e,0x63,0x6f,0x70,0x79,0x28,0x29,0x3e,0x43,0x6f,0x70,0x79,0x3c,0x2f,0x62,0x75,0x74,0x74,0x6f,0x6e,0x3e,0x3c,0x62,0x75,0x74,0x74,0x6f,0x6e,0x20,0x6f,0x6e,0x63,0x6c,0x69,0x63,0x6b,0x3d,0x64,0x6c,0x2e,0x75,0x70,0x64,0x61,0x74,0x65,0x28,0x29,0x3e,0x55,0x70,0x64,0x61,0x74,0x65,0x20,0x64,0x61,0x74,0x61,0x26,0x6d,0x6c,0x64,0x72,0x3b,0x3c,0x2f,0x62,0x75,0x74,0x74,0x6f,0x6e,0x3e,0x3c,0x62,0x75,0x74,0x74,0x6f,0x6e,0x20,0x6f,0x6e,0x63,0x6c,0x69,0x63,0x6b,0x3d,0x64,0x6c,0x2e,0x63,0x6c,0x65,0x61,0x72,0x28,0x29,0x3e,0x43,0x6c,0x65,0x61,0x72,0x20,0x6c,0x6f,0x67,0x26,0x6d,0x6c,0x64,0x72,0x3b,0x3c,0x2f,0x62,0x75,0x74,0x74,0x6f,0x6e,0x3e,0x3c,0x2f,0x64,0x69,0x76,0x3e,0x3c,0x70,0x20,0x69,0x64,0x3d,0x76,0x3e,0x4f,0x66,0x66,0x6c,0x69,0x6e,0x65,0x3a,0x20,0x6e,0x6f,0x20,0x76,0x69,0x73,0x75,0x61,0x6c,0x20,0x70,0x72,0x65,0x76,0x69,0x65,0x77,0x3c,0x2f,0x64,0x69,0x76,0x3e,0x3c,0x21,0x2d,0x2d,0x46,0x53,0x5f,0x53,0x54,0x41,0x52,0x54}; ",16261,True,3707.167525276936,median "//// AUTOGENERATED FILE - this file was generated via https://github.com/jboss-container-images/jboss-kie-modules/blob/master/tools/gen-template-doc/gen_template_docs.py. Changes to .adoc or HTML files may be overwritten! Please change the generator or the input template (https://github.com/jboss-container-images/jboss-kie-modules/tree/master/tools/gen-template-doc/*.in) //// [id='rhdm78-authoring-ha-ref_{context}'] = rhdm78-authoring-ha.yaml template Application template for a HA persistent authoring environment, for Red Hat Decision Manager 7.8 - Deprecated == Parameters Templates allow you to define parameters that take on a value. That value is then substituted wherever the parameter is referenced. References can be defined in any text field in the objects list field. See the https://access.redhat.com/documentation/en-us/openshift_container_platform/3.11/html-single/developer_guide/#dev-guide-templates[Openshift documentation] for more information. |======================================================================= |Variable name |Image Environment Variable |Description |Example value |Required |`APPLICATION_NAME` | -- | The name for the application. | myapp | True |`CREDENTIALS_SECRET` | -- | Secret containing the KIE_ADMIN_USER and KIE_ADMIN_PWD values. | rhpam-credentials | True |`KIE_SERVER_CONTROLLER_TOKEN` | `KIE_SERVER_CONTROLLER_TOKEN` | KIE server controller token for bearer authentication. (Sets the org.kie.server.controller.token system property) | -- | False |`KIE_SERVER_BYPASS_AUTH_USER` | `KIE_SERVER_BYPASS_AUTH_USER` | Allows the KIE server to bypass the authenticated user for task-related operations, for example, queries. (Sets the org.kie.server.bypass.auth.user system property) | false | False |`KIE_SERVER_MODE` | `KIE_SERVER_MODE` | The KIE Server mode. Valid values are 'DEVELOPMENT' or 'PRODUCTION'. In production mode, you can not deploy SNAPSHOT versions of artifacts on the KIE server and can not change the version of an artifact in an existing container. (Sets the org.kie.server.mode system property). | `DEVELOPMENT` | False |`KIE_MBEANS` | `KIE_MBEANS` | KIE server mbeans enabled/disabled. (Sets the kie.mbeans and kie.scanner.mbeans system properties) | enabled | False |`DROOLS_SERVER_FILTER_CLASSES` | `DROOLS_SERVER_FILTER_CLASSES` | KIE server class filtering. (Sets the org.drools.server.filter.classes system property) | true | False |`PROMETHEUS_SERVER_EXT_DISABLED` | `PROMETHEUS_SERVER_EXT_DISABLED` | If set to false, the prometheus server extension will be enabled. (Sets the org.kie.prometheus.server.ext.disabled system property) | false | False |`DECISION_CENTRAL_HOSTNAME_HTTP` | `HOSTNAME_HTTP` | Custom hostname for http service route for Decision Central. Leave blank for default hostname, e.g.: insecure--rhdmcentr-. | -- | False |`DECISION_CENTRAL_HOSTNAME_HTTPS` | `HOSTNAME_HTTPS` | Custom hostname for https service route for Decision Central. Leave blank for default hostname, e.g.: -rhdmcentr-. | -- | False |`KIE_SERVER_HOSTNAME_HTTP` | `HOSTNAME_HTTP` | Custom hostname for http service route for KIE Server. Leave blank for default hostname, e.g.: insecure--kieserver-. | -- | False |`KIE_SERVER_HOSTNAME_HTTPS` | `HOSTNAME_HTTPS` | Custom hostname for https service route for KIE Server. Leave blank for default hostname, e.g.: -kieserver-. | -- | False |`DECISION_CENTRAL_HTTPS_SECRET` | -- | The name of the secret containing the keystore file for Decision Central. | decisioncentral-app-secret | True |`DECISION_CENTRAL_HTTPS_KEYSTORE` | `HTTPS_KEYSTORE` | The name of the keystore file within the secret for Decision Central. | keystore.jks | False |`DECISION_CENTRAL_HTTPS_NAME` | `HTTPS_NAME` | The name associated with the server certificate for Decision Central. | jboss | False |`DECISION_CENTRAL_HTTPS_PASSWORD` | `HTTPS_PASSWORD` | The password for the keystore and certificate for Decision Central. | mykeystorepass | False |`KIE_SERVER_HTTPS_SECRET` | -- | The name of the secret containing the keystore file for KIE Server. | kieserver-app-secret | True |`KIE_SERVER_HTTPS_KEYSTORE` | `HTTPS_KEYSTORE` | The name of the keystore file within the secret for KIE Server. | keystore.jks | False |`KIE_SERVER_HTTPS_NAME` | `HTTPS_NAME` | The name associated with the server certificate for KIE Server. | jboss | False |`KIE_SERVER_HTTPS_PASSWORD` | `HTTPS_PASSWORD` | The password for the keystore and certificate for KIE Server. | mykeystorepass | False |`APPFORMER_JMS_BROKER_USER` | `APPFORMER_JMS_BROKER_USER` | The user name to connect to the JMS broker. | jmsBrokerUser | True |`APPFORMER_JMS_BROKER_PASSWORD` | `APPFORMER_JMS_BROKER_PASSWORD` | The password to connect to the JMS broker. | -- | True |`DATAGRID_IMAGE` | -- | DataGrid image. | registry.redhat.io/jboss-datagrid-7/datagrid73-openshift:1.5 | True |`DATAGRID_CPU_LIMIT` | -- | DataGrid Container CPU limit. | 1000m | True |`DATAGRID_MEMORY_LIMIT` | -- | DataGrid Container memory limit. | 2Gi | True |`DATAGRID_VOLUME_CAPACITY` | -- | Size of the persistent storage for DataGrid's runtime data. | 1Gi | True |`AMQ_BROKER_IMAGE` | -- | AMQ Broker Image | registry.redhat.io/amq7/amq-broker:7.6 | True |`AMQ_ROLE` | -- | User role for standard broker user. | admin | True |`AMQ_NAME` | -- | The name of the broker. | broker | True |`AMQ_GLOBAL_MAX_SIZE` | -- | Specifies the maximum amount of memory that message data can consume. If no value is specified, half of the system's memory is allocated. | 10 gb | False |`AMQ_VOLUME_CAPACITY` | -- | Size of persistent storage for AMQ broker volume. | 1Gi | True |`AMQ_REPLICAS` | -- | Number of broker replicas for a cluster | 2 | True |`DECISION_CENTRAL_CONTAINER_REPLICAS` | -- | Decision Central Container Replicas, defines how many Decision Central containers will be started. | 2 | True |`KIE_SERVER_CONTAINER_REPLICAS` | -- | KIE Server Container Replicas, defines how many KIE Server containers will be started. | 2 | True |`KIE_SERVER_CONTROLLER_OPENSHIFT_GLOBAL_DISCOVERY_ENABLED` | `KIE_SERVER_CONTROLLER_OPENSHIFT_GLOBAL_DISCOVERY_ENABLED` | If set to true, turns on KIE server global discovery feature (Sets the org.kie.server.controller.openshift.global.discovery.enabled system property) | false | False |`KIE_SERVER_CONTROLLER_OPENSHIFT_PREFER_KIESERVER_SERVICE` | `KIE_SERVER_CONTROLLER_OPENSHIFT_PREFER_KIESERVER_SERVICE` | If OpenShift integration of Business Central is turned on, setting this parameter to true enables connection to KIE Server via an OpenShift internal Service endpoint. (Sets the org.kie.server.controller.openshift.prefer.kieserver.service system property) | true | False |`KIE_SERVER_CONTROLLER_TEMPLATE_CACHE_TTL` | `KIE_SERVER_CONTROLLER_TEMPLATE_CACHE_TTL` | KIE ServerTemplate Cache TTL in milliseconds. (Sets the org.kie.server.controller.template.cache.ttl system property) | 60000 | False |`IMAGE_STREAM_NAMESPACE` | -- | Namespace in which the ImageStreams for Red Hat Decision Manager images are installed. These ImageStreams are normally installed in the openshift namespace. You need to modify this parameter only if you installed the ImageStreams in a different namespace/project. | openshift | True |`DECISION_CENTRAL_IMAGE_STREAM_NAME` | -- | The name of the image stream to use for Decision Central. Default is ""rhdm-decisioncentral-rhel8"". | rhdm-decisioncentral-rhel8 | True |`KIE_SERVER_IMAGE_STREAM_NAME` | -- | The name of the image stream to use for KIE server. Default is ""rhdm-kieserver-rhel8"". | rhdm-kieserver-rhel8 | True |`IMAGE_STREAM_TAG` | -- | A named pointer to an image in an image stream. Default is ""7.8.0"". | 7.8.0 | True |`MAVEN_MIRROR_URL` | `MAVEN_MIRROR_URL` | Maven mirror that Decision Central and KIE server must use. If you configure a mirror, this mirror must contain all artifacts that are required for building and deploying your services. | -- | False |`MAVEN_MIRROR_OF` | `MAVEN_MIRROR_OF` | Maven mirror configuration for KIE server. | external:*,!repo-rhdmcentr | False |`MAVEN_REPO_ID` | `MAVEN_REPO_ID` | The id to use for the maven repository. If set, it can be excluded from the optionally configured mirror by adding it to MAVEN_MIRROR_OF. For example: external:*,!repo-rhdmcentr,!repo-custom. If MAVEN_MIRROR_URL is set but MAVEN_MIRROR_ID is not set, an id will be generated randomly, but won't be usable in MAVEN_MIRROR_OF. | repo-custom | False |`MAVEN_REPO_URL` | `MAVEN_REPO_URL` | Fully qualified URL to a Maven repository or service. | \\http://nexus.nexus-project.svc.cluster.local:8081/nexus/content/groups/public/ | False |`MAVEN_REPO_USERNAME` | `MAVEN_REPO_USERNAME` | User name for accessing the Maven repository, if required. | -- | False |`MAVEN_REPO_PASSWORD` | `MAVEN_REPO_PASSWORD` | Password to access the Maven repository, if required. | -- | False |`GIT_HOOKS_DIR` | `GIT_HOOKS_DIR` | The directory to use for git hooks, if required. | `/opt/kie/data/git/hooks` | False |`DECISION_CENTRAL_VOLUME_CAPACITY` | -- | Size of the persistent storage for Decision Central's runtime data. | 1Gi | True |`DECISION_CENTRAL_MEMORY_LIMIT` | -- | Decision Central Container memory limit. | 8Gi | True |`DECISION_CENTRAL_JAVA_MAX_MEM_RATIO` | `JAVA_MAX_MEM_RATIO` | Decision Central Container JVM max memory ratio. `-Xmx` is set to a ratio of the memory available on the container. The default is 80, which means the upper boundary is 80% of the available memory. To skip adding the `-Xmx` option, set this value to 0. | 80 | True |`DECISION_CENTRAL_CPU_LIMIT` | -- | Decision Central Container CPU limit. | 2000m | True |`KIE_SERVER_MEMORY_LIMIT` | -- | KIE server Container memory limit. | 1Gi | True |`KIE_SERVER_CPU_LIMIT` | -- | KIE server Container CPU limit. | 1000m | True |`SSO_URL` | `SSO_URL` | RH-SSO URL. | \\https://rh-sso.example.com/auth | False |`SSO_REALM` | `SSO_REALM` | RH-SSO Realm name. | -- | False |`DECISION_CENTRAL_SSO_CLIENT` | `SSO_CLIENT` | Decision Central RH-SSO Client name. | -- | False |`DECISION_CENTRAL_SSO_SECRET` | `SSO_SECRET` | Decision Central RH-SSO Client Secret. | 252793ed-7118-4ca8-8dab-5622fa97d892 | False |`KIE_SERVER_SSO_CLIENT` | `SSO_CLIENT` | KIE Server RH-SSO Client name. | -- | False |`KIE_SERVER_SSO_SECRET` | `SSO_SECRET` | KIE Server RH-SSO Client Secret. | 252793ed-7118-4ca8-8dab-5622fa97d892 | False |`SSO_USERNAME` | `SSO_USERNAME` | RH-SSO Realm admin user name used to create the Client if it doesn't exist. | -- | False |`SSO_PASSWORD` | `SSO_PASSWORD` | RH-SSO Realm Admin Password used to create the Client. | -- | False |`SSO_DISABLE_SSL_CERTIFICATE_VALIDATION` | `SSO_DISABLE_SSL_CERTIFICATE_VALIDATION` | RH-SSO Disable SSL Certificate Validation. | false | False |`SSO_PRINCIPAL_ATTRIBUTE` | `SSO_PRINCIPAL_ATTRIBUTE` | RH-SSO Principal Attribute to use as user name. | preferred_username | False |`AUTH_LDAP_URL` | `AUTH_LDAP_URL` | LDAP Endpoint to connect for authentication. | ldap://myldap.example.com | False |`AUTH_LDAP_BIND_DN` | `AUTH_LDAP_BIND_DN` | Bind DN used for authentication. | uid=admin,ou=users,ou=example,ou=com | False |`AUTH_LDAP_BIND_CREDENTIAL` | `AUTH_LDAP_BIND_CREDENTIAL` | LDAP Credentials used for authentication. | Password | False |`AUTH_LDAP_JAAS_SECURITY_DOMAIN` | `AUTH_LDAP_JAAS_SECURITY_DOMAIN` | The JMX ObjectName of the JaasSecurityDomain used to decrypt the password. | -- | False |`AUTH_LDAP_BASE_CTX_DN` | `AUTH_LDAP_BASE_CTX_DN` | LDAP Base DN of the top-level context to begin the user search. | ou=users,ou=example,ou=com | False |`AUTH_LDAP_BASE_FILTER` | `AUTH_LDAP_BASE_FILTER` | LDAP search filter used to locate the context of the user to authenticate. The input username or userDN obtained from the login module callback is substituted into the filter anywhere a {0} expression is used. A common example for the search filter is (uid={0}). | (uid={0}) | False |`AUTH_LDAP_SEARCH_SCOPE` | `AUTH_LDAP_SEARCH_SCOPE` | The search scope to use. | `SUBTREE_SCOPE` | False |`AUTH_LDAP_SEARCH_TIME_LIMIT` | `AUTH_LDAP_SEARCH_TIME_LIMIT` | The timeout in milliseconds for user or role searches. | 10000 | False |`AUTH_LDAP_DISTINGUISHED_NAME_ATTRIBUTE` | `AUTH_LDAP_DISTINGUISHED_NAME_ATTRIBUTE` | The name of the attribute in the user entry that contains the DN of the user. This may be necessary if the DN of the user itself contains special characters, backslash for example, that prevent correct user mapping. If the attribute does not exist, the entry's DN is used. | distinguishedName | False |`AUTH_LDAP_PARSE_USERNAME` | `AUTH_LDAP_PARSE_USERNAME` | A flag indicating if the DN is to be parsed for the user name. If set to true, the DN is parsed for the user name. If set to false the DN is not parsed for the user name. This option is used together with usernameBeginString and usernameEndString. | true | False |`AUTH_LDAP_USERNAME_BEGIN_STRING` | `AUTH_LDAP_USERNAME_BEGIN_STRING` | Defines the String which is to be removed from the start of the DN to reveal the user name. This option is used together with usernameEndString and only taken into account if parseUsername is set to true. | -- | False |`AUTH_LDAP_USERNAME_END_STRING` | `AUTH_LDAP_USERNAME_END_STRING` | Defines the String which is to be removed from the end of the DN to reveal the user name. This option is used together with usernameEndString and only taken into account if parseUsername is set to true. | -- | False |`AUTH_LDAP_ROLE_ATTRIBUTE_ID` | `AUTH_LDAP_ROLE_ATTRIBUTE_ID` | Name of the attribute containing the user roles. | memberOf | False |`AUTH_LDAP_ROLES_CTX_DN` | `AUTH_LDAP_ROLES_CTX_DN` | The fixed DN of the context to search for user roles. This is not the DN where the actual roles are, but the DN where the objects containing the user roles are. For example, in a Microsoft Active Directory server, this is the DN where the user account is. | ou=groups,ou=example,ou=com | False |`AUTH_LDAP_ROLE_FILTER` | `AUTH_LDAP_ROLE_FILTER` | A search filter used to locate the roles associated with the authenticated user. The input username or userDN obtained from the login module callback is substituted into the filter anywhere a {0} expression is used. The authenticated userDN is substituted into the filter anywhere a {1} is used. An example search filter that matches on the input username is (member={0}). An alternative that matches on the authenticated userDN is (member={1}). | (memberOf={1}) | False |`AUTH_LDAP_ROLE_RECURSION` | `AUTH_LDAP_ROLE_RECURSION` | The number of levels of recursion the role search will go below a matching context. Disable recursion by setting this to 0. | 1 | False |`AUTH_LDAP_DEFAULT_ROLE` | `AUTH_LDAP_DEFAULT_ROLE` | A role included for all authenticated users | user | False |`AUTH_LDAP_ROLE_NAME_ATTRIBUTE_ID` | `AUTH_LDAP_ROLE_NAME_ATTRIBUTE_ID` | Name of the attribute within the roleCtxDN context which contains the role name. If the roleAttributeIsDN property is set to true, this property is used to find the role object's name attribute. | name | False |`AUTH_LDAP_PARSE_ROLE_NAME_FROM_DN` | `AUTH_LDAP_PARSE_ROLE_NAME_FROM_DN` | A flag indicating if the DN returned by a query contains the roleNameAttributeID. If set to true, the DN is checked for the roleNameAttributeID. If set to false, the DN is not checked for the roleNameAttributeID. This flag can improve the performance of LDAP queries. | false | False |`AUTH_LDAP_ROLE_ATTRIBUTE_IS_DN` | `AUTH_LDAP_ROLE_ATTRIBUTE_IS_DN` | Whether or not the roleAttributeID contains the fully-qualified DN of a role object. If false, the role name is taken from the value of the roleNameAttributeId attribute of the context name. Certain directory schemas, such as Microsoft Active Directory, require this attribute to be set to true. | false | False |`AUTH_LDAP_REFERRAL_USER_ATTRIBUTE_ID_TO_CHECK` | `AUTH_LDAP_REFERRAL_USER_ATTRIBUTE_ID_TO_CHECK` | If you are not using referrals, you can ignore this option. When using referrals, this option denotes the attribute name which contains users defined for a certain role, for example member, if the role object is inside the referral. Users are checked against the content of this attribute name. If this option is not set, the check will always fail, so role objects cannot be stored in a referral tree. | -- | False |`AUTH_ROLE_MAPPER_ROLES_PROPERTIES` | `AUTH_ROLE_MAPPER_ROLES_PROPERTIES` | When present, the RoleMapping Login Module will be configured to use the provided file. This parameter defines the fully-qualified file path and name of a properties file or resource which maps roles to replacement roles. The format is original_role=role1,role2,role3 | -- | False |`AUTH_ROLE_MAPPER_REPLACE_ROLE` | `AUTH_ROLE_MAPPER_REPLACE_ROLE` | Whether to add to the current roles, or replace the current roles with the mapped ones. Replaces if set to true. | -- | False |======================================================================= == Objects The CLI supports various object types. A list of these object types as well as their abbreviations can be found in the https://access.redhat.com/documentation/en-us/openshift_container_platform/3.11/html/cli_reference/cli-reference-basic-cli-operations#object-types[Openshift documentation]. === Services A service is an abstraction which defines a logical set of pods and a policy by which to access them. See the https://cloud.google.com/container-engine/docs/services/[container-engine documentation] for more information. |============= |Service |Port |Name | Description .2+| `${APPLICATION_NAME}-rhdmcentr` |8080 | http .2+| All the Decision Central web server's ports. |8443 | https .1+| `${APPLICATION_NAME}-rhdmcentr-ping` |8888 | ping .1+| The JGroups ping port for rhdmcentr clustering. .1+| `${APPLICATION_NAME}-datagrid-ping` |8888 | ping .1+| Provides a ping service for clustered applications. .1+| `${APPLICATION_NAME}-datagrid` |11222 | hotrod .1+| Provides a service for accessing the application over Hot Rod protocol. .2+| `${APPLICATION_NAME}-kieserver` |8080 | http .2+| All the KIE server web server's ports. |8443 | https .1+| `${APPLICATION_NAME}-amq-tcp` |61616 | -- .1+| The broker's OpenWire port. .1+| `ping` |8888 | -- .1+| The JGroups ping port for amq clustering. |============= === Routes A route is a way to expose a service by giving it an externally reachable hostname such as `www.example.com`. A defined route and the endpoints identified by its service can be consumed by a router to provide named connectivity from external clients to your applications. Each route consists of a route name, service selector, and (optionally) security configuration. See the https://access.redhat.com/documentation/en-us/openshift_enterprise/3.2/html/architecture/core-concepts#architecture-core-concepts-routes[Openshift documentation] for more information. |============= | Service | Security | Hostname |insecure-${APPLICATION_NAME}-rhdmcentr-http | none | `${DECISION_CENTRAL_HOSTNAME_HTTP}` |`${APPLICATION_NAME}-rhdmcentr-https` | TLS passthrough | `${DECISION_CENTRAL_HOSTNAME_HTTPS}` |insecure-${APPLICATION_NAME}-kieserver-http | none | `${KIE_SERVER_HOSTNAME_HTTP}` |`${APPLICATION_NAME}-kieserver-https` | TLS passthrough | `${KIE_SERVER_HOSTNAME_HTTPS}` |============= === Deployment Configurations A deployment in OpenShift is a replication controller based on a user-defined template called a deployment configuration. Deployments are created manually or in response to triggered events. See the https://access.redhat.com/documentation/en-us/openshift_container_platform/3.11/html/developer_guide/deployments#dev-guide-how-deployments-work[Openshift documentation] for more information. ==== Triggers A trigger drives the creation of new deployments in response to events, both inside and outside OpenShift. See the https://access.redhat.com/documentation/en-us/openshift_container_platform/3.11/html/developer_guide/deployments#triggers[Openshift documentation] for more information. |============ |Deployment | Triggers |`${APPLICATION_NAME}-rhdmcentr` | ImageChange |`${APPLICATION_NAME}-kieserver` | ImageChange |============ ==== Replicas A replication controller ensures that a specified number of pod ""replicas"" are running at any one time. If there are too many, the replication controller kills some pods. If there are too few, it starts more. See the https://cloud.google.com/container-engine/docs/replicationcontrollers/[container-engine documentation] for more information. |============ |Deployment | Replicas |`${APPLICATION_NAME}-rhdmcentr` | 2 |`${APPLICATION_NAME}-kieserver` | 2 |============ ==== Pod Template ===== Service Accounts Service accounts are API objects that exist within each project. They can be created or deleted like any other API object. See the https://access.redhat.com/documentation/en-us/openshift_container_platform/3.11/html/developer_guide/dev-guide-service-accounts#dev-managing-service-accounts[Openshift documentation] for more information. |============ |Deployment | Service Account |`${APPLICATION_NAME}-rhdmcentr` | `${APPLICATION_NAME}-rhdmsvc` |`${APPLICATION_NAME}-kieserver` | `${APPLICATION_NAME}-rhdmsvc` |============ ===== Image |============ |Deployment | Image |`${APPLICATION_NAME}-rhdmcentr` | `${DECISION_CENTRAL_IMAGE_STREAM_NAME}` |`${APPLICATION_NAME}-kieserver` | `${KIE_SERVER_IMAGE_STREAM_NAME}` |============ ===== Readiness Probe .${APPLICATION_NAME}-rhdmcentr ---- Http Get on http://localhost:8080/rest/ready ---- .${APPLICATION_NAME}-kieserver ---- Http Get on http://localhost:8080/services/rest/server/readycheck ---- ===== Liveness Probe .${APPLICATION_NAME}-rhdmcentr ---- Http Get on http://localhost:8080/rest/healthy ---- .${APPLICATION_NAME}-kieserver ---- Http Get on http://localhost:8080/services/rest/server/healthcheck ---- ===== Exposed Ports |============= |Deployments | Name | Port | Protocol .4+| `${APPLICATION_NAME}-rhdmcentr` |jolokia | 8778 | `TCP` |http | 8080 | `TCP` |https | 8443 | `TCP` |ping | 8888 | `TCP` .3+| `${APPLICATION_NAME}-kieserver` |jolokia | 8778 | `TCP` |http | 8080 | `TCP` |https | 8443 | `TCP` |============= ===== Image Environment Variables |======================================================================= |Deployment |Variable name |Description |Example value .65+| `${APPLICATION_NAME}-rhdmcentr` |`APPLICATION_USERS_PROPERTIES` | -- | `/opt/kie/data/configuration/application-users.properties` |`APPLICATION_ROLES_PROPERTIES` | -- | `/opt/kie/data/configuration/application-roles.properties` |`KIE_ADMIN_USER` | Admin user name | Set according to the credentials secret |`KIE_ADMIN_PWD` | Admin user password | Set according to the credentials secret |`KIE_MBEANS` | KIE server mbeans enabled/disabled. (Sets the kie.mbeans and kie.scanner.mbeans system properties) | `${KIE_MBEANS}` |`KIE_SERVER_CONTROLLER_OPENSHIFT_ENABLED` | -- | true |`KIE_SERVER_CONTROLLER_OPENSHIFT_GLOBAL_DISCOVERY_ENABLED` | If set to true, turns on KIE server global discovery feature (Sets the org.kie.server.controller.openshift.global.discovery.enabled system property) | `${KIE_SERVER_CONTROLLER_OPENSHIFT_GLOBAL_DISCOVERY_ENABLED}` |`KIE_SERVER_CONTROLLER_OPENSHIFT_PREFER_KIESERVER_SERVICE` | If OpenShift integration of Business Central is turned on, setting this parameter to true enables connection to KIE Server via an OpenShift internal Service endpoint. (Sets the org.kie.server.controller.openshift.prefer.kieserver.service system property) | `${KIE_SERVER_CONTROLLER_OPENSHIFT_PREFER_KIESERVER_SERVICE}` |`KIE_SERVER_CONTROLLER_TEMPLATE_CACHE_TTL` | KIE ServerTemplate Cache TTL in milliseconds. (Sets the org.kie.server.controller.template.cache.ttl system property) | `${KIE_SERVER_CONTROLLER_TEMPLATE_CACHE_TTL}` |`KIE_SERVER_CONTROLLER_TOKEN` | KIE server controller token for bearer authentication. (Sets the org.kie.server.controller.token system property) | `${KIE_SERVER_CONTROLLER_TOKEN}` |`WORKBENCH_ROUTE_NAME` | -- | `${APPLICATION_NAME}-rhdmcentr` |`MAVEN_MIRROR_URL` | Maven mirror that Decision Central and KIE server must use. If you configure a mirror, this mirror must contain all artifacts that are required for building and deploying your services. | `${MAVEN_MIRROR_URL}` |`MAVEN_REPO_ID` | The id to use for the maven repository. If set, it can be excluded from the optionally configured mirror by adding it to MAVEN_MIRROR_OF. For example: external:*,!repo-rhdmcentr,!repo-custom. If MAVEN_MIRROR_URL is set but MAVEN_MIRROR_ID is not set, an id will be generated randomly, but won't be usable in MAVEN_MIRROR_OF. | `${MAVEN_REPO_ID}` |`MAVEN_REPO_URL` | Fully qualified URL to a Maven repository or service. | `${MAVEN_REPO_URL}` |`MAVEN_REPO_USERNAME` | User name for accessing the Maven repository, if required. | `${MAVEN_REPO_USERNAME}` |`MAVEN_REPO_PASSWORD` | Password to access the Maven repository, if required. | `${MAVEN_REPO_PASSWORD}` |`GIT_HOOKS_DIR` | The directory to use for git hooks, if required. | `${GIT_HOOKS_DIR}` |`HTTPS_KEYSTORE_DIR` | -- | `/etc/decisioncentral-secret-volume` |`HTTPS_KEYSTORE` | The name of the keystore file within the secret for Decision Central. | `${DECISION_CENTRAL_HTTPS_KEYSTORE}` |`HTTPS_NAME` | The name associated with the server certificate for Decision Central. | `${DECISION_CENTRAL_HTTPS_NAME}` |`HTTPS_PASSWORD` | The password for the keystore and certificate for Decision Central. | `${DECISION_CENTRAL_HTTPS_PASSWORD}` |`JGROUPS_PING_PROTOCOL` | -- | openshift.DNS_PING |`OPENSHIFT_DNS_PING_SERVICE_NAME` | -- | `${APPLICATION_NAME}-rhdmcentr-ping` |`OPENSHIFT_DNS_PING_SERVICE_PORT` | -- | 8888 |`APPFORMER_INFINISPAN_SERVICE_NAME` | -- | `${APPLICATION_NAME}-datagrid` |`APPFORMER_INFINISPAN_PORT` | -- | 11222 |`APPFORMER_JMS_BROKER_ADDRESS` | -- | `${APPLICATION_NAME}-amq-tcp` |`APPFORMER_JMS_BROKER_PORT` | -- | 61616 |`APPFORMER_JMS_BROKER_USER` | The user name to connect to the JMS broker. | `${APPFORMER_JMS_BROKER_USER}` |`APPFORMER_JMS_BROKER_PASSWORD` | The password to connect to the JMS broker. | `${APPFORMER_JMS_BROKER_PASSWORD}` |`JAVA_MAX_MEM_RATIO` | Decision Central Container JVM max memory ratio. `-Xmx` is set to a ratio of the memory available on the container. The default is 80, which means the upper boundary is 80% of the available memory. To skip adding the `-Xmx` option, set this value to 0. | `${DECISION_CENTRAL_JAVA_MAX_MEM_RATIO}` |`SSO_URL` | RH-SSO URL. | `${SSO_URL}` |`SSO_OPENIDCONNECT_DEPLOYMENTS` | -- | ROOT.war |`SSO_REALM` | RH-SSO Realm name. | `${SSO_REALM}` |`SSO_SECRET` | Decision Central RH-SSO Client Secret. | `${DECISION_CENTRAL_SSO_SECRET}` |`SSO_CLIENT` | Decision Central RH-SSO Client name. | `${DECISION_CENTRAL_SSO_CLIENT}` |`SSO_USERNAME` | RH-SSO Realm admin user name used to create the Client if it doesn't exist. | `${SSO_USERNAME}` |`SSO_PASSWORD` | RH-SSO Realm Admin Password used to create the Client. | `${SSO_PASSWORD}` |`SSO_DISABLE_SSL_CERTIFICATE_VALIDATION` | RH-SSO Disable SSL Certificate Validation. | `${SSO_DISABLE_SSL_CERTIFICATE_VALIDATION}` |`SSO_PRINCIPAL_ATTRIBUTE` | RH-SSO Principal Attribute to use as user name. | `${SSO_PRINCIPAL_ATTRIBUTE}` |`HOSTNAME_HTTP` | Custom hostname for http service route for Decision Central. Leave blank for default hostname, e.g.: insecure--rhdmcentr-. | `${DECISION_CENTRAL_HOSTNAME_HTTP}` |`HOSTNAME_HTTPS` | Custom hostname for https service route for Decision Central. Leave blank for default hostname, e.g.: -rhdmcentr-. | `${DECISION_CENTRAL_HOSTNAME_HTTPS}` |`AUTH_LDAP_URL` | LDAP Endpoint to connect for authentication. | `${AUTH_LDAP_URL}` |`AUTH_LDAP_BIND_DN` | Bind DN used for authentication. | `${AUTH_LDAP_BIND_DN}` |`AUTH_LDAP_BIND_CREDENTIAL` | LDAP Credentials used for authentication. | `${AUTH_LDAP_BIND_CREDENTIAL}` |`AUTH_LDAP_JAAS_SECURITY_DOMAIN` | The JMX ObjectName of the JaasSecurityDomain used to decrypt the password. | `${AUTH_LDAP_JAAS_SECURITY_DOMAIN}` |`AUTH_LDAP_BASE_CTX_DN` | LDAP Base DN of the top-level context to begin the user search. | `${AUTH_LDAP_BASE_CTX_DN}` |`AUTH_LDAP_BASE_FILTER` | LDAP search filter used to locate the context of the user to authenticate. The input username or userDN obtained from the login module callback is substituted into the filter anywhere a {0} expression is used. A common example for the search filter is (uid={0}). | `${AUTH_LDAP_BASE_FILTER}` |`AUTH_LDAP_SEARCH_SCOPE` | The search scope to use. | `${AUTH_LDAP_SEARCH_SCOPE}` |`AUTH_LDAP_SEARCH_TIME_LIMIT` | The timeout in milliseconds for user or role searches. | `${AUTH_LDAP_SEARCH_TIME_LIMIT}` |`AUTH_LDAP_DISTINGUISHED_NAME_ATTRIBUTE` | The name of the attribute in the user entry that contains the DN of the user. This may be necessary if the DN of the user itself contains special characters, backslash for example, that prevent correct user mapping. If the attribute does not exist, the entry's DN is used. | `${AUTH_LDAP_DISTINGUISHED_NAME_ATTRIBUTE}` |`AUTH_LDAP_PARSE_USERNAME` | A flag indicating if the DN is to be parsed for the user name. If set to true, the DN is parsed for the user name. If set to false the DN is not parsed for the user name. This option is used together with usernameBeginString and usernameEndString. | `${AUTH_LDAP_PARSE_USERNAME}` |`AUTH_LDAP_USERNAME_BEGIN_STRING` | Defines the String which is to be removed from the start of the DN to reveal the user name. This option is used together with usernameEndString and only taken into account if parseUsername is set to true. | `${AUTH_LDAP_USERNAME_BEGIN_STRING}` |`AUTH_LDAP_USERNAME_END_STRING` | Defines the String which is to be removed from the end of the DN to reveal the user name. This option is used together with usernameEndString and only taken into account if parseUsername is set to true. | `${AUTH_LDAP_USERNAME_END_STRING}` |`AUTH_LDAP_ROLE_ATTRIBUTE_ID` | Name of the attribute containing the user roles. | `${AUTH_LDAP_ROLE_ATTRIBUTE_ID}` |`AUTH_LDAP_ROLES_CTX_DN` | The fixed DN of the context to search for user roles. This is not the DN where the actual roles are, but the DN where the objects containing the user roles are. For example, in a Microsoft Active Directory server, this is the DN where the user account is. | `${AUTH_LDAP_ROLES_CTX_DN}` |`AUTH_LDAP_ROLE_FILTER` | A search filter used to locate the roles associated with the authenticated user. The input username or userDN obtained from the login module callback is substituted into the filter anywhere a {0} expression is used. The authenticated userDN is substituted into the filter anywhere a {1} is used. An example search filter that matches on the input username is (member={0}). An alternative that matches on the authenticated userDN is (member={1}). | `${AUTH_LDAP_ROLE_FILTER}` |`AUTH_LDAP_ROLE_RECURSION` | The number of levels of recursion the role search will go below a matching context. Disable recursion by setting this to 0. | `${AUTH_LDAP_ROLE_RECURSION}` |`AUTH_LDAP_DEFAULT_ROLE` | A role included for all authenticated users | `${AUTH_LDAP_DEFAULT_ROLE}` |`AUTH_LDAP_ROLE_NAME_ATTRIBUTE_ID` | Name of the attribute within the roleCtxDN context which contains the role name. If the roleAttributeIsDN property is set to true, this property is used to find the role object's name attribute. | `${AUTH_LDAP_ROLE_NAME_ATTRIBUTE_ID}` |`AUTH_LDAP_PARSE_ROLE_NAME_FROM_DN` | A flag indicating if the DN returned by a query contains the roleNameAttributeID. If set to true, the DN is checked for the roleNameAttributeID. If set to false, the DN is not checked for the roleNameAttributeID. This flag can improve the performance of LDAP queries. | `${AUTH_LDAP_PARSE_ROLE_NAME_FROM_DN}` |`AUTH_LDAP_ROLE_ATTRIBUTE_IS_DN` | Whether or not the roleAttributeID contains the fully-qualified DN of a role object. If false, the role name is taken from the value of the roleNameAttributeId attribute of the context name. Certain directory schemas, such as Microsoft Active Directory, require this attribute to be set to true. | `${AUTH_LDAP_ROLE_ATTRIBUTE_IS_DN}` |`AUTH_LDAP_REFERRAL_USER_ATTRIBUTE_ID_TO_CHECK` | If you are not using referrals, you can ignore this option. When using referrals, this option denotes the attribute name which contains users defined for a certain role, for example member, if the role object is inside the referral. Users are checked against the content of this attribute name. If this option is not set, the check will always fail, so role objects cannot be stored in a referral tree. | `${AUTH_LDAP_REFERRAL_USER_ATTRIBUTE_ID_TO_CHECK}` |`AUTH_ROLE_MAPPER_ROLES_PROPERTIES` | When present, the RoleMapping Login Module will be configured to use the provided file. This parameter defines the fully-qualified file path and name of a properties file or resource which maps roles to replacement roles. The format is original_role=role1,role2,role3 | `${AUTH_ROLE_MAPPER_ROLES_PROPERTIES}` |`AUTH_ROLE_MAPPER_REPLACE_ROLE` | Whether to add to the current roles, or replace the current roles with the mapped ones. Replaces if set to true. | `${AUTH_ROLE_MAPPER_REPLACE_ROLE}` .63+| `${APPLICATION_NAME}-kieserver` |`WORKBENCH_SERVICE_NAME` | -- | `${APPLICATION_NAME}-rhdmcentr` |`KIE_ADMIN_USER` | Admin user name | Set according to the credentials secret |`KIE_ADMIN_PWD` | Admin user password | Set according to the credentials secret |`KIE_SERVER_MODE` | The KIE Server mode. Valid values are 'DEVELOPMENT' or 'PRODUCTION'. In production mode, you can not deploy SNAPSHOT versions of artifacts on the KIE server and can not change the version of an artifact in an existing container. (Sets the org.kie.server.mode system property). | `${KIE_SERVER_MODE}` |`KIE_MBEANS` | KIE server mbeans enabled/disabled. (Sets the kie.mbeans and kie.scanner.mbeans system properties) | `${KIE_MBEANS}` |`DROOLS_SERVER_FILTER_CLASSES` | KIE server class filtering. (Sets the org.drools.server.filter.classes system property) | `${DROOLS_SERVER_FILTER_CLASSES}` |`PROMETHEUS_SERVER_EXT_DISABLED` | If set to false, the prometheus server extension will be enabled. (Sets the org.kie.prometheus.server.ext.disabled system property) | `${PROMETHEUS_SERVER_EXT_DISABLED}` |`KIE_SERVER_BYPASS_AUTH_USER` | Allows the KIE server to bypass the authenticated user for task-related operations, for example, queries. (Sets the org.kie.server.bypass.auth.user system property) | `${KIE_SERVER_BYPASS_AUTH_USER}` |`KIE_SERVER_CONTROLLER_SERVICE` | -- | `${APPLICATION_NAME}-rhdmcentr` |`KIE_SERVER_CONTROLLER_PROTOCOL` | -- | ws |`KIE_SERVER_ID` | -- | -- |`KIE_SERVER_ROUTE_NAME` | -- | insecure-${APPLICATION_NAME}-kieserver |`KIE_SERVER_STARTUP_STRATEGY` | -- | OpenShiftStartupStrategy |`MAVEN_MIRROR_URL` | Maven mirror that Decision Central and KIE server must use. If you configure a mirror, this mirror must contain all artifacts that are required for building and deploying your services. | `${MAVEN_MIRROR_URL}` |`MAVEN_MIRROR_OF` | Maven mirror configuration for KIE server. | `${MAVEN_MIRROR_OF}` |`MAVEN_REPOS` | -- | RHDMCENTR,EXTERNAL |`RHDMCENTR_MAVEN_REPO_ID` | -- | repo-rhdmcentr |`RHDMCENTR_MAVEN_REPO_SERVICE` | -- | `${APPLICATION_NAME}-rhdmcentr` |`RHDMCENTR_MAVEN_REPO_PATH` | -- | `/maven2/` |`RHDMCENTR_MAVEN_REPO_USERNAME` | -- | Set according to the credentials secret |`RHDMCENTR_MAVEN_REPO_PASSWORD` | -- | Set according to the credentials secret |`EXTERNAL_MAVEN_REPO_ID` | The id to use for the maven repository. If set, it can be excluded from the optionally configured mirror by adding it to MAVEN_MIRROR_OF. For example: external:*,!repo-rhdmcentr,!repo-custom. If MAVEN_MIRROR_URL is set but MAVEN_MIRROR_ID is not set, an id will be generated randomly, but won't be usable in MAVEN_MIRROR_OF. | `${MAVEN_REPO_ID}` |`EXTERNAL_MAVEN_REPO_URL` | Fully qualified URL to a Maven repository or service. | `${MAVEN_REPO_URL}` |`EXTERNAL_MAVEN_REPO_USERNAME` | User name for accessing the Maven repository, if required. | `${MAVEN_REPO_USERNAME}` |`EXTERNAL_MAVEN_REPO_PASSWORD` | Password to access the Maven repository, if required. | `${MAVEN_REPO_PASSWORD}` |`HTTPS_KEYSTORE_DIR` | -- | `/etc/kieserver-secret-volume` |`HTTPS_KEYSTORE` | The name of the keystore file within the secret for KIE Server. | `${KIE_SERVER_HTTPS_KEYSTORE}` |`HTTPS_NAME` | The name associated with the server certificate for KIE Server. | `${KIE_SERVER_HTTPS_NAME}` |`HTTPS_PASSWORD` | The password for the keystore and certificate for KIE Server. | `${KIE_SERVER_HTTPS_PASSWORD}` |`SSO_URL` | RH-SSO URL. | `${SSO_URL}` |`SSO_OPENIDCONNECT_DEPLOYMENTS` | -- | ROOT.war |`SSO_REALM` | RH-SSO Realm name. | `${SSO_REALM}` |`SSO_SECRET` | KIE Server RH-SSO Client Secret. | `${KIE_SERVER_SSO_SECRET}` |`SSO_CLIENT` | KIE Server RH-SSO Client name. | `${KIE_SERVER_SSO_CLIENT}` |`SSO_USERNAME` | RH-SSO Realm admin user name used to create the Client if it doesn't exist. | `${SSO_USERNAME}` |`SSO_PASSWORD` | RH-SSO Realm Admin Password used to create the Client. | `${SSO_PASSWORD}` |`SSO_DISABLE_SSL_CERTIFICATE_VALIDATION` | RH-SSO Disable SSL Certificate Validation. | `${SSO_DISABLE_SSL_CERTIFICATE_VALIDATION}` |`SSO_PRINCIPAL_ATTRIBUTE` | RH-SSO Principal Attribute to use as user name. | `${SSO_PRINCIPAL_ATTRIBUTE}` |`HOSTNAME_HTTP` | Custom hostname for http service route for KIE Server. Leave blank for default hostname, e.g.: insecure--kieserver-. | `${KIE_SERVER_HOSTNAME_HTTP}` |`HOSTNAME_HTTPS` | Custom hostname for https service route for KIE Server. Leave blank for default hostname, e.g.: -kieserver-. | `${KIE_SERVER_HOSTNAME_HTTPS}` |`AUTH_LDAP_URL` | LDAP Endpoint to connect for authentication. | `${AUTH_LDAP_URL}` |`AUTH_LDAP_BIND_DN` | Bind DN used for authentication. | `${AUTH_LDAP_BIND_DN}` |`AUTH_LDAP_BIND_CREDENTIAL` | LDAP Credentials used for authentication. | `${AUTH_LDAP_BIND_CREDENTIAL}` |`AUTH_LDAP_JAAS_SECURITY_DOMAIN` | The JMX ObjectName of the JaasSecurityDomain used to decrypt the password. | `${AUTH_LDAP_JAAS_SECURITY_DOMAIN}` |`AUTH_LDAP_BASE_CTX_DN` | LDAP Base DN of the top-level context to begin the user search. | `${AUTH_LDAP_BASE_CTX_DN}` |`AUTH_LDAP_BASE_FILTER` | LDAP search filter used to locate the context of the user to authenticate. The input username or userDN obtained from the login module callback is substituted into the filter anywhere a {0} expression is used. A common example for the search filter is (uid={0}). | `${AUTH_LDAP_BASE_FILTER}` |`AUTH_LDAP_SEARCH_SCOPE` | The search scope to use. | `${AUTH_LDAP_SEARCH_SCOPE}` |`AUTH_LDAP_SEARCH_TIME_LIMIT` | The timeout in milliseconds for user or role searches. | `${AUTH_LDAP_SEARCH_TIME_LIMIT}` |`AUTH_LDAP_DISTINGUISHED_NAME_ATTRIBUTE` | The name of the attribute in the user entry that contains the DN of the user. This may be necessary if the DN of the user itself contains special characters, backslash for example, that prevent correct user mapping. If the attribute does not exist, the entry's DN is used. | `${AUTH_LDAP_DISTINGUISHED_NAME_ATTRIBUTE}` |`AUTH_LDAP_PARSE_USERNAME` | A flag indicating if the DN is to be parsed for the user name. If set to true, the DN is parsed for the user name. If set to false the DN is not parsed for the user name. This option is used together with usernameBeginString and usernameEndString. | `${AUTH_LDAP_PARSE_USERNAME}` |`AUTH_LDAP_USERNAME_BEGIN_STRING` | Defines the String which is to be removed from the start of the DN to reveal the user name. This option is used together with usernameEndString and only taken into account if parseUsername is set to true. | `${AUTH_LDAP_USERNAME_BEGIN_STRING}` |`AUTH_LDAP_USERNAME_END_STRING` | Defines the String which is to be removed from the end of the DN to reveal the user name. This option is used together with usernameEndString and only taken into account if parseUsername is set to true. | `${AUTH_LDAP_USERNAME_END_STRING}` |`AUTH_LDAP_ROLE_ATTRIBUTE_ID` | Name of the attribute containing the user roles. | `${AUTH_LDAP_ROLE_ATTRIBUTE_ID}` |`AUTH_LDAP_ROLES_CTX_DN` | The fixed DN of the context to search for user roles. This is not the DN where the actual roles are, but the DN where the objects containing the user roles are. For example, in a Microsoft Active Directory server, this is the DN where the user account is. | `${AUTH_LDAP_ROLES_CTX_DN}` |`AUTH_LDAP_ROLE_FILTER` | A search filter used to locate the roles associated with the authenticated user. The input username or userDN obtained from the login module callback is substituted into the filter anywhere a {0} expression is used. The authenticated userDN is substituted into the filter anywhere a {1} is used. An example search filter that matches on the input username is (member={0}). An alternative that matches on the authenticated userDN is (member={1}). | `${AUTH_LDAP_ROLE_FILTER}` |`AUTH_LDAP_ROLE_RECURSION` | The number of levels of recursion the role search will go below a matching context. Disable recursion by setting this to 0. | `${AUTH_LDAP_ROLE_RECURSION}` |`AUTH_LDAP_DEFAULT_ROLE` | A role included for all authenticated users | `${AUTH_LDAP_DEFAULT_ROLE}` |`AUTH_LDAP_ROLE_NAME_ATTRIBUTE_ID` | Name of the attribute within the roleCtxDN context which contains the role name. If the roleAttributeIsDN property is set to true, this property is used to find the role object's name attribute. | `${AUTH_LDAP_ROLE_NAME_ATTRIBUTE_ID}` |`AUTH_LDAP_PARSE_ROLE_NAME_FROM_DN` | A flag indicating if the DN returned by a query contains the roleNameAttributeID. If set to true, the DN is checked for the roleNameAttributeID. If set to false, the DN is not checked for the roleNameAttributeID. This flag can improve the performance of LDAP queries. | `${AUTH_LDAP_PARSE_ROLE_NAME_FROM_DN}` |`AUTH_LDAP_ROLE_ATTRIBUTE_IS_DN` | Whether or not the roleAttributeID contains the fully-qualified DN of a role object. If false, the role name is taken from the value of the roleNameAttributeId attribute of the context name. Certain directory schemas, such as Microsoft Active Directory, require this attribute to be set to true. | `${AUTH_LDAP_ROLE_ATTRIBUTE_IS_DN}` |`AUTH_LDAP_REFERRAL_USER_ATTRIBUTE_ID_TO_CHECK` | If you are not using referrals, you can ignore this option. When using referrals, this option denotes the attribute name which contains users defined for a certain role, for example member, if the role object is inside the referral. Users are checked against the content of this attribute name. If this option is not set, the check will always fail, so role objects cannot be stored in a referral tree. | `${AUTH_LDAP_REFERRAL_USER_ATTRIBUTE_ID_TO_CHECK}` |`AUTH_ROLE_MAPPER_ROLES_PROPERTIES` | When present, the RoleMapping Login Module will be configured to use the provided file. This parameter defines the fully-qualified file path and name of a properties file or resource which maps roles to replacement roles. The format is original_role=role1,role2,role3 | `${AUTH_ROLE_MAPPER_ROLES_PROPERTIES}` |`AUTH_ROLE_MAPPER_REPLACE_ROLE` | Whether to add to the current roles, or replace the current roles with the mapped ones. Replaces if set to true. | `${AUTH_ROLE_MAPPER_REPLACE_ROLE}` |======================================================================= ===== Volumes |============= |Deployment |Name | mountPath | Purpose | readOnly |`${APPLICATION_NAME}-rhdmcentr` | decisioncentral-keystore-volume | `/etc/decisioncentral-secret-volume` | ssl certs | True |`${APPLICATION_NAME}-kieserver` | kieserver-keystore-volume | `/etc/kieserver-secret-volume` | ssl certs | True |============= === External Dependencies ==== Volume Claims A `PersistentVolume` object is a storage resource in an OpenShift cluster. Storage is provisioned by an administrator by creating `PersistentVolume` objects from sources such as GCE Persistent Disks, AWS Elastic Block Stores (EBS), and NFS mounts. See the https://access.redhat.com/documentation/en-us/openshift_container_platform/3.11/html/developer_guide/dev-guide-persistent-volumes[Openshift documentation] for more information. |============= |Name | Access Mode |`${APPLICATION_NAME}-rhdmcentr-claim` | ReadWriteMany |============= ==== Secrets This template requires the following secrets to be installed for the application to run. decisioncentral-app-secret kieserver-app-secret [[clustering]] ==== Clustering Clustering in OpenShift EAP is achieved through one of two discovery mechanisms: Kubernetes or DNS. This is done by configuring the JGroups protocol stack in standalone-openshift.xml with either the `` or `` elements. The templates are configured to use `DNS_PING`, however `KUBE_PING`is the default used by the image. The discovery mechanism used is specified by the `JGROUPS_PING_PROTOCOL` environment variable which can be set to either `openshift.DNS_PING` or `openshift.KUBE_PING`. `openshift.KUBE_PING` is the default used by the image if no value is specified for `JGROUPS_PING_PROTOCOL`. For DNS_PING to work, the following steps must be taken: . The `OPENSHIFT_DNS_PING_SERVICE_NAME` environment variable must be set to the name of the ping service for the cluster (see table above). If not set, the server will act as if it is a single-node cluster (a ""cluster of one""). . The `OPENSHIFT_DNS_PING_SERVICE_PORT` environment variables should be set to the port number on which the ping service is exposed (see table above). The `DNS_PING` protocol will attempt to discern the port from the SRV records, if it can, otherwise it will default to 8888. . A ping service which exposes the ping port must be defined. This service should be ""headless"" (ClusterIP=None) and must have the following: .. The port must be named for port discovery to work. .. It must be annotated with `service.alpha.kubernetes.io/tolerate-unready-endpoints` set to `""true""`. Omitting this annotation will result in each node forming their own ""cluster of one"" during startup, then merging their cluster into the other nodes' clusters after startup (as the other nodes are not detected until after they have started). .Example ping service for use with DNS_PING [source,yaml] ---- kind: Service apiVersion: v1 spec: clusterIP: None ports: - name: ping port: 8888 selector: deploymentConfig: eap-app metadata: name: eap-app-ping annotations: service.alpha.kubernetes.io/tolerate-unready-endpoints: ""true"" description: ""The JGroups ping port for clustering."" ---- For `KUBE_PING` to work, the following steps must be taken: . The `OPENSHIFT_KUBE_PING_NAMESPACE` environment variable must be set (see table above). If not set, the server will act as if it is a single-node cluster (a ""cluster of one""). . The `OPENSHIFT_KUBE_PING_LABELS` environment variables should be set (see table above). If not set, pods outside of your application (albeit in your namespace) will try to join. . Authorization must be granted to the service account the pod is running under to be allowed to access Kubernetes' REST api. This is done on the command line. .Policy commands ==== Using the default service account in the myproject namespace: .... oc policy add-role-to-user view system:serviceaccount:myproject:default -n myproject .... Using the eap-service-account in the myproject namespace: .... oc policy add-role-to-user view system:serviceaccount:myproject:eap-service-account -n myproject .... ==== ",12069,True,2651.1642669496455,median ".//============================================================================ .// This archetype file contains the functions for generating .// preexisting instances initialization code. .// .// Note: This archetype is not presently in the test cycle. .// It must be run with a schema that includes CSME_CIE, R2961 and R2962. .//============================================================================ .// .// .//============================================================================ .// Initialize the instance subsystem. .// Update the instance and link records with array index values .// and container counts. .// The mapping of the instances to a particular array index is .// arbitrary. .//============================================================================ .function PEIInstanceSubsystemInit .param inst_ref_set o_objs .// .for each o_obj in o_objs .select many i_inss related by o_obj->CSME_CIE[R2961]->I_INS[R2962] .// Check for preexisting instance population requirement. .// The class must have instances and also be colored. .assign i = cardinality i_inss .select one te_class related by o_obj->TE_CLASS[R2019] .if ( ( i > 0 ) and ( te_class.PEIsDefinedInData ) ) .assign te_class.PEIsDefinedInData = TRUE .else .assign te_class.PEIsDefinedInData = FALSE .end if .// .assign i = 0 .for each i_ins in i_inss .assign i_ins.Name = ""${i}"" .assign i = i + 1 .end for .end for .end function .// .// .//============================================================================ .// Count the preexisting instances of the given type. .// Return the number of preexisting instances for obj. .//============================================================================ .function PEINumberOfPreexistingInstances .param inst_ref o_obj .select many i_inss related by o_obj->CSME_CIE[R2961]->I_INS[R2962] .assign attr_result = cardinality i_inss .// .assign msg = ""PEINumberOfPreexistingInstances is ${attr_result} "" .// .assign msg = msg + ""for ${o_obj.Name} (${o_obj.Key_Lett})"" .// .print ""${msg}"" .end function .// .// .//============================================================================= .// Generate initializers for preexisting instances. .// We generate the initializers in array index order. C initializers .// will assume sequential ordering. .//============================================================================= .function PEIRenderInitializers .param inst_ref o_obj .assign attr_assset = """" .select any te_set from instances of TE_SET .select one te_class related by o_obj->TE_CLASS[R2019] .if ( te_class.PEIsDefinedInData ) .assign inst_count = 0 .select many i_inss related by o_obj->CSME_CIE[R2961]->I_INS[R2962] .assign i_inss_cardinality = cardinality i_inss .while ( inst_count < i_inss_cardinality ) .for each i_ins in i_inss .if ( i_ins.Name == ""$t{inst_count}"" ) .invoke initializercode = PEIRenderInitializerBody( i_ins, o_obj ) .assign attr_assset = attr_assset + initializercode.assset { ${initializercode.result} }\\ .if ( last i_inss ) .else , .end if .break for .end if .end for .assign inst_count = inst_count + 1 .end while .// inst_count .// If there is a need for relationship set containers, build them up. .if ( attr_assset != """" ) .invoke rel_set_name = PEIGetRelationshipSetContainerName( te_class ) .assign attr_assset = ""static ${te_set.element_type} ${rel_set_name.result}[] = {\\n"" + attr_assset .assign attr_assset = ""/* PEI relationship set containers. */\\n"" + attr_assset .assign attr_assset = attr_assset + ""\\n};\\n"" .end if .end if .end function .// .// .//============================================================================= .// Generate body of one preexisting instance initializer. .// First, the initial state initializer is output. .// The class instance attribute data variable values are generated .// in the same order in which they appear in the application analysis OIM. .// The relationship optimization initializers are then generated. .//============================================================================= .function PEIRenderInitializerBody .param inst_ref i_ins .param inst_ref o_obj .assign attr_result = """" .assign attr_assset = """" .// .// Generate state machine state (if needed). .// .invoke cs_init = PEIRenderInitializerBodyCurrentState( i_ins, o_obj ) .assign attr_result = attr_result + cs_init.result .if ( """" != attr_result ) .assign attr_result = attr_result + "", "" .end if .// .// Generate the attribute value initializers. .// .select any te_attr related by o_obj->TE_CLASS[R2019]->TE_ATTR[R2061] where ( selected.prevID == 0 ) .if ( not_empty te_attr ) .select one o_attr related by te_attr->O_ATTR[R2033] .while ( not_empty te_attr ) .if ( te_attr.translate ) .select any i_avl related by i_ins->I_AVL[R2909] where ( selected.Attr_ID == o_attr.Attr_ID ) .invoke avlcode = PEIRenderInitializerBodyAttribute( o_attr, i_avl ) .assign attr_result = attr_result + avlcode.result .end if .// .// Advance to the next object attribute, if any. .select one te_attr related by te_attr->TE_ATTR[R2087.'precedes'] .// .// Generate comma separator. .if ( not_empty te_attr ) .if ( te_attr.translate ) .assign attr_result = attr_result + "", "" .end if .end if .end while .end if .// .// Generate the association linkage (if needed). .// .invoke ass_init = PEIRenderInitializerBodyAssociation( i_ins, o_obj ) .assign attr_result = attr_result + ass_init.result .assign attr_assset = attr_assset + ass_init.assset .// .end function .// .// .//============================================================================= .// Generate initialization for a single attribute value. .// Return the value as a string quoted correctly (if needed). .//============================================================================= .function PEIRenderInitializerBodyAttribute .param inst_ref o_attr .param inst_ref i_avl .assign attr_result = ""0"" .// Get the attribute data type. Strings need to be quoted. .invoke r = GetAttributeCodeGenType( o_attr ) .assign te_dt = r.result .if ( 4 == te_dt.Core_Typ ) .// string .if ( empty i_avl ) .// In absence of a populated attribute, use the attribute default value. .if ( """" != o_attr.DefaultValue ) .assign attr_result = o_attr.DefaultValue .else .assign attr_result = """""""""""" .end if .else .assign attr_result = """"""${i_avl.Value}"""""" .end if .else .if ( empty i_avl ) .assign attr_result = ""0"" .else .assign attr_result = i_avl.Value .end if .end if .end function .// .// .//============================================================================= .// Generate the optimized association linkage for this instance. .// Select the relationship set for this object. Loop through each one .// generating linkage anywhere storage is provided (for pointer refs). .// Get the multiplicity so we know whether we need sets or simple .// pointers. .// Do the right thing for each flavor of association, simple, reflexive, .// associative and sub/super. .// Return the static initializer body material. .//============================================================================= .function PEIRenderInitializerBodyAssociation .param inst_ref i_ins .param inst_ref o_obj .// .assign multiplicity = 0 .assign attr_assset = """" .assign attr_result = """" .select many te_rels related by o_obj->R_OIR[R201]->R_REL[R201]->TE_REL[R2034] .if ( not_empty te_rels ) .// Pre-order the relationships ascending by their relationship number. .// Note: This decouples code generation from SQL table .// insertion ordering internals. .invoke SortSetAscendingByAttr_Numb( te_rels ) .assign rel_count = 0 .assign rel_cardinality = cardinality te_rels .// .while ( rel_count < rel_cardinality ) .for each te_rel in te_rels .if ( te_rel.Order == rel_count ) .select one rel related by te_rel->R_REL[R2034] .if ( not te_rel.storage_needed ) .break for .end if .// Simple relationship? .select one simple_rel related by rel->R_SIMP[R206] .if ( not_empty simple_rel ) .select one participant related by simple_rel->R_PART[R207] .select one formalizer related by simple_rel->R_FORM[R208] .if ( empty formalizer ) .print ""\\n\\tRelationship R${rel.Numb} is not formalized!\\n"" .exit 101 .end if .// Deal with reflexives. .if ( participant.Obj_ID == formalizer.Obj_ID ) .invoke s = PEIRelInitSimpleReflexive( i_ins, o_obj, rel, participant, formalizer ) .assign attr_result = attr_result + s.result .assign attr_assset = attr_assset + s.assset .else .// Get multiplicity to pass to the code generator. .if ( o_obj.Obj_ID == participant.Obj_ID ) .assign multiplicity = formalizer.Mult .else .assign multiplicity = participant.Mult .end if .invoke s = PEIRelInitSimple( i_ins, o_obj, rel, multiplicity ) .assign attr_result = attr_result + s.result .assign attr_assset = attr_assset + s.assset .end if .// reflexive .else .// elif Subtype-Supertype relationship? .select one r_subsup related by rel->R_SUBSUP[R206] .if ( not_empty r_subsup ) .invoke s = PEIRelInitSubSuper( i_ins, o_obj, rel, r_subsup ) .assign attr_result = attr_result + s.result .else .// elif Associative relationship? .select one assrel related by rel->R_ASSOC[R206] .if ( not_empty assrel ) .invoke s = PEIRelInitAssociative( i_ins, o_obj, rel, assrel ) .assign attr_result = attr_result + s.result .assign attr_assset = attr_assset + s.assset .else .// elif Composed relationship? .select one composed_rel related by rel->R_COMP[R206] .if ( not_empty composed_rel ) .print ""\\nWARNING: R${rel.Numb} is COMPOSITION - No code generated.\\n"" .invoke s = PEIRelInitComposed( o_obj, rel ) .assign attr_result = attr_result + s.result .else .// elif Error: New subtype of R_REL or a corrupted model SQL... .print ""ERROR: Unknown association type:R${rel.Numb} for class '${o_obj.Name}' (${o_obj.Key_Lett})"" .exit 101 .end if .// not_empty composed_rel .end if .// not_empty associative_rel .end if .// not_empty subtype_supertype_rel .end if .// not_empty simp_rel .break for .end if .end for .assign rel_count = rel_count + 1 .end while .// rel_count < rel_cardinality .end if .// not_empty rel_set .end function .// .// .//============================================================================= .// Generate the optimized relationship linkage for a simple association. .// of multiplicity ONE. .//============================================================================= .function PEIRelInitSimple .param inst_ref i_ins .param inst_ref o_obj .param inst_ref r_rel .param integer multiplicity .// .assign attr_result = """" .assign attr_assset = """" .select any related_i_ins from instances of I_INS .// .// Find related instance index. .// Traverse the instance to link to instance chain .// to get the instance ArrayIndex. .if ( multiplicity == 0 ) .// ONE .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .select one related_i_ins related by i_lnk->I_LIP[R2901]->I_INS[R2958] .if ( empty related_i_ins ) .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .select one related_i_ins related by i_lnk->I_LIP[R2902]->I_INS[R2958] .end if .if ( not_empty related_i_ins ) .select one related_o_obj related by related_i_ins->CSME_CIE[R2962]->O_OBJ[R2961] .select one related_te_class related by related_o_obj->TE_CLASS[R2019] .assign attr_result = "", &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}]"" .else .// not participating .assign attr_result = "", 0"" .end if .// not empty .else .// MANY .// Build linked list of containers pointing to related instances. .select many i_lnks related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .select many related1_i_ins related by i_lnks->I_LIP[R2901]->I_INS[R2958] .select many i_lnks related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .select many related2_i_inss related by i_lnks->I_LIP[R2902]->I_INS[R2958] .assign related_i_inss = related1_i_ins | related2_i_inss .invoke s = PEIRenderRelationshipManyOptimization( related_i_inss, o_obj ) .assign attr_result = attr_result + s.result .assign attr_assset = attr_assset + s.assset .end if .// .end function .// .// .//============================================================================= .// Generate the optimized relationship linkage for a simple reflexive .// association. .// In the reflexive case, the part and form are aligned with R2901 and R2902. .//============================================================================= .function PEIRelInitSimpleReflexive .param inst_ref i_ins .param inst_ref o_obj .param inst_ref r_rel .param inst_ref r_part .param inst_ref r_form .// .assign attr_result = """" .assign attr_assset = """" .select one related_te_class related by o_obj->TE_CLASS[R2019] .select any related_i_ins from instances of I_INS .// .// Link the formalizer to the participant. .// .if ( r_part.Mult == 0 ) .// ONE .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .select one related_i_ins related by i_lnk->I_LIP[R2901]->I_INS[R2958] .if ( not_empty related_i_ins ) .assign attr_result = attr_result + "", &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}]"" .else .// Not participating. .assign attr_result = attr_result + "", 0"" .end if .else .// MANY .// Build linked list of containers pointing to related instances. .select many i_lnks related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .select many related_i_inss related by i_lnks->I_LIP[R2901]->I_INS[R2958] .invoke s = PEIRenderRelationshipManyOptimization( related_i_inss, o_obj ) .assign attr_result = attr_result + s.result .assign attr_assset = attr_assset + s.assset .end if .// .// Now link the participant to the formalizer(s). .// .if ( r_form.Mult == 0 ) .// ONE .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .select one related_i_ins related by i_lnk->I_LIP[R2902]->I_INS[R2958] .if ( not_empty related_i_ins ) .assign attr_result = attr_result + "", &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}]"" .else .// Not participating. .assign attr_result = attr_result + "", 0"" .end if .else .// MANY .// Build linked list of containers pointing to related instances. .select many i_lnks related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .select many related_i_inss related by i_lnks->I_LIP[R2902]->I_INS[R2958] .invoke s = PEIRenderRelationshipManyOptimization( related_i_inss, o_obj ) .assign attr_result = attr_result + s.result .assign attr_assset = attr_assset + s.assset .end if .// .end function .// .// .//============================================================================= .// Generate the optimized relationship linkage for an associative .// relationship. .// In the reflexive case, R2901 and R2902 will jive with AONE and AOTH. .// In the non-reflexive, we compare the instance Obj_ID with the .// AONE/AOTH Obj_ID. .//============================================================================= .function PEIRelInitAssociative .param inst_ref i_ins .param inst_ref o_obj .param inst_ref r_rel .param inst_ref r_assoc .// .assign attr_result = """" .assign attr_assset = """" .select one aone related by r_assoc->R_AONE[R209] .select one aoth related by r_assoc->R_AOTH[R210] .select one assr related by r_assoc->R_ASSR[R211] .// .// The other associated instance. .// .if ( o_obj.Obj_ID == aoth.Obj_ID ) .// Optimize relationship to associator. .if ( ( aone.Mult == 0 ) and ( assr.Mult == 0 ) ) .// ONE .select any i_lnk from instances of I_LNK where ( false ) .if ( aone.Obj_ID == aoth.Obj_ID ) .// reflexive .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .else .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .if ( empty i_lnk ) .select one related_o_obj related by i_ins->CSME_CIE[R2962]->O_OBJ[R2961] .if ( related_o_obj.Obj_ID == aoth.Obj_ID ) .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .end if .end if .// not empty .end if .// reflexive .if ( not_empty i_lnk ) .select one related_i_ins related by i_lnk->I_LIP[R2903]->I_INS[R2958] .select one related_o_obj related by related_i_ins->CSME_CIE[R2962]->O_OBJ[R2961] .select one related_te_class related by related_o_obj->TE_CLASS[R2019] .assign attr_result = attr_result + "", &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}]"" .else .// not participating .assign attr_result = attr_result + "", 0"" .end if .// not empty .else .// MANY .// Build linked list of containers pointing to related instances. .select many i_lnks from instances of I_LNK where ( false ) .select many related_i_inss from instances of I_INS where ( false ) .if ( aone.Obj_ID == aoth.Obj_ID ) .// reflexive .select many i_lnks related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .else .select many one_i_lnks related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .select many two_i_lnks related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .assign i_lnks = one_i_lnks | two_i_lnks .end if .select many related_i_inss related by i_lnks->I_LIP[R2903]->I_INS[R2958] .invoke s = PEIRenderRelationshipManyOptimization( related_i_inss, o_obj ) .assign attr_result = attr_result + s.result .assign attr_assset = attr_assset + s.assset .end if .end if .// .// The one associated instance. .// .if ( o_obj.Obj_ID == aone.Obj_ID ) .// Optimize relationship to associator. .if ( ( aoth.Mult == 0 ) and ( assr.Mult == 0 ) ) .// ONE .select any i_lnk from instances of I_LNK where ( false ) .if ( aone.Obj_ID == aoth.Obj_ID ) .// reflexive .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .else .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .if ( empty i_lnk ) .select one related_o_obj related by i_ins->CSME_CIE[R2962]->O_OBJ[R2961] .if ( related_o_obj.Obj_ID == aone.Obj_ID ) .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .end if .end if .end if .// reflexive .if ( not_empty i_lnk ) .select one related_i_ins related by i_lnk->I_LIP[R2903]->I_INS[R2958] .select one related_o_obj related by related_i_ins->CSME_CIE[R2962]->O_OBJ[R2961] .select one related_te_class related by related_o_obj->TE_CLASS[R2019] .assign attr_result = attr_result + "", &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}]"" .else .// not participating .assign attr_result = attr_result + "", 0"" .end if .// not empty .else .// MANY .// Build linked list of containers pointing to related instances. .select many i_lnks from instances of I_LNK where ( false ) .select many related_i_inss from instances of I_INS where ( false ) .if ( aone.Obj_ID == aoth.Obj_ID ) .select many i_lnks related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .else .select many one_i_lnks related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .select many two_i_lnks related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .assign i_lnks = one_i_lnks | two_i_lnks .end if .select many related_i_inss related by i_lnks->I_LIP[R2903]->I_INS[R2958] .invoke s = PEIRenderRelationshipManyOptimization( related_i_inss, o_obj ) .assign attr_result = attr_result + s.result .assign attr_assset = attr_assset + s.assset .end if .end if .// .// The associative instance. .// .if ( o_obj.Obj_ID == assr.Obj_ID ) .// Optimize relationship to both associates. .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2903] where ( selected.Rel_ID == r_rel.Rel_ID ) .if ( not_empty i_lnk ) .select one related_i_ins related by i_lnk->I_LIP[R2901]->I_INS[R2958] .select one related_o_obj related by related_i_ins->CSME_CIE[R2962]->O_OBJ[R2961] .select one related_te_class related by related_o_obj->TE_CLASS[R2019] .select one related2_i_ins related by i_lnk->I_LIP[R2902]->I_INS[R2958] .select one related2_o_obj related by related2_i_ins->CSME_CIE[R2962]->O_OBJ[R2961] .select one related2_te_class related by related2_o_obj->TE_CLASS[R2019] .if ( ( aone.Obj_ID == aoth.Obj_ID ) or ( related2_o_obj.Obj_ID == aone.Obj_ID ) ) .assign attr_result = attr_result + "", &${related2_te_class.GeneratedName}_instances[${related2_i_ins.Name}]"" .assign attr_result = attr_result + "", &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}]"" .else .assign attr_result = attr_result + "", &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}]"" .assign attr_result = attr_result + "", &${related2_te_class.GeneratedName}_instances[${related2_i_ins.Name}]"" .end if .else .// not participating .assign attr_result = attr_result + "", 0, 0"" .end if .// not empty .end if .end function .// .// .//============================================================================= .// Generate the optimized relationship linkage for a Subtype/Supertype .// association. .//============================================================================= .function PEIRelInitSubSuper .param inst_ref i_ins .param inst_ref o_obj .param inst_ref r_rel .param inst_ref r_subsup .assign attr_result = """" .// .// Find related instance index. .// Traverse the instance to link to instance chain .// to get the instance ArrayIndex. .select one super related by r_subsup->R_SUPER[R212] .if ( o_obj.Obj_ID == super.Obj_ID ) .// Supertype .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2901] where ( selected.Rel_ID == r_rel.Rel_ID ) .select one related_i_ins related by i_lnk->I_LIP[R2902]->I_INS[R2958] .if ( empty i_lnk ) .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .select one related_i_ins related by i_lnk->I_LIP[R2901]->I_INS[R2958] .end if .if ( not_empty i_lnk ) .select one related_o_obj related by related_i_ins->CSME_CIE[R2962]->O_OBJ[R2961] .select one related_te_class related by related_o_obj->TE_CLASS[R2019] .assign attr_result = "", (void *) &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}], ${related_te_class.system_class_number}"" .else .// not participating .assign attr_result = "", 0, 0"" .end if .else .// Subtype .select any i_lnk related by i_ins->I_LIP[R2958]->I_LNK[R2902] where ( selected.Rel_ID == r_rel.Rel_ID ) .if ( not_empty i_lnk ) .select one related_i_ins related by i_lnk->I_LIP[R2901]->I_INS[R2958] .select one related_o_obj related by related_i_ins->CSME_CIE[R2962]->O_OBJ[R2961] .select one related_te_class related by related_o_obj->TE_CLASS[R2019] .assign attr_result = "", &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}]"" .else .// not participating .assign attr_result = "", 0"" .end if .end if .end function .// .// .//============================================================================= .// Generate the optimized relationship linkage for a composed association. .//============================================================================= .function PEIRelInitComposed .param inst_ref o_obj .param inst_ref r_rel .assign attr_result = """" .end function .// .// .//============================================================================= .// Generate an initializer for the current state attribute if needed. .//============================================================================= .function PEIRenderInitializerBodyCurrentState .param inst_ref i_ins .param inst_ref o_obj .assign attr_result = """" .select one te_state related by i_ins->SM_STATE[R2915]->TE_STATE[R2037] .if ( not_empty te_state ) .assign attr_result = te_state.enumerator .end if .end function .// .// .//============================================================================= .// Render relationship MANY optimization. .// This helper is used to render the code used to optimize a relationship .// set. The set variable is generated for inside the instance structure. .// The linked list body pointing to related instances is also generated. .//============================================================================= .function PEIRenderRelationshipManyOptimization .param inst_ref_set i_inss .param inst_ref o_obj .// .assign attr_result = """" .assign attr_assset = """" .select any te_sys from instances of TE_SYS .// i_inss, o_obj .assign instance_count = cardinality i_inss .if ( instance_count > 0 ) .select one te_class related by o_obj->TE_CLASS[R2019] .assign ContainerIndex = te_class.ContainerIndex .// A container index starting greater than zero means we are not the .// first (instance) to be adding linked lists. Precede with comma. .if ( ContainerIndex > 0 ) .assign attr_assset = "",\\n"" .end if .invoke rel_set_name = PEIGetRelationshipSetContainerName( te_class ) .assign attr_result = "", { &${rel_set_name.result}[${ContainerIndex}] }"" .for each related_i_ins in i_inss .assign ContainerIndex = ContainerIndex + 1 .select one related_o_obj related by related_i_ins->CSME_CIE[R2962]->O_OBJ[R2961] .select one related_te_class related by related_o_obj->TE_CLASS[R2019] .if ( last i_inss ) .if ( te_sys.CollectionsFlavor == 20 ) .assign icount = cardinality i_inss .if ( icount > 1 ) .assign attr_assset = attr_assset + "" { 0, (void *) &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}], &${rel_set_name.result}[${ContainerIndex} - 2] }"" .else .assign attr_assset = attr_assset + "" { 0, (void *) &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}], 0 }"" .end if .// cardinality i_inss > 1 .else .assign attr_assset = attr_assset + "" { 0, (void *) &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}] }"" .end if .elif ( first i_inss ) .if ( te_sys.CollectionsFlavor == 20 ) .assign attr_assset = attr_assset + "" { &${rel_set_name.result}[${ContainerIndex}], (void *) &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}], 0 },\\n"" .else .assign attr_assset = attr_assset + "" { &${rel_set_name.result}[${ContainerIndex}], (void *) &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}] },\\n"" .end if .else .if ( te_sys.CollectionsFlavor == 20 ) .assign attr_assset = attr_assset + "" { &${rel_set_name.result}[${ContainerIndex}], (void *) &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}], &${rel_set_name.result}[${ContainerIndex} - 2] },\\n"" .else .assign attr_assset = attr_assset + "" { &${rel_set_name.result}[${ContainerIndex}], (void *) &${related_te_class.GeneratedName}_instances[${related_i_ins.Name}] },\\n"" .end if .end if .end for .assign te_class.ContainerIndex = ContainerIndex .else .// Empty relationship set. .assign attr_result = "", { 0 }"" .end if .end function .// ",8102,False,1917.1189236944042,median "[[netty-component]] = Netty Component :docTitle: Netty :artifactId: camel-netty :description: Socket level networking using TCP or UDP with the Netty 4.x. :since: 2.14 :supportLevel: Stable :component-header: Both producer and consumer are supported include::{cq-version}@camel-quarkus:ROOT:partial$reference/components/netty.adoc[opts=optional] *Since Camel {since}* *{component-header}* The Netty component in Camel is a socket communication component, based on the http://netty.io/[Netty] project version 4. + Netty is a NIO client server framework which enables quick and easy development of networkServerInitializerFactory applications such as protocol servers and clients. + Netty greatly simplifies and streamlines network programming such as TCP and UDP socket server. This camel component supports both producer and consumer endpoints. The Netty component has several options and allows fine-grained control of a number of TCP/UDP communication parameters (buffer sizes, keepAlives, tcpNoDelay, etc) and facilitates both In-Only and In-Out communication on a Camel route. Maven users will need to add the following dependency to their `pom.xml` for this component: [source,xml] ---- org.apache.camel camel-netty x.x.x ---- == URI format The URI scheme for a netty component is as follows [source,text] ---- netty:tcp://0.0.0.0:99999[?options] netty:udp://remotehost:99999/[?options] ---- This component supports producer and consumer endpoints for both TCP and UDP. You can append query options to the URI in the following format, `?option=value&option=value&...` == Options // component options: START The Netty component supports 73 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *configuration* (common) | To use the NettyConfiguration as configuration when creating endpoints. | | NettyConfiguration | *disconnect* (common) | Whether or not to disconnect(close) from Netty Channel right after use. Can be used for both consumer and producer. | false | boolean | *keepAlive* (common) | Setting to ensure socket is not closed due to inactivity | true | boolean | *reuseAddress* (common) | Setting to facilitate socket multiplexing | true | boolean | *reuseChannel* (common) | This option allows producers and consumers (in client mode) to reuse the same Netty Channel for the lifecycle of processing the Exchange. This is useful if you need to call a server multiple times in a Camel route and want to use the same network connection. When using this, the channel is not returned to the connection pool until the Exchange is done; or disconnected if the disconnect option is set to true. The reused Channel is stored on the Exchange as an exchange property with the key NettyConstants#NETTY_CHANNEL which allows you to obtain the channel during routing and use it as well. | false | boolean | *sync* (common) | Setting to set endpoint as one-way or request-response | true | boolean | *tcpNoDelay* (common) | Setting to improve TCP protocol performance | true | boolean | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *broadcast* (consumer) | Setting to choose Multicast over UDP | false | boolean | *clientMode* (consumer) | If the clientMode is true, netty consumer will connect the address as a TCP client. | false | boolean | *reconnect* (consumer) | Used only in clientMode in consumer, the consumer will attempt to reconnect on disconnection if this is enabled | true | boolean | *reconnectInterval* (consumer) | Used if reconnect and clientMode is enabled. The interval in milli seconds to attempt reconnection | 10000 | int | *backlog* (consumer) | Allows to configure a backlog for netty consumer (server). Note the backlog is just a best effort depending on the OS. Setting this option to a value such as 200, 500 or 1000, tells the TCP stack how long the accept queue can be If this option is not configured, then the backlog depends on OS setting. | | int | *bossCount* (consumer) | When netty works on nio mode, it uses default bossCount parameter from Netty, which is 1. User can use this option to override the default bossCount from Netty | 1 | int | *bossGroup* (consumer) | Set the BossGroup which could be used for handling the new connection of the server side across the NettyEndpoint | | EventLoopGroup | *disconnectOnNoReply* (consumer) | If sync is enabled then this option dictates NettyConsumer if it should disconnect where there is no reply to send back. | true | boolean | *executorService* (consumer) | To use the given EventExecutorGroup. | | EventExecutorGroup | *maximumPoolSize* (consumer) | Sets a maximum thread pool size for the netty consumer ordered thread pool. The default size is 2 x cpu_core plus 1. Setting this value to eg 10 will then use 10 threads unless 2 x cpu_core plus 1 is a higher value, which then will override and be used. For example if there are 8 cores, then the consumer thread pool will be 17. This thread pool is used to route messages received from Netty by Camel. We use a separate thread pool to ensure ordering of messages and also in case some messages will block, then nettys worker threads (event loop) wont be affected. | | int | *nettyServerBootstrapFactory* (consumer) | To use a custom NettyServerBootstrapFactory | | NettyServerBootstrapFactory | *networkInterface* (consumer) | When using UDP then this option can be used to specify a network interface by its name, such as eth0 to join a multicast group. | | String | *noReplyLogLevel* (consumer) | If sync is enabled this option dictates NettyConsumer which logging level to use when logging a there is no reply to send back. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverClosedChannelException{zwsp}CaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an java.nio.channels.ClosedChannelException then its logged using this logging level. This is used to avoid logging the closed channel exceptions, as clients can disconnect abruptly and then cause a flood of closed exceptions in the Netty server. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | DEBUG | LoggingLevel | *serverExceptionCaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an exception then its logged using this logging level. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverInitializerFactory* (consumer) | To use a custom ServerInitializerFactory | | ServerInitializerFactory | *usingExecutorService* (consumer) | Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. | true | boolean | *connectTimeout* (producer) | Time to wait for a socket connection to be available. Value is in milliseconds. | 10000 | int | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *requestTimeout* (producer) | Allows to use a timeout for the Netty producer when calling a remote server. By default no timeout is in use. The value is in milli seconds, so eg 30000 is 30 seconds. The requestTimeout is using Netty's ReadTimeoutHandler to trigger the timeout. | | long | *clientInitializerFactory* (producer) | To use a custom ClientInitializerFactory | | ClientInitializerFactory | *correlationManager* (producer) | To use a custom correlation manager to manage how request and reply messages are mapped when using request/reply with the netty producer. This should only be used if you have a way to map requests together with replies such as if there is correlation ids in both the request and reply messages. This can be used if you want to multiplex concurrent messages on the same channel (aka connection) in netty. When doing this you must have a way to correlate the request and reply messages so you can store the right reply on the inflight Camel Exchange before its continued routed. We recommend extending the TimeoutCorrelationManagerSupport when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. See also the producerPoolEnabled option for more details. | | NettyCamelStateCorrelationManager | *lazyChannelCreation* (producer) | Channels can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. | true | boolean | *producerPoolEnabled* (producer) | Whether producer pool is enabled or not. Important: If you turn this off then a single shared connection is used for the producer, also if you are doing request/reply. That means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement NettyCamelStateCorrelationManager as correlation manager and configure it via the correlationManager option. See also the correlationManager option for more details. | true | boolean | *producerPoolMaxActive* (producer) | Sets the cap on the number of objects that can be allocated by the pool (checked out to clients, or idle awaiting checkout) at a given time. Use a negative value for no limit. | -1 | int | *producerPoolMaxIdle* (producer) | Sets the cap on the number of idle instances in the pool. | 100 | int | *producerPoolMinEvictableIdle* (producer) | Sets the minimum amount of time (value in millis) an object may sit idle in the pool before it is eligible for eviction by the idle object evictor. | 300000 | long | *producerPoolMinIdle* (producer) | Sets the minimum number of instances allowed in the producer pool before the evictor thread (if active) spawns new objects. | | int | *udpConnectionlessSending* (producer) | This option supports connection less udp sending which is a real fire and forget. A connected udp send receive the PortUnreachableException if no one is listen on the receiving port. | false | boolean | *useByteBuf* (producer) | If the useByteBuf is true, netty producer will turn the message body into ByteBuf before sending it out. | false | boolean | *hostnameVerification* ( security) | To enable/disable hostname verification on SSLEngine | false | boolean | *allowSerializedHeaders* (advanced) | Only used for TCP when transferExchange is true. When set to true, serializable objects in headers and properties will be added to the exchange. Otherwise Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *autowiredEnabled* (advanced) | Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc. | true | boolean | *channelGroup* (advanced) | To use a explicit ChannelGroup. | | ChannelGroup | *nativeTransport* (advanced) | Whether to use native transport instead of NIO. Native transport takes advantage of the host operating system and is only supported on some platforms. You need to add the netty JAR for the host operating system you are using. See more details at: \\http://netty.io/wiki/native-transports.html | false | boolean | *options* (advanced) | Allows to configure additional netty options using option. as prefix. For example option.child.keepAlive=false to set the netty option child.keepAlive=false. See the Netty documentation for possible options that can be used. | | Map | *receiveBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during inbound communication. Size is bytes. | 65536 | int | *receiveBufferSizePredictor* (advanced) | Configures the buffer size predictor. See details at Jetty documentation and this mail thread. | | int | *sendBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during outbound communication. Size is bytes. | 65536 | int | *transferExchange* (advanced) | Only used for TCP. You can transfer the exchange over the wire instead of just the body. The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *udpByteArrayCodec* (advanced) | For UDP only. If enabled the using byte array codec instead of Java serialization protocol. | false | boolean | *workerCount* (advanced) | When netty works on nio mode, it uses default workerCount parameter from Netty (which is cpu_core_threads x 2). User can use this option to override the default workerCount from Netty. | | int | *workerGroup* (advanced) | To use a explicit EventLoopGroup as the boss thread pool. For example to share a thread pool with multiple consumers or producers. By default each consumer or producer has their own worker pool with 2 x cpu count core threads. | | EventLoopGroup | *allowDefaultCodec* (codec) | The netty component installs a default codec if both, encoder/decoder is null and textline is false. Setting allowDefaultCodec to false prevents the netty component from installing a default codec as the first element in the filter chain. | true | boolean | *autoAppendDelimiter* (codec) | Whether or not to auto append missing end delimiter when sending using the textline codec. | true | boolean | *decoderMaxLineLength* (codec) | The max line length to use for the textline codec. | 1024 | int | *decoders* (codec) | A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *delimiter* (codec) | The delimiter to use for the textline codec. Possible values are LINE and NULL. There are 2 enums and the value can be one of: LINE, NULL | LINE | TextLineDelimiter | *encoders* (codec) | A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *encoding* (codec) | The encoding (a charset name) to use for the textline codec. If not provided, Camel will use the JVM default Charset. | | String | *textline* (codec) | Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; if not specified or the value is false, then Object Serialization is assumed over TCP - however only Strings are allowed to be serialized by default. | false | boolean | *enabledProtocols* (security) | Which protocols to enable when using SSL | TLSv1,TLSv1.1,TLSv1.2 | String | *keyStoreFile* (security) | Client side certificate keystore to be used for encryption | | File | *keyStoreFormat* (security) | Keystore format to be used for payload encryption. Defaults to JKS if not set | | String | *keyStoreResource* (security) | Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String | *needClientAuth* (security) | Configures whether the server needs client authentication when using SSL. | false | boolean | *passphrase* (security) | Password setting to use in order to encrypt/decrypt payloads sent using SSH | | String | *securityProvider* (security) | Security provider to be used for payload encryption. Defaults to SunX509 if not set. | | String | *ssl* (security) | Setting to specify whether SSL encryption is applied to this endpoint | false | boolean | *sslClientCertHeaders* (security) | When enabled and in SSL mode, then the Netty consumer will enrich the Camel Message with headers having information about the client certificate such as subject name, issuer name, serial number, and the valid date range. | false | boolean | *sslContextParameters* (security) | To configure security using SSLContextParameters | | SSLContextParameters | *sslHandler* (security) | Reference to a class that could be used to return an SSL Handler | | SslHandler | *trustStoreFile* (security) | Server side certificate keystore to be used for encryption | | File | *trustStoreResource* (security) | Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String | *useGlobalSslContextParameters* (security) | Enable usage of global SSL context parameters. | false | boolean |=== // component options: END // endpoint options: START The Netty endpoint is configured using URI syntax: ---- netty:protocol://host:port ---- with the following path and query parameters: === Path Parameters (3 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *protocol* | *Required* The protocol to use which can be tcp or udp. There are 2 enums and the value can be one of: tcp, udp | | String | *host* | *Required* The hostname. For the consumer the hostname is localhost or 0.0.0.0. For the producer the hostname is the remote host to connect to | | String | *port* | *Required* The host port number | | int |=== === Query Parameters (71 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *disconnect* (common) | Whether or not to disconnect(close) from Netty Channel right after use. Can be used for both consumer and producer. | false | boolean | *keepAlive* (common) | Setting to ensure socket is not closed due to inactivity | true | boolean | *reuseAddress* (common) | Setting to facilitate socket multiplexing | true | boolean | *reuseChannel* (common) | This option allows producers and consumers (in client mode) to reuse the same Netty Channel for the lifecycle of processing the Exchange. This is useful if you need to call a server multiple times in a Camel route and want to use the same network connection. When using this, the channel is not returned to the connection pool until the Exchange is done; or disconnected if the disconnect option is set to true. The reused Channel is stored on the Exchange as an exchange property with the key NettyConstants#NETTY_CHANNEL which allows you to obtain the channel during routing and use it as well. | false | boolean | *sync* (common) | Setting to set endpoint as one-way or request-response | true | boolean | *tcpNoDelay* (common) | Setting to improve TCP protocol performance | true | boolean | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *broadcast* (consumer) | Setting to choose Multicast over UDP | false | boolean | *clientMode* (consumer) | If the clientMode is true, netty consumer will connect the address as a TCP client. | false | boolean | *reconnect* (consumer) | Used only in clientMode in consumer, the consumer will attempt to reconnect on disconnection if this is enabled | true | boolean | *reconnectInterval* (consumer) | Used if reconnect and clientMode is enabled. The interval in milli seconds to attempt reconnection | 10000 | int | *backlog* (consumer) | Allows to configure a backlog for netty consumer (server). Note the backlog is just a best effort depending on the OS. Setting this option to a value such as 200, 500 or 1000, tells the TCP stack how long the accept queue can be If this option is not configured, then the backlog depends on OS setting. | | int | *bossCount* (consumer) | When netty works on nio mode, it uses default bossCount parameter from Netty, which is 1. User can use this option to override the default bossCount from Netty | 1 | int | *bossGroup* (consumer) | Set the BossGroup which could be used for handling the new connection of the server side across the NettyEndpoint | | EventLoopGroup | *disconnectOnNoReply* (consumer) | If sync is enabled then this option dictates NettyConsumer if it should disconnect where there is no reply to send back. | true | boolean | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | | ExceptionHandler | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. There are 3 enums and the value can be one of: InOnly, InOut, InOptionalOut | | ExchangePattern | *nettyServerBootstrapFactory* (consumer) | To use a custom NettyServerBootstrapFactory | | NettyServerBootstrapFactory | *networkInterface* (consumer) | When using UDP then this option can be used to specify a network interface by its name, such as eth0 to join a multicast group. | | String | *noReplyLogLevel* (consumer) | If sync is enabled this option dictates NettyConsumer which logging level to use when logging a there is no reply to send back. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverClosedChannelException{zwsp}CaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an java.nio.channels.ClosedChannelException then its logged using this logging level. This is used to avoid logging the closed channel exceptions, as clients can disconnect abruptly and then cause a flood of closed exceptions in the Netty server. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | DEBUG | LoggingLevel | *serverExceptionCaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an exception then its logged using this logging level. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverInitializerFactory* (consumer) | To use a custom ServerInitializerFactory | | ServerInitializerFactory | *usingExecutorService* (consumer) | Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. | true | boolean | *connectTimeout* (producer) | Time to wait for a socket connection to be available. Value is in milliseconds. | 10000 | int | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *requestTimeout* (producer) | Allows to use a timeout for the Netty producer when calling a remote server. By default no timeout is in use. The value is in milli seconds, so eg 30000 is 30 seconds. The requestTimeout is using Netty's ReadTimeoutHandler to trigger the timeout. | | long | *clientInitializerFactory* (producer) | To use a custom ClientInitializerFactory | | ClientInitializerFactory | *correlationManager* (producer) | To use a custom correlation manager to manage how request and reply messages are mapped when using request/reply with the netty producer. This should only be used if you have a way to map requests together with replies such as if there is correlation ids in both the request and reply messages. This can be used if you want to multiplex concurrent messages on the same channel (aka connection) in netty. When doing this you must have a way to correlate the request and reply messages so you can store the right reply on the inflight Camel Exchange before its continued routed. We recommend extending the TimeoutCorrelationManagerSupport when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. See also the producerPoolEnabled option for more details. | | NettyCamelStateCorrelationManager | *lazyChannelCreation* (producer) | Channels can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. | true | boolean | *producerPoolEnabled* (producer) | Whether producer pool is enabled or not. Important: If you turn this off then a single shared connection is used for the producer, also if you are doing request/reply. That means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement NettyCamelStateCorrelationManager as correlation manager and configure it via the correlationManager option. See also the correlationManager option for more details. | true | boolean | *producerPoolMaxActive* (producer) | Sets the cap on the number of objects that can be allocated by the pool (checked out to clients, or idle awaiting checkout) at a given time. Use a negative value for no limit. | -1 | int | *producerPoolMaxIdle* (producer) | Sets the cap on the number of idle instances in the pool. | 100 | int | *producerPoolMinEvictableIdle* (producer) | Sets the minimum amount of time (value in millis) an object may sit idle in the pool before it is eligible for eviction by the idle object evictor. | 300000 | long | *producerPoolMinIdle* (producer) | Sets the minimum number of instances allowed in the producer pool before the evictor thread (if active) spawns new objects. | | int | *udpConnectionlessSending* (producer) | This option supports connection less udp sending which is a real fire and forget. A connected udp send receive the PortUnreachableException if no one is listen on the receiving port. | false | boolean | *useByteBuf* (producer) | If the useByteBuf is true, netty producer will turn the message body into ByteBuf before sending it out. | false | boolean | *hostnameVerification* ( security) | To enable/disable hostname verification on SSLEngine | false | boolean | *allowSerializedHeaders* (advanced) | Only used for TCP when transferExchange is true. When set to true, serializable objects in headers and properties will be added to the exchange. Otherwise Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *channelGroup* (advanced) | To use a explicit ChannelGroup. | | ChannelGroup | *nativeTransport* (advanced) | Whether to use native transport instead of NIO. Native transport takes advantage of the host operating system and is only supported on some platforms. You need to add the netty JAR for the host operating system you are using. See more details at: \\http://netty.io/wiki/native-transports.html | false | boolean | *options* (advanced) | Allows to configure additional netty options using option. as prefix. For example option.child.keepAlive=false to set the netty option child.keepAlive=false. See the Netty documentation for possible options that can be used. | | Map | *receiveBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during inbound communication. Size is bytes. | 65536 | int | *receiveBufferSizePredictor* (advanced) | Configures the buffer size predictor. See details at Jetty documentation and this mail thread. | | int | *sendBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during outbound communication. Size is bytes. | 65536 | int | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used | false | boolean | *transferExchange* (advanced) | Only used for TCP. You can transfer the exchange over the wire instead of just the body. The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *udpByteArrayCodec* (advanced) | For UDP only. If enabled the using byte array codec instead of Java serialization protocol. | false | boolean | *workerCount* (advanced) | When netty works on nio mode, it uses default workerCount parameter from Netty (which is cpu_core_threads x 2). User can use this option to override the default workerCount from Netty. | | int | *workerGroup* (advanced) | To use a explicit EventLoopGroup as the boss thread pool. For example to share a thread pool with multiple consumers or producers. By default each consumer or producer has their own worker pool with 2 x cpu count core threads. | | EventLoopGroup | *allowDefaultCodec* (codec) | The netty component installs a default codec if both, encoder/decoder is null and textline is false. Setting allowDefaultCodec to false prevents the netty component from installing a default codec as the first element in the filter chain. | true | boolean | *autoAppendDelimiter* (codec) | Whether or not to auto append missing end delimiter when sending using the textline codec. | true | boolean | *decoderMaxLineLength* (codec) | The max line length to use for the textline codec. | 1024 | int | *decoders* (codec) | A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *delimiter* (codec) | The delimiter to use for the textline codec. Possible values are LINE and NULL. There are 2 enums and the value can be one of: LINE, NULL | LINE | TextLineDelimiter | *encoders* (codec) | A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *encoding* (codec) | The encoding (a charset name) to use for the textline codec. If not provided, Camel will use the JVM default Charset. | | String | *textline* (codec) | Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; if not specified or the value is false, then Object Serialization is assumed over TCP - however only Strings are allowed to be serialized by default. | false | boolean | *enabledProtocols* (security) | Which protocols to enable when using SSL | TLSv1,TLSv1.1,TLSv1.2 | String | *keyStoreFile* (security) | Client side certificate keystore to be used for encryption | | File | *keyStoreFormat* (security) | Keystore format to be used for payload encryption. Defaults to JKS if not set | | String | *keyStoreResource* (security) | Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String | *needClientAuth* (security) | Configures whether the server needs client authentication when using SSL. | false | boolean | *passphrase* (security) | Password setting to use in order to encrypt/decrypt payloads sent using SSH | | String | *securityProvider* (security) | Security provider to be used for payload encryption. Defaults to SunX509 if not set. | | String | *ssl* (security) | Setting to specify whether SSL encryption is applied to this endpoint | false | boolean | *sslClientCertHeaders* (security) | When enabled and in SSL mode, then the Netty consumer will enrich the Camel Message with headers having information about the client certificate such as subject name, issuer name, serial number, and the valid date range. | false | boolean | *sslContextParameters* (security) | To configure security using SSLContextParameters | | SSLContextParameters | *sslHandler* (security) | Reference to a class that could be used to return an SSL Handler | | SslHandler | *trustStoreFile* (security) | Server side certificate keystore to be used for encryption | | File | *trustStoreResource* (security) | Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String |=== // endpoint options: END == Registry based Options Codec Handlers and SSL Keystores can be enlisted in the Registry, such as in the Spring XML file. The values that could be passed in, are the following: [width=""100%"",cols=""10%,90%"",options=""header"",] |=== |Name |Description |`passphrase` |password setting to use in order to encrypt/decrypt payloads sent using SSH |`keyStoreFormat` |keystore format to be used for payload encryption. Defaults to ""JKS"" if not set |`securityProvider` |Security provider to be used for payload encryption. Defaults to ""SunX509"" if not set. |`keyStoreFile` |*deprecated:* Client side certificate keystore to be used for encryption |`trustStoreFile` |*deprecated:* Server side certificate keystore to be used for encryption |`keyStoreResource` |Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with `""classpath:""`, `""file:""`, or `""http:""` to load the resource from different systems. |`trustStoreResource` |Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with `""classpath:""`, `""file:""`, or `""http:""` to load the resource from different systems. |`sslHandler` |Reference to a class that could be used to return an SSL Handler |`encoder` |A custom `ChannelHandler` class that can be used to perform special marshalling of outbound payloads. Must override io.netty.channel.ChannelInboundHandlerAdapter. |`encoders` |A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. |`decoder` |A custom `ChannelHandler` class that can be used to perform special marshalling of inbound payloads. Must override io.netty.channel.ChannelOutboundHandlerAdapter. |`decoders` |A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. |=== [NOTE] ==== Read below about using non shareable encoders/decoders. ==== === Using non shareable encoders or decoders If your encoders or decoders are not shareable (e.g. they don't have the @Shareable class annotation), then your encoder/decoder must implement the `org.apache.camel.component.netty.ChannelHandlerFactory` interface, and return a new instance in the `newChannelHandler` method. This is to ensure the encoder/decoder can safely be used. If this is not the case, then the Netty component will log a WARN when an endpoint is created. The Netty component offers a `org.apache.camel.component.netty.ChannelHandlerFactories` factory class, that has a number of commonly used methods. == Sending Messages to/from a Netty endpoint === Netty Producer In Producer mode, the component provides the ability to send payloads to a socket endpoint using either TCP or UDP protocols (with optional SSL support). The producer mode supports both one-way and request-response based operations. === Netty Consumer In Consumer mode, the component provides the ability to: * listen on a specified socket using either TCP or UDP protocols (with optional SSL support), * receive requests on the socket using text/xml, binary and serialized object based payloads and * send them along on a route as message exchanges. The consumer mode supports both one-way and request-response based operations. == Examples === A UDP Netty endpoint using Request-Reply and serialized object payload Note that Object serialization is not allowed by default, and so a decoder must be configured. [source,java] ---- @BindToRegistry(""decoder"") public ChannelHandler getDecoder() throws Exception { return new DefaultChannelHandlerFactory() { @Override public ChannelHandler newChannelHandler() { return new DatagramPacketObjectDecoder(ClassResolvers.weakCachingResolver(null)); } }; } RouteBuilder builder = new RouteBuilder() { public void configure() { from(""netty:udp://0.0.0.0:5155?sync=true&decoders=#decoder"") .process(new Processor() { public void process(Exchange exchange) throws Exception { Poetry poetry = (Poetry) exchange.getIn().getBody(); // Process poetry in some way exchange.getOut().setBody(""Message received); } } } }; ---- === A TCP based Netty consumer endpoint using One-way communication [source,java] ---- RouteBuilder builder = new RouteBuilder() { public void configure() { from(""netty:tcp://0.0.0.0:5150"") .to(""mock:result""); } }; ---- === An SSL/TCP based Netty consumer endpoint using Request-Reply communication [[Netty-UsingtheJSSEConfigurationUtility]] Using the JSSE Configuration Utility The Netty component supports SSL/TLS configuration through the xref:manual::camel-configuration-utilities.adoc[Camel JSSE Configuration Utility]. This utility greatly decreases the amount of component specific code you need to write and is configurable at the endpoint and component levels. The following examples demonstrate how to use the utility with the Netty component. [[Netty-Programmaticconfigurationofthecomponent]] Programmatic configuration of the component [source,java] ---- KeyStoreParameters ksp = new KeyStoreParameters(); ksp.setResource(""/users/home/server/keystore.jks""); ksp.setPassword(""keystorePassword""); KeyManagersParameters kmp = new KeyManagersParameters(); kmp.setKeyStore(ksp); kmp.setKeyPassword(""keyPassword""); SSLContextParameters scp = new SSLContextParameters(); scp.setKeyManagers(kmp); NettyComponent nettyComponent = getContext().getComponent(""netty"", NettyComponent.class); nettyComponent.setSslContextParameters(scp); ---- [[Netty-SpringDSLbasedconfigurationofendpoint]] Spring DSL based configuration of endpoint [source,xml] ---- ... ... ... ... ---- [[Netty-UsingBasicSSLTLSconfigurationontheJettyComponent]] Using Basic SSL/TLS configuration on the Jetty Component [source,java] ---- Registry registry = context.getRegistry(); registry.bind(""password"", ""changeit""); registry.bind(""ksf"", new File(""src/test/resources/keystore.jks"")); registry.bind(""tsf"", new File(""src/test/resources/keystore.jks"")); context.addRoutes(new RouteBuilder() { public void configure() { String netty_ssl_endpoint = ""netty:tcp://0.0.0.0:5150?sync=true&ssl=true&passphrase=#password"" + ""&keyStoreFile=#ksf&trustStoreFile=#tsf""; String return_string = ""When You Go Home, Tell Them Of Us And Say,"" + ""For Your Tomorrow, We Gave Our Today.""; from(netty_ssl_endpoint) .process(new Processor() { public void process(Exchange exchange) throws Exception { exchange.getOut().setBody(return_string); } } } }); ---- [[Netty-GettingaccesstoSSLSessionandtheclientcertificate]] Getting access to SSLSession and the client certificate You can get access to the `javax.net.ssl.SSLSession` if you eg need to get details about the client certificate. When `ssl=true` then the xref:netty-component.adoc[Netty] component will store the `SSLSession` as a header on the Camel Message as shown below: [source,java] ---- SSLSession session = exchange.getIn().getHeader(NettyConstants.NETTY_SSL_SESSION, SSLSession.class); // get the first certificate which is client certificate javax.security.cert.X509Certificate cert = session.getPeerCertificateChain()[0]; Principal principal = cert.getSubjectDN(); ---- Remember to set `needClientAuth=true` to authenticate the client, otherwise `SSLSession` cannot access information about the client certificate, and you may get an exception `javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated`. You may also get this exception if the client certificate is expired or not valid etc. [TIP] ==== The option `sslClientCertHeaders` can be set to `true` which then enriches the Camel Message with headers having details about the client certificate. For example the subject name is readily available in the header `CamelNettySSLClientCertSubjectName`. ==== === Using Multiple Codecs In certain cases it may be necessary to add chains of encoders and decoders to the netty pipeline. To add multpile codecs to a camel netty endpoint the 'encoders' and 'decoders' uri parameters should be used. Like the 'encoder' and 'decoder' parameters they are used to supply references (lists of ChannelUpstreamHandlers and ChannelDownstreamHandlers) that should be added to the pipeline. Note that if encoders is specified then the encoder param will be ignored, similarly for decoders and the decoder param. [NOTE] ==== Read further above about using non shareable encoders/decoders. ==== The lists of codecs need to be added to the Camel's registry so they can be resolved when the endpoint is created. [source,java] ---- ChannelHandlerFactory lengthDecoder = ChannelHandlerFactories.newLengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4); StringDecoder stringDecoder = new StringDecoder(); registry.bind(""length-decoder"", lengthDecoder); registry.bind(""string-decoder"", stringDecoder); LengthFieldPrepender lengthEncoder = new LengthFieldPrepender(4); StringEncoder stringEncoder = new StringEncoder(); registry.bind(""length-encoder"", lengthEncoder); registry.bind(""string-encoder"", stringEncoder); List decoders = new ArrayList(); decoders.add(lengthDecoder); decoders.add(stringDecoder); List encoders = new ArrayList(); encoders.add(lengthEncoder); encoders.add(stringEncoder); registry.bind(""encoders"", encoders); registry.bind(""decoders"", decoders); ---- Spring's native collections support can be used to specify the codec lists in an application context [source,xml] ---- ---- The bean names can then be used in netty endpoint definitions either as a comma separated list or contained in a List e.g. [source,java] ---- from(""direct:multiple-codec"").to(""netty:tcp://0.0.0.0:{{port}}?encoders=#encoders&sync=false""); from(""netty:tcp://0.0.0.0:{{port}}?decoders=#length-decoder,#string-decoder&sync=false"").to(""mock:multiple-codec""); ---- or via XML. [source,xml] ---- ---- == Closing Channel When Complete When acting as a server you sometimes want to close the channel when, for example, a client conversion is finished. + You can do this by simply setting the endpoint option `disconnect=true`. However you can also instruct Camel on a per message basis as follows. + To instruct Camel to close the channel, you should add a header with the key `CamelNettyCloseChannelWhenComplete` set to a boolean `true` value. + For instance, the example below will close the channel after it has written the bye message back to the client: [source,java] ---- from(""netty:tcp://0.0.0.0:8080"").process(new Processor() { public void process(Exchange exchange) throws Exception { String body = exchange.getIn().getBody(String.class); exchange.getOut().setBody(""Bye "" + body); // some condition which determines if we should close if (close) { exchange.getOut().setHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, true); } } }); ---- [[Netty-Addingcustomchannelpipelinefactoriestogaincompletecontroloveracreatedpipeline]] Adding custom channel pipeline factories to gain complete control over a created pipeline == Custom pipeline Custom channel pipelines provide complete control to the user over the handler/interceptor chain by inserting custom handler(s), encoder(s) & decoder(s) without having to specify them in the Netty Endpoint URL in a very simple way. In order to add a custom pipeline, a custom channel pipeline factory must be created and registered with the context via the context registry (Registry, or the camel-spring ApplicationContextRegistry etc). A custom pipeline factory must be constructed as follows * A Producer linked channel pipeline factory must extend the abstract class `ClientPipelineFactory`. * A Consumer linked channel pipeline factory must extend the abstract class `ServerInitializerFactory`. * The classes should override the initChannel() method in order to insert custom handler(s), encoder(s) and decoder(s). Not overriding the `initChannel()` method creates a pipeline with no handlers, encoders or decoders wired to the pipeline. The example below shows how ServerInitializerFactory factory may be created === Using custom pipeline factory [source,java] ---- public class SampleServerInitializerFactory extends ServerInitializerFactory { private int maxLineSize = 1024; protected void initChannel(Channel ch) throws Exception { ChannelPipeline channelPipeline = ch.pipeline(); channelPipeline.addLast(""encoder-SD"", new StringEncoder(CharsetUtil.UTF_8)); channelPipeline.addLast(""decoder-DELIM"", new DelimiterBasedFrameDecoder(maxLineSize, true, Delimiters.lineDelimiter())); channelPipeline.addLast(""decoder-SD"", new StringDecoder(CharsetUtil.UTF_8)); // here we add the default Camel ServerChannelHandler for the consumer, to allow Camel to route the message etc. channelPipeline.addLast(""handler"", new ServerChannelHandler(consumer)); } } ---- The custom channel pipeline factory can then be added to the registry and instantiated/utilized on a camel route in the following way [source,java] ---- Registry registry = camelContext.getRegistry(); ServerInitializerFactory factory = new TestServerInitializerFactory(); registry.bind(""spf"", factory); context.addRoutes(new RouteBuilder() { public void configure() { String netty_ssl_endpoint = ""netty:tcp://0.0.0.0:5150?serverInitializerFactory=#spf"" String return_string = ""When You Go Home, Tell Them Of Us And Say,"" + ""For Your Tomorrow, We Gave Our Today.""; from(netty_ssl_endpoint) .process(new Processor() { public void process(Exchange exchange) throws Exception { exchange.getOut().setBody(return_string); } } } }); ---- == Reusing Netty boss and worker thread pools Netty has two kind of thread pools: boss and worker. By default each Netty consumer and producer has their private thread pools. If you want to reuse these thread pools among multiple consumers or producers then the thread pools must be created and enlisted in the Registry. For example using Spring XML we can create a shared worker thread pool using the `NettyWorkerPoolBuilder` with 2 worker threads as shown below: [source,xml] ---- ---- [TIP] ==== For boss thread pool there is a `org.apache.camel.component.netty.NettyServerBossPoolBuilder` builder for Netty consumers, and a `org.apache.camel.component.netty.NettyClientBossPoolBuilder` for the Netty producers. ==== Then in the Camel routes we can refer to this worker pools by configuring the `workerPool` option in the URI as shown below: [source,xml] ---- ... ---- And if we have another route we can refer to the shared worker pool: [source,xml] ---- ... ---- and so forth. == Multiplexing concurrent messages over a single connection with request/reply When using Netty for request/reply messaging via the netty producer then by default each message is sent via a non-shared connection (pooled). This ensures that replies are automatic being able to map to the correct request thread for further routing in Camel. In other words correlation between request/reply messages happens out-of-the-box because the replies comes back on the same connection that was used for sending the request; and this connection is not shared with others. When the response comes back, the connection is returned back to the connection pool, where it can be reused by others. However if you want to multiplex concurrent request/responses on a single shared connection, then you need to turn off the connection pooling by setting `producerPoolEnabled=false`. Now this means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement `NettyCamelStateCorrelationManager` as correlation manager and configure it via the `correlationManager=#myManager` option. [NOTE] ==== We recommend extending the `TimeoutCorrelationManagerSupport` when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. ==== You can find an example with the Apache Camel source code in the examples directory under the `camel-example-netty-custom-correlation` directory. include::camel-spring-boot::page$netty-starter.adoc[] ",12477,False,2366.3973406772493,median "[[main-component]] = Main Component //THIS FILE IS COPIED: EDIT THE SOURCE FILE: :page-source: core/camel-main/src/main/docs/main.adoc :docTitle: Main :artifactId: camel-main :description: Camel Main support :since: 3.0 :supportLevel: Stable //Manually maintained attributes :group: Core *Since Camel {since}* This module is used for running Camel standalone via a main class extended from `camel-main`. == Configuration options When running Camel via `camel-main` you can configure Camel in the `application.properties` file. The following table lists all the options: // main options: START [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *camel.main.allowUseOriginal{zwsp}Message* | Sets whether to allow access to the original message from Camel's error handler, or from org.apache.camel.spi.UnitOfWork.getOriginalInMessage(). Turning this off can optimize performance, as defensive copy of the original message is not needed. Default is false. | | boolean | *camel.main.autoConfiguration{zwsp}Enabled* | Whether auto configuration of components, dataformats, languages is enabled or not. When enabled the configuration parameters are loaded from the properties component and optionally from the classpath file META-INF/services/org/apache/camel/autowire.properties. You can prefix the parameters in the properties file with: - camel.component.name.option1=value1 - camel.component.name.option2=value2 - camel.dataformat.name.option1=value1 - camel.dataformat.name.option2=value2 - camel.language.name.option1=value1 - camel.language.name.option2=value2 Where name is the name of the component, dataformat or language such as seda,direct,jaxb. The auto configuration also works for any options on components that is a complex type (not standard Java type) and there has been an explicit single bean instance registered to the Camel registry via the org.apache.camel.spi.Registry#bind(String,Object) method or by using the org.apache.camel.BindToRegistry annotation style. This option is default enabled. | true | boolean | *camel.main.autoConfiguration{zwsp}EnvironmentVariablesEnabled* | Whether auto configuration should include OS environment variables as well. When enabled this allows to overrule any configuration using an OS environment variable. For example to set a shutdown timeout of 5 seconds: CAMEL_MAIN_SHUTDOWNTIMEOUT=5. This option is default enabled. | true | boolean | *camel.main.autoConfiguration{zwsp}FailFast* | Whether auto configuration should fail fast when configuring one ore more properties fails for whatever reason such as a invalid property name, etc. This option is default enabled. | true | boolean | *camel.main.autoConfiguration{zwsp}LogSummary* | Whether auto configuration should log a summary with the configured properties. This option is default enabled. | true | boolean | *camel.main.autoStartup* | Sets whether the object should automatically start when Camel starts. Important: Currently only routes can be disabled, as CamelContext's are always started. Note: When setting auto startup false on CamelContext then that takes precedence and no routes are started. You would need to start CamelContext explicit using the org.apache.camel.CamelContext.start() method, to start the context, and then you would need to start the routes manually using CamelContext.getRouteController().startRoute(String). Default is true to always start up. | true | boolean | *camel.main.autowireComponent{zwsp}Properties* | Whether autowiring components with properties that are of same type, which has been added to the Camel registry, as a singleton instance. This is used for convention over configuration to inject DataSource, AmazonLogin instances to the components. This option is default enabled. | true | boolean | *camel.main.autowireComponent{zwsp}PropertiesAllowPrivateSetter* | Whether autowiring components allows to use private setter method when setting the value. This may be needed in some rare situations when some configuration classes may configure via constructors over setters. But constructor configuration is more cumbersome to use via .properties files etc. | true | boolean | *camel.main.autowireComponent{zwsp}PropertiesDeep* | Whether autowiring components (with deep nesting by attempting to walk as deep down the object graph by creating new empty objects on the way if needed) with properties that are of same type, which has been added to the Camel registry, as a singleton instance. This is used for convention over configuration to inject DataSource, AmazonLogin instances to the components. This option is default disabled. | | boolean | *camel.main.autowireComponent{zwsp}PropertiesNonNullOnly* | Whether to only autowire if the property has no default value or has not been configured explicit. This option is default disabled. | | boolean | *camel.main.backlogTracing* | Sets whether backlog tracing is enabled or not. Default is false. | | boolean | *camel.main.beanIntrospection{zwsp}ExtendedStatistics* | Sets whether bean introspection uses extended statistics. The default is false. | | boolean | *camel.main.beanIntrospection{zwsp}LoggingLevel* | Sets the logging level used by bean introspection, logging activity of its usage. The default is TRACE. | | LoggingLevel | *camel.main.caseInsensitive{zwsp}Headers* | Whether to use case sensitive or insensitive headers. Important: When using case sensitive (this is set to false). Then the map is case sensitive which means headers such as content-type and Content-Type are two different keys which can be a problem for some protocols such as HTTP based, which rely on case insensitive headers. However case sensitive implementations can yield faster performance. Therefore use case sensitive implementation with care. Default is true. | true | boolean | *camel.main.configuration{zwsp}Classes* | Sets classes names that will be used to configure the camel context as example by providing custom beans through org.apache.camel.BindToRegistry annotation. | | String | *camel.main.configurations* | Sets the configuration objects used to configure the camel context. | | List | *camel.main.consumerTemplate{zwsp}CacheSize* | Consumer template endpoints cache size. | 1000 | int | *camel.main.durationHitExitCode* | Sets the exit code for the application if duration was hit | | int | *camel.main.durationMaxIdle{zwsp}Seconds* | To specify for how long time in seconds Camel can be idle before automatic terminating the JVM. You can use this to run Camel for a short while. | | int | *camel.main.durationMaxMessages* | To specify how many messages to process by Camel before automatic terminating the JVM. You can use this to run Camel for a short while. | | int | *camel.main.durationMaxSeconds* | To specify for how long time in seconds to keep running the JVM before automatic terminating the JVM. You can use this to run Camel for a short while. | | int | *camel.main.endpointBasic{zwsp}PropertyBinding* | Whether the endpoint should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities. The default value is false. | | boolean | *camel.main.endpointBridgeError{zwsp}Handler* | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN/ERROR level and ignored. The default value is false. | | boolean | *camel.main.endpointLazyStart{zwsp}Producer* | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. The default value is false. | | boolean | *camel.main.endpointRuntime{zwsp}StatisticsEnabled* | Sets whether endpoint runtime statistics is enabled (gathers runtime usage of each incoming and outgoing endpoints). The default value is false. | | boolean | *camel.main.fileConfigurations* | Directory to load additional configuration files that contains configuration values that takes precedence over any other configuration. This can be used to refer to files that may have secret configuration that has been mounted on the file system for containers. You can specify a pattern to load from sub directories and a name pattern such as /var/app/secret/.properties, multiple directories can be separated by comma. | | String | *camel.main.inflightRepository{zwsp}BrowseEnabled* | Sets whether the inflight repository should allow browsing each inflight exchange. This is by default disabled as there is a very slight performance overhead when enabled. | | boolean | *camel.main.javaRoutesExclude{zwsp}Pattern* | Used for exclusive filtering component scanning of RouteBuilder classes with Component annotation. The exclusive filtering takes precedence over inclusive filtering. The pattern is using Ant-path style pattern. Multiple patterns can be specified separated by comma. For example to exclude all classes starting with Bar use: **/Bar* To exclude all routes form a specific package use: com/mycompany/bar/* To exclude all routes form a specific package and its sub-packages use double wildcards: com/mycompany/bar/** And to exclude all routes from two specific packages use: com/mycompany/bar/*,com/mycompany/stuff/* | | String | *camel.main.javaRoutesInclude{zwsp}Pattern* | Used for inclusive filtering component scanning of RouteBuilder classes with Component annotation. The exclusive filtering takes precedence over inclusive filtering. The pattern is using Ant-path style pattern. Multiple patterns can be specified separated by comma. For example to include all classes starting with Foo use: **/Foo To include all routes form a specific package use: com/mycompany/foo/* To include all routes form a specific package and its sub-packages use double wildcards: com/mycompany/foo/** And to include all routes from two specific packages use: com/mycompany/foo/*,com/mycompany/stuff/* | | String | *camel.main.jmxEnabled* | Enable JMX in your Camel application. | true | boolean | *camel.main.jmxManagementName{zwsp}Pattern* | The naming pattern for creating the CamelContext JMX management name. The default pattern is #name# | #name# | String | *camel.main.jmxManagement{zwsp}StatisticsLevel* | Sets the JMX statistics level, the level can be set to Extended to gather additional information The default value is Default. | Default | ManagementStatisticsLevel | *camel.main.lightweight* | Experimental: Configure the context to be lightweight. This will trigger some optimizations and memory reduction options. Lightweight context have some limitations. At this moment, dynamic endpoint destinations are not supported. | | boolean | *camel.main.loadTypeConverters* | Whether to load custom type converters by scanning classpath. This is used for backwards compatibility with Camel 2.x. Its recommended to migrate to use fast type converter loading by setting Converter(loader = true) on your custom type converter classes. | | boolean | *camel.main.logDebugMaxChars* | Is used to limit the maximum length of the logging Camel message bodies. If the message body is longer than the limit, the log message is clipped. Use -1 to have unlimited length. Use for example 1000 to log at most 1000 characters. | | int | *camel.main.logExhaustedMessage{zwsp}Body* | Sets whether to log exhausted message body with message history. Default is false. | | boolean | *camel.main.logMask* | Sets whether log mask is enabled or not. Default is false. | | boolean | *camel.main.mdcLoggingKeys{zwsp}Pattern* | Sets the pattern used for determine which custom MDC keys to propagate during message routing when the routing engine continues routing asynchronously for the given message. Setting this pattern to will propagate all custom keys. Or setting the pattern to foo,bar will propagate any keys starting with either foo or bar. Notice that a set of standard Camel MDC keys are always propagated which starts with camel. as key name. The match rules are applied in this order (case insensitive): 1. exact match, returns true 2. wildcard match (pattern ends with a and the name starts with the pattern), returns true 3. regular expression match, returns true 4. otherwise returns false | | String | *camel.main.messageHistory* | Sets whether message history is enabled or not. Default is false. | | boolean | *camel.main.name* | Sets the name of the CamelContext. | | String | *camel.main.packageScanRoute{zwsp}Builders* | Sets package names for scanning for org.apache.camel.builder.RouteBuilder classes as candidates to be included. If you are using Spring Boot then its instead recommended to use Spring Boots component scanning and annotate your route builder classes with Component. In other words only use this for Camel Main in standalone mode. | | String | *camel.main.producerTemplate{zwsp}CacheSize* | Producer template endpoints cache size. | 1000 | int | *camel.main.routeControllerBack{zwsp}OffDelay* | Backoff delay in millis when restarting a route that failed to startup. | | long | *camel.main.routeControllerBack{zwsp}OffMaxAttempts* | Backoff maximum number of attempts to restart a route that failed to startup. When this threshold has been exceeded then the controller will give up attempting to restart the route, and the route will remain as stopped. | | long | *camel.main.routeControllerBack{zwsp}OffMaxDelay* | Backoff maximum delay in millis when restarting a route that failed to startup. | | long | *camel.main.routeControllerBack{zwsp}OffMaxElapsedTime* | Backoff maximum elapsed time in millis, after which the backoff should be considered exhausted and no more attempts should be made. | | long | *camel.main.routeControllerBack{zwsp}OffMultiplier* | Backoff multiplier to use for exponential backoff. This is used to extend the delay between restart attempts. | | double | *camel.main.routeController{zwsp}ExcludeRoutes* | Pattern for filtering routes to be included as supervised. The pattern is matching on route id, and endpoint uri for the route. Multiple patterns can be separated by comma. For example to include all kafka routes, you can say kafka:. And to include routes with specific route ids myRoute,myOtherRoute. The pattern supports wildcards and uses the matcher from org.apache.camel.support.PatternHelper#matchPattern. | | String | *camel.main.routeController{zwsp}IncludeRoutes* | Pattern for filtering routes to be excluded as supervised. The pattern is matching on route id, and endpoint uri for the route. Multiple patterns can be separated by comma. For example to exclude all JMS routes, you can say jms:. And to exclude routes with specific route ids mySpecialRoute,myOtherSpecialRoute. The pattern supports wildcards and uses the matcher from org.apache.camel.support.PatternHelper#matchPattern. | | String | *camel.main.routeController{zwsp}InitialDelay* | Initial delay in milli seconds before the route controller starts, after CamelContext has been started. | | long | *camel.main.routeController{zwsp}RouteStartupLoggingLevel* | Sets the logging level used for logging route startup activity. By default INFO level is used. You can use this to change the level for example to OFF if this kind of logging is not wanted. | INFO | LoggingLevel | *camel.main.routeController{zwsp}SuperviseEnabled* | To enable using supervising route controller which allows Camel to startup and then the controller takes care of starting the routes in a safe manner. This can be used when you want to startup Camel despite a route may otherwise fail fast during startup and cause Camel to fail to startup as well. By delegating the route startup to the supervising route controller then its manages the startup using a background thread. The controller allows to be configured with various settings to attempt to restart failing routes. | | boolean | *camel.main.routeController{zwsp}ThreadPoolSize* | The number of threads used by the route controller scheduled thread pool that are used for restarting routes. The pool uses 1 thread by default, but you can increase this to allow the controller to concurrently attempt to restart multiple routes in case more than one route has problems starting. | | int | *camel.main.routeController{zwsp}UnhealthyOnExhausted* | Whether to mark the route as unhealthy (down) when all restarting attempts (backoff) have failed and the route is not successfully started and the route manager is giving up. Setting this to true allows health checks to know about this and can report the Camel application as DOWN. The default is false. | | boolean | *camel.main.routeFilterExclude{zwsp}Pattern* | Used for filtering routes routes matching the given pattern, which follows the following rules: - Match by route id - Match by route input endpoint uri The matching is using exact match, by wildcard and regular expression as documented by PatternHelper#matchPattern(String,String) . For example to only include routes which starts with foo in their route id's, use: include=foo* And to exclude routes which starts from JMS endpoints, use: exclude=jms:* Multiple patterns can be separated by comma, for example to exclude both foo and bar routes, use: exclude=foo*,bar* Exclude takes precedence over include. | | String | *camel.main.routeFilterInclude{zwsp}Pattern* | Used for filtering routes routes matching the given pattern, which follows the following rules: - Match by route id - Match by route input endpoint uri The matching is using exact match, by wildcard and regular expression as documented by PatternHelper#matchPattern(String,String) . For example to only include routes which starts with foo in their route id's, use: include=foo* And to exclude routes which starts from JMS endpoints, use: exclude=jms:* Multiple patterns can be separated by comma, for example to exclude both foo and bar routes, use: exclude=foo*,bar* Exclude takes precedence over include. | | String | *camel.main.routesBuilder{zwsp}Classes* | Sets classes names that implement RoutesBuilder . | | String | *camel.main.routesBuilders* | Sets the RoutesBuilder instances. | | List | *camel.main.routesCollector{zwsp}Enabled* | Whether the routes collector is enabled or not. When enabled Camel will auto-discover routes (RouteBuilder instances from the registry and also load additional XML routes from the file system. The routes collector is default enabled. | true | boolean | *camel.main.shutdownLogInflight{zwsp}ExchangesOnTimeout* | Sets whether to log information about the inflight Exchanges which are still running during a shutdown which didn't complete without the given timeout. This requires to enable the option inflightRepositoryBrowseEnabled. | true | boolean | *camel.main.shutdownNowOn{zwsp}Timeout* | Sets whether to force shutdown of all consumers when a timeout occurred and thus not all consumers was shutdown within that period. You should have good reasons to set this option to false as it means that the routes keep running and is halted abruptly when CamelContext has been shutdown. | true | boolean | *camel.main.shutdownRoutesIn{zwsp}ReverseOrder* | Sets whether routes should be shutdown in reverse or the same order as they where started. | true | boolean | *camel.main.shutdownSuppress{zwsp}LoggingOnTimeout* | Whether Camel should try to suppress logging during shutdown and timeout was triggered, meaning forced shutdown is happening. And during forced shutdown we want to avoid logging errors/warnings et all in the logs as a side-effect of the forced timeout. Notice the suppress is a best effort as there may still be some logs coming from 3rd party libraries and whatnot, which Camel cannot control. This option is default false. | | boolean | *camel.main.shutdownTimeout* | Timeout in seconds to graceful shutdown Camel. | 45 | int | *camel.main.streamCachingAny{zwsp}SpoolRules* | Sets whether if just any of the org.apache.camel.spi.StreamCachingStrategy.SpoolRule rules returns true then shouldSpoolCache(long) returns true, to allow spooling to disk. If this option is false, then all the org.apache.camel.spi.StreamCachingStrategy.SpoolRule must return true. The default value is false which means that all the rules must return true. | | boolean | *camel.main.streamCachingBuffer{zwsp}Size* | Sets the stream caching buffer size to use when allocating in-memory buffers used for in-memory stream caches. The default size is 4096. | | int | *camel.main.streamCaching{zwsp}Enabled* | Sets whether stream caching is enabled or not. Default is false. | | boolean | *camel.main.streamCachingRemove{zwsp}SpoolDirectoryWhenStopping* | Whether to remove stream caching temporary directory when stopping. This option is default true. | true | boolean | *camel.main.streamCachingSpool{zwsp}Cipher* | Sets a stream caching cipher name to use when spooling to disk to write with encryption. By default the data is not encrypted. | | String | *camel.main.streamCachingSpool{zwsp}Directory* | Sets the stream caching spool (temporary) directory to use for overflow and spooling to disk. If no spool directory has been explicit configured, then a temporary directory is created in the java.io.tmpdir directory. | | String | *camel.main.streamCachingSpool{zwsp}Threshold* | Stream caching threshold in bytes when overflow to disk is activated. The default threshold is 128kb. Use -1 to disable overflow to disk. | | long | *camel.main.streamCachingSpool{zwsp}UsedHeapMemoryLimit* | Sets what the upper bounds should be when streamCachingSpoolUsedHeapMemoryThreshold is in use. | | String | *camel.main.streamCachingSpool{zwsp}UsedHeapMemoryThreshold* | Sets a percentage (1-99) of used heap memory threshold to activate stream caching spooling to disk. | | int | *camel.main.streamCaching{zwsp}StatisticsEnabled* | Sets whether stream caching statistics is enabled. | | boolean | *camel.main.threadNamePattern* | Sets the thread name pattern used for creating the full thread name. The default pattern is: Camel (#camelId#) thread ##counter# - #name# Where #camelId# is the name of the CamelContext. and #counter# is a unique incrementing counter. and #name# is the regular thread name. You can also use #longName# which is the long thread name which can includes endpoint parameters etc. | | String | *camel.main.tracing* | Sets whether tracing is enabled or not. Default is false. | | boolean | *camel.main.tracingPattern* | Tracing pattern to match which node EIPs to trace. For example to match all To EIP nodes, use to. The pattern matches by node and route id's Multiple patterns can be separated by comma. | | String | *camel.main.useBreadcrumb* | Set whether breadcrumb is enabled. The default value is false. | | boolean | *camel.main.useDataType* | Whether to enable using data type on Camel messages. Data type are automatic turned on if one ore more routes has been explicit configured with input and output types. Otherwise data type is default off. | | boolean | *camel.main.useMdcLogging* | To turn on MDC logging | | boolean | *camel.main.xmlRests* | Directory to scan for adding additional XML rests. You can turn this off by setting the value to false. Files can be loaded from either classpath or file by prefixing with classpath: or file: Wildcards is supported using a ANT pattern style paths, such as classpath:**/*camel*.xml Notice when using wildcards, then there is additional overhead as the classpath is scanned, where as if you specific the exact name for each XML file is faster as no classpath scanning is needed. Multiple directories can be specified and separated by comma, such as: file:/myapp/mycamel/*.xml,file:/myapp/myothercamel/*.xml | classpath:camel-rest/*.xml | String | *camel.main.xmlRoutes* | Directory to scan for adding additional XML routes. You can turn this off by setting the value to false. Files can be loaded from either classpath or file by prefixing with classpath: or file: Wildcards is supported using a ANT pattern style paths, such as classpath:**/*camel*.xml Notice when using wildcards, then there is additional overhead as the classpath is scanned, where as if you specific the exact name for each XML file is faster as no classpath scanning is needed. Multiple directories can be specified and separated by comma, such as: file:/myapp/mycamel/*.xml,file:/myapp/myothercamel/*.xml | classpath:camel/*.xml | String | *camel.main.xmlRouteTemplates* | Directory to scan for adding additional XML route templates. You can turn this off by setting the value to false. Files can be loaded from either classpath or file by prefixing with classpath: or file: Wildcards is supported using a ANT pattern style paths, such as classpath:**/*template-*.xml Notice when using wildcards, then there is additional overhead as the classpath is scanned, where as if you specific the exact name for each XML file is faster as no classpath scanning is needed. Multiple directories can be specified and separated by comma, such as: file:/myapp/mycamel/*.xml,file:/myapp/myothercamel/*.xml | classpath:camel-template/*.xml | String | *camel.faulttolerance.bulkhead{zwsp}Enabled* | Whether bulkhead is enabled or not on the circuit breaker. Default is false. | false | Boolean | *camel.faulttolerance.bulkhead{zwsp}ExecutorServiceRef* | References to a custom thread pool to use when bulkhead is enabled. | | String | *camel.faulttolerance.bulkhead{zwsp}MaxConcurrentCalls* | Configures the max amount of concurrent calls the bulkhead will support. Default value is 10. | 10 | Integer | *camel.faulttolerance.bulkhead{zwsp}WaitingTaskQueue* | Configures the task queue size for holding waiting tasks to be processed by the bulkhead. Default value is 10. | 10 | Integer | *camel.faulttolerance.circuit{zwsp}BreakerRef* | Refers to an existing io.smallrye.faulttolerance.core.circuit.breaker.CircuitBreaker instance to lookup and use from the registry. When using this, then any other circuit breaker options are not in use. | | String | *camel.faulttolerance.delay* | Control how long the circuit breaker stays open. The value are in seconds and the default is 5 seconds. | 5 | Long | *camel.faulttolerance.failure{zwsp}Ratio* | Configures the failure rate threshold in percentage. If the failure rate is equal or greater than the threshold the CircuitBreaker transitions to open and starts short-circuiting calls. The threshold must be greater than 0 and not greater than 100. Default value is 50 percentage. | 50 | Integer | *camel.faulttolerance.request{zwsp}VolumeThreshold* | Controls the size of the rolling window used when the circuit breaker is closed Default value is 20. | 20 | Integer | *camel.faulttolerance.success{zwsp}Threshold* | Controls the number of trial calls which are allowed when the circuit breaker is half-open Default value is 1. | 1 | Integer | *camel.faulttolerance.timeout{zwsp}Duration* | Configures the thread execution timeout. Default value is 1000 milliseconds. | 1000 | Long | *camel.faulttolerance.timeout{zwsp}Enabled* | Whether timeout is enabled or not on the circuit breaker. Default is false. | false | Boolean | *camel.faulttolerance.timeout{zwsp}PoolSize* | Configures the pool size of the thread pool when timeout is enabled. Default value is 10. | 10 | Integer | *camel.faulttolerance.timeout{zwsp}ScheduledExecutorServiceRef* | References to a custom thread pool to use when timeout is enabled | | String | *camel.health.config* | Set additional HealthConfigurationProperties for fine grained configuration of health checks. | | Map | *camel.health.contextEnabled* | Whether context health check is enabled | true | Boolean | *camel.health.enabled* | Whether health check is enabled globally | true | Boolean | *camel.health.registryEnabled* | Whether registry health check is enabled | true | Boolean | *camel.health.routesEnabled* | Whether routes health check is enabled | true | Boolean | *camel.hystrix.allowMaximumSize{zwsp}ToDivergeFromCoreSize* | Allows the configuration for maximumSize to take effect. That value can then be equal to, or higher, than coreSize | | Boolean | *camel.hystrix.circuitBreaker{zwsp}Enabled* | Whether to use a HystrixCircuitBreaker or not. If false no circuit-breaker logic will be used and all requests permitted. This is similar in effect to circuitBreakerForceClosed() except that continues tracking metrics and knowing whether it should be open/closed, this property results in not even instantiating a circuit-breaker. | | Boolean | *camel.hystrix.circuitBreaker{zwsp}ErrorThresholdPercentage* | Error percentage threshold (as whole number such as 50) at which point the circuit breaker will trip open and reject requests. It will stay tripped for the duration defined in circuitBreakerSleepWindowInMilliseconds; The error percentage this is compared against comes from HystrixCommandMetrics.getHealthCounts(). | | Integer | *camel.hystrix.circuitBreaker{zwsp}ForceClosed* | If true the HystrixCircuitBreaker#allowRequest() will always return true to allow requests regardless of the error percentage from HystrixCommandMetrics.getHealthCounts(). The circuitBreakerForceOpen() property takes precedence so if it set to true this property does nothing. | | Boolean | *camel.hystrix.circuitBreaker{zwsp}ForceOpen* | If true the HystrixCircuitBreaker.allowRequest() will always return false, causing the circuit to be open (tripped) and reject all requests. This property takes precedence over circuitBreakerForceClosed(); | | Boolean | *camel.hystrix.circuitBreaker{zwsp}RequestVolumeThreshold* | Minimum number of requests in the metricsRollingStatisticalWindowInMilliseconds() that must exist before the HystrixCircuitBreaker will trip. If below this number the circuit will not trip regardless of error percentage. | | Integer | *camel.hystrix.circuitBreaker{zwsp}SleepWindowInMilliseconds* | The time in milliseconds after a HystrixCircuitBreaker trips open that it should wait before trying requests again. | | Integer | *camel.hystrix.corePoolSize* | Core thread-pool size that gets passed to java.util.concurrent.ThreadPoolExecutor#setCorePoolSize(int) | | Integer | *camel.hystrix.execution{zwsp}IsolationSemaphoreMax{zwsp}ConcurrentRequests* | Number of concurrent requests permitted to HystrixCommand.run(). Requests beyond the concurrent limit will be rejected. Applicable only when executionIsolationStrategy == SEMAPHORE. | | Integer | *camel.hystrix.execution{zwsp}IsolationStrategy* | What isolation strategy HystrixCommand.run() will be executed with. If THREAD then it will be executed on a separate thread and concurrent requests limited by the number of threads in the thread-pool. If SEMAPHORE then it will be executed on the calling thread and concurrent requests limited by the semaphore count. | | String | *camel.hystrix.execution{zwsp}IsolationThreadInterruptOn{zwsp}Timeout* | Whether the execution thread should attempt an interrupt (using Future#cancel ) when a thread times out. Applicable only when executionIsolationStrategy() == THREAD. | | Boolean | *camel.hystrix.executionTimeout{zwsp}Enabled* | Whether the timeout mechanism is enabled for this command | | Boolean | *camel.hystrix.executionTimeout{zwsp}InMilliseconds* | Time in milliseconds at which point the command will timeout and halt execution. If executionIsolationThreadInterruptOnTimeout == true and the command is thread-isolated, the executing thread will be interrupted. If the command is semaphore-isolated and a HystrixObservableCommand, that command will get unsubscribed. | | Integer | *camel.hystrix.fallbackEnabled* | Whether HystrixCommand.getFallback() should be attempted when failure occurs. | | Boolean | *camel.hystrix.fallback{zwsp}IsolationSemaphoreMax{zwsp}ConcurrentRequests* | Number of concurrent requests permitted to HystrixCommand.getFallback(). Requests beyond the concurrent limit will fail-fast and not attempt retrieving a fallback. | | Integer | *camel.hystrix.groupKey* | Sets the group key to use. The default value is CamelHystrix. | | String | *camel.hystrix.keepAliveTime* | Keep-alive time in minutes that gets passed to ThreadPoolExecutor#setKeepAliveTime(long,TimeUnit) | | Integer | *camel.hystrix.maximumSize* | Maximum thread-pool size that gets passed to ThreadPoolExecutor#setMaximumPoolSize(int) . This is the maximum amount of concurrency that can be supported without starting to reject HystrixCommands. Please note that this setting only takes effect if you also set allowMaximumSizeToDivergeFromCoreSize | | Integer | *camel.hystrix.maxQueueSize* | Max queue size that gets passed to BlockingQueue in HystrixConcurrencyStrategy.getBlockingQueue(int) This should only affect the instantiation of a threadpool - it is not eliglible to change a queue size on the fly. For that, use queueSizeRejectionThreshold(). | | Integer | *camel.hystrix.metricsHealth{zwsp}SnapshotIntervalInMilliseconds* | Time in milliseconds to wait between allowing health snapshots to be taken that calculate success and error percentages and affect HystrixCircuitBreaker.isOpen() status. On high-volume circuits the continual calculation of error percentage can become CPU intensive thus this controls how often it is calculated. | | Integer | *camel.hystrix.metricsRolling{zwsp}PercentileBucketSize* | Maximum number of values stored in each bucket of the rolling percentile. This is passed into HystrixRollingPercentile inside HystrixCommandMetrics. | | Integer | *camel.hystrix.metricsRolling{zwsp}PercentileEnabled* | Whether percentile metrics should be captured using HystrixRollingPercentile inside HystrixCommandMetrics. | | Boolean | *camel.hystrix.metricsRolling{zwsp}PercentileWindowBuckets* | Number of buckets the rolling percentile window is broken into. This is passed into HystrixRollingPercentile inside HystrixCommandMetrics. | | Integer | *camel.hystrix.metricsRolling{zwsp}PercentileWindowInMilliseconds* | Duration of percentile rolling window in milliseconds. This is passed into HystrixRollingPercentile inside HystrixCommandMetrics. | | Integer | *camel.hystrix.metricsRolling{zwsp}StatisticalWindowBuckets* | Number of buckets the rolling statistical window is broken into. This is passed into HystrixRollingNumber inside HystrixCommandMetrics. | | Integer | *camel.hystrix.metricsRolling{zwsp}StatisticalWindowIn{zwsp}Milliseconds* | This property sets the duration of the statistical rolling window, in milliseconds. This is how long metrics are kept for the thread pool. The window is divided into buckets and rolls by those increments. | | Integer | *camel.hystrix.queueSize{zwsp}RejectionThreshold* | Queue size rejection threshold is an artificial max size at which rejections will occur even if maxQueueSize has not been reached. This is done because the maxQueueSize of a BlockingQueue can not be dynamically changed and we want to support dynamically changing the queue size that affects rejections. This is used by HystrixCommand when queuing a thread for execution. | | Integer | *camel.hystrix.requestLog{zwsp}Enabled* | Whether HystrixCommand execution and events should be logged to HystrixRequestLog. | | Boolean | *camel.hystrix.threadPoolKey* | Sets the thread pool key to use. Will by default use the same value as groupKey has been configured to use. | | String | *camel.hystrix.threadPool{zwsp}RollingNumberStatisticalWindow{zwsp}Buckets* | Number of buckets the rolling statistical window is broken into. This is passed into HystrixRollingNumber inside each HystrixThreadPoolMetrics instance. | | Integer | *camel.hystrix.threadPool{zwsp}RollingNumberStatisticalWindow{zwsp}InMilliseconds* | Duration of statistical rolling window in milliseconds. This is passed into HystrixRollingNumber inside each HystrixThreadPoolMetrics instance. | | Integer | *camel.lra.coordinatorContext{zwsp}Path* | The context-path for the LRA coordinator. Is default /lra-coordinator | /lra-coordinator | String | *camel.lra.coordinatorUrl* | The URL for the LRA coordinator service that orchestrates the transactions | | String | *camel.lra.localParticipant{zwsp}ContextPath* | The context-path for the local participant. Is default /lra-participant | /lra-participant | String | *camel.lra.localParticipantUrl* | The URL for the local participant | | String | *camel.resilience4j.automatic{zwsp}TransitionFromOpenToHalfOpen{zwsp}Enabled* | Enables automatic transition from OPEN to HALF_OPEN state once the waitDurationInOpenState has passed. | | Boolean | *camel.resilience4j.bulkhead{zwsp}Enabled* | Whether bulkhead is enabled or not on the circuit breaker. | false | Boolean | *camel.resilience4j.bulkheadMax{zwsp}ConcurrentCalls* | Configures the max amount of concurrent calls the bulkhead will support. | | Integer | *camel.resilience4j.bulkheadMax{zwsp}WaitDuration* | Configures a maximum amount of time which the calling thread will wait to enter the bulkhead. If bulkhead has space available, entry is guaranteed and immediate. If bulkhead is full, calling threads will contest for space, if it becomes available. maxWaitDuration can be set to 0. Note: for threads running on an event-loop or equivalent (rx computation pool, etc), setting maxWaitDuration to 0 is highly recommended. Blocking an event-loop thread will most likely have a negative effect on application throughput. | | Integer | *camel.resilience4j.circuit{zwsp}BreakerRef* | Refers to an existing io.github.resilience4j.circuitbreaker.CircuitBreaker instance to lookup and use from the registry. When using this, then any other circuit breaker options are not in use. | | String | *camel.resilience4j.configRef* | Refers to an existing io.github.resilience4j.circuitbreaker.CircuitBreakerConfig instance to lookup and use from the registry. | | String | *camel.resilience4j.failureRate{zwsp}Threshold* | Configures the failure rate threshold in percentage. If the failure rate is equal or greater than the threshold the CircuitBreaker transitions to open and starts short-circuiting calls. The threshold must be greater than 0 and not greater than 100. Default value is 50 percentage. | 50 | Float | *camel.resilience4j.minimum{zwsp}NumberOfCalls* | Configures configures the minimum number of calls which are required (per sliding window period) before the CircuitBreaker can calculate the error rate. For example, if minimumNumberOfCalls is 10, then at least 10 calls must be recorded, before the failure rate can be calculated. If only 9 calls have been recorded the CircuitBreaker will not transition to open even if all 9 calls have failed. Default minimumNumberOfCalls is 100 | 100 | Integer | *camel.resilience4j.permitted{zwsp}NumberOfCallsInHalfOpenState* | Configures the number of permitted calls when the CircuitBreaker is half open. The size must be greater than 0. Default size is 10. | 10 | Integer | *camel.resilience4j.sliding{zwsp}WindowSize* | Configures the size of the sliding window which is used to record the outcome of calls when the CircuitBreaker is closed. slidingWindowSize configures the size of the sliding window. Sliding window can either be count-based or time-based. If slidingWindowType is COUNT_BASED, the last slidingWindowSize calls are recorded and aggregated. If slidingWindowType is TIME_BASED, the calls of the last slidingWindowSize seconds are recorded and aggregated. The slidingWindowSize must be greater than 0. The minimumNumberOfCalls must be greater than 0. If the slidingWindowType is COUNT_BASED, the minimumNumberOfCalls cannot be greater than slidingWindowSize . If the slidingWindowType is TIME_BASED, you can pick whatever you want. Default slidingWindowSize is 100. | 100 | Integer | *camel.resilience4j.sliding{zwsp}WindowType* | Configures the type of the sliding window which is used to record the outcome of calls when the CircuitBreaker is closed. Sliding window can either be count-based or time-based. If slidingWindowType is COUNT_BASED, the last slidingWindowSize calls are recorded and aggregated. If slidingWindowType is TIME_BASED, the calls of the last slidingWindowSize seconds are recorded and aggregated. Default slidingWindowType is COUNT_BASED. | COUNT_BASED | String | *camel.resilience4j.slowCall{zwsp}DurationThreshold* | Configures the duration threshold (seconds) above which calls are considered as slow and increase the slow calls percentage. Default value is 60 seconds. | 60 | Integer | *camel.resilience4j.slowCall{zwsp}RateThreshold* | Configures a threshold in percentage. The CircuitBreaker considers a call as slow when the call duration is greater than slowCallDurationThreshold(Duration. When the percentage of slow calls is equal or greater the threshold, the CircuitBreaker transitions to open and starts short-circuiting calls. The threshold must be greater than 0 and not greater than 100. Default value is 100 percentage which means that all recorded calls must be slower than slowCallDurationThreshold. | 100 | Float | *camel.resilience4j.timeout{zwsp}CancelRunningFuture* | Configures whether cancel is called on the running future. Defaults to true. | true | Boolean | *camel.resilience4j.timeout{zwsp}Duration* | Configures the thread execution timeout (millis). Default value is 1000 millis (1 second). | 1000 | Integer | *camel.resilience4j.timeout{zwsp}Enabled* | Whether timeout is enabled or not on the circuit breaker. Default is false. | false | Boolean | *camel.resilience4j.timeout{zwsp}ExecutorServiceRef* | References to a custom thread pool to use when timeout is enabled (uses ForkJoinPool#commonPool() by default) | | String | *camel.resilience4j.wait{zwsp}DurationInOpenState* | Configures the wait duration (in seconds) which specifies how long the CircuitBreaker should stay open, before it switches to half open. Default value is 60 seconds. | 60 | Integer | *camel.resilience4j.writable{zwsp}StackTraceEnabled* | Enables writable stack traces. When set to false, Exception.getStackTrace returns a zero length array. This may be used to reduce log spam when the circuit breaker is open as the cause of the exceptions is already known (the circuit breaker is short-circuiting calls). | | Boolean | *camel.rest.apiComponent* | Sets the name of the Camel component to use as the REST API (such as swagger or openapi) | | String | *camel.rest.apiContextIdPattern* | Optional CamelContext id pattern to only allow Rest APIs from rest services within CamelContext's which name matches the pattern. The pattern #name# refers to the CamelContext name, to match on the current CamelContext only. For any other value, the pattern uses the rules from org.apache.camel.support.EndpointHelper#matchPattern(String,String) | | String | *camel.rest.apiContextListing* | Sets whether listing of all available CamelContext's with REST services in the JVM is enabled. If enabled it allows to discover these contexts, if false then only the current CamelContext is in use. | | boolean | *camel.rest.apiContextPath* | Sets a leading API context-path the REST API services will be using. This can be used when using components such as camel-servlet where the deployed web application is deployed using a context-path. | | String | *camel.rest.apiContextRouteId* | Sets the route id to use for the route that services the REST API. The route will by default use an auto assigned route id. | | String | *camel.rest.apiHost* | To use an specific hostname for the API documentation (eg swagger) This can be used to override the generated host with this configured hostname | | String | *camel.rest.apiProperties* | Sets additional options on api level | | Map | *camel.rest.apiVendorExtension* | Whether vendor extension is enabled in the Rest APIs. If enabled then Camel will include additional information as vendor extension (eg keys starting with x-) such as route ids, class names etc. Not all 3rd party API gateways and tools supports vendor-extensions when importing your API docs. | | boolean | *camel.rest.bindingMode* | Sets the binding mode to be used by the REST consumer | RestBindingMode.off | RestBindingMode | *camel.rest.clientRequest{zwsp}Validation* | Whether to enable validation of the client request to check whether the Content-Type and Accept headers from the client is supported by the Rest-DSL configuration of its consumes/produces settings. This can be turned on, to enable this check. In case of validation error, then HTTP Status codes 415 or 406 is returned. The default value is false. | | boolean | *camel.rest.component* | Sets the name of the Camel component to use as the REST consumer | | String | *camel.rest.componentProperties* | Sets additional options on component level | | Map | *camel.rest.consumerProperties* | Sets additional options on consumer level | | Map | *camel.rest.contextPath* | Sets a leading context-path the REST services will be using. This can be used when using components such as camel-servlet where the deployed web application is deployed using a context-path. Or for components such as camel-jetty or camel-netty-http that includes a HTTP server. | | String | *camel.rest.corsHeaders* | Sets the CORS headers to use if CORS has been enabled. | | Map | *camel.rest.dataFormat{zwsp}Properties* | Sets additional options on data format level | | Map | *camel.rest.enableCORS* | To specify whether to enable CORS which means Camel will automatic include CORS in the HTTP headers in the response. This option is default false | | boolean | *camel.rest.endpointProperties* | Sets additional options on endpoint level | | Map | *camel.rest.host* | Sets the hostname to use by the REST consumer | | String | *camel.rest.hostNameResolver* | Sets the resolver to use for resolving hostname | RestHostNameResolver.allLocalIp | RestHostNameResolver | *camel.rest.jsonDataFormat* | Sets a custom json data format to be used Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. | | String | *camel.rest.port* | Sets the port to use by the REST consumer | | int | *camel.rest.producerApiDoc* | Sets the location of the api document (swagger api) the REST producer will use to validate the REST uri and query parameters are valid accordingly to the api document. This requires adding camel-swagger-java to the classpath, and any miss configuration will let Camel fail on startup and report the error(s). The location of the api document is loaded from classpath by default, but you can use file: or http: to refer to resources to load from file or http url. | | String | *camel.rest.producerComponent* | Sets the name of the Camel component to use as the REST producer | | String | *camel.rest.scheme* | Sets the scheme to use by the REST consumer | | String | *camel.rest.skipBindingOnError{zwsp}Code* | Whether to skip binding output if there is a custom HTTP error code, and instead use the response body as-is. This option is default true. | true | boolean | *camel.rest.useXForwardHeaders* | WWhether to use X-Forward headers to set host etc. for Swagger. This option is default true. | true | boolean | *camel.rest.xmlDataFormat* | Sets a custom xml data format to be used. Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. | | String | *camel.threadpool.allowCore{zwsp}ThreadTimeOut* | Sets default whether to allow core threads to timeout | | Boolean | *camel.threadpool.config* | Adds a configuration for a specific thread pool profile (inherits default values) | | Map | *camel.threadpool.keepAliveTime* | Sets the default keep alive time for inactive threads | | Long | *camel.threadpool.maxPoolSize* | Sets the default maximum pool size | | Integer | *camel.threadpool.maxQueueSize* | Sets the default maximum number of tasks in the work queue. Use -1 or an unbounded queue | | Integer | *camel.threadpool.poolSize* | Sets the default core pool size (threads to keep minimum in pool) | | Integer | *camel.threadpool.rejected{zwsp}Policy* | Sets the default handler for tasks which cannot be executed by the thread pool. | | ThreadPoolRejectedPolicy | *camel.threadpool.timeUnit* | Sets the default time unit used for keep alive time | | TimeUnit |=== // main options: END == Specifying custom beans Custom beans can be configured in `camel-main` via properties (such as in the `application.properties` file). For example to create a `DataSource` for a Postgress database, you can create a new bean instance via `#class:` with the class name (fully qualified). Properties on the data source can then additional configured such as the server and database name, etc. [source,properties] ---- camel.beans.myDS = #class:org.postgresql.jdbc3.Jdbc3PoolingDataSource camel.beans.myDS.dataSourceName = myDS camel.beans.myDS.serverName = mypostrgress camel.beans.myDS.databaseName = test camel.beans.myDS.user = testuser camel.beans.myDS.password = testpassword camel.beans.myDS.maxConnections = 10 ---- The bean is registered in the Camel Registry with the name `myDS`. If you use the SQL component then the datasource can be configured on the SQL component: [source,properties] ---- camel.component.sql.dataSource = #myDS ---- To refer to a custom bean you may want to favour using `#bean:` style, as this states the intention more clearly that its referring to a bean, and not just a text value that happens to start with a `#` sign: [source,properties] ---- camel.component.sql.dataSource = #bean:myDS ---- === Creating a custom bean with constructor parameters When creating a bean then parameters to the constructor can be provided. Suppose we have a class `MyFoo` with a constructur: [source,java] ---- public class MyFoo { private String name; private boolean important; private int id; public MyFoo(String name, boolean important, int id) { this.name = name; this.important = important; this.id = id; } } ---- Then we can create a bean instance with name `foo` and provide parameters to the constructor as shown: [source,properties] ---- camel.beans.foo = #class:com.foo.MyBean(""Hello World"", true, 123) ---- === Optional parameters on beans If a parameter on a bean is not mandatory then the parameter can be marked as optional using `?` syntax, as shown: [source,properties] ---- camel.beans.foo = #class:com.foo.MyBean(""Hello World"", true, 123) camel.beans.foo.?company = Acme ---- Then the company parameter is only set if `MyBean` has this option (silent ignore if no option present). Otherwise if a parameter is set and the bean does not have such a parameter, then an exception is thrown by Camel. === Nested parameters on beans You can configure nested parameters separating them via `.` (dot). For example given this `Country` class: [source,java] ---- public class Country { private String iso; private String name; public void setIso(String iso) { this.iso = iso; } public void setName(String name) { this.name = name; } } ---- Which is an option on the `MyBean` class. Then we can then configure its iso and name parameter as shown below: [source,properties] ---- camel.beans.foo = #class:com.foo.MyBean(""Hello World"", true, 123) camel.beans.foo.country.iso = USA camel.beans.foo.country.name = United States of America ---- Camel will automatic create an instance of `Country` if `MyBean` has a getter/setter for this option, and that the `Country` bean has a default no-arg constructor. === Configuring singleton beans by their type In the example above the SQL component was configured with the name of the `DataSource`. There can be situations where you know there is only a single instance of a data source in the Camel registry. In such a situation you can instead refer to the class or interface type via the `#type:` prefix as shown below: [source,properties] ---- camel.component.sql.dataSource = #type:javax.sql.DataSource ---- If there is no bean in the registry with the type `javax.sql.DataSource` then the option isn't configured. === Autowiring beans The example above can be taken one step further by letting `camel-main` try to autowire the beans. [source,properties] ---- camel.component.sql.dataSource = #autowired ---- In this situation then `#autowrired` will make Camel detect the type of the `dataSource` option on the `SQL` component. As the type is a `javax.sql.DataSource` instance, then Camel will lookup in the registry if there is a single instance of the same type. If there is no such bean then the option isn't configured. == Defining a Map bean You can specify `java.util.Map` beans in `camel-main` via properties (such as in the `application.properties` file). Maps have a special syntax with brackets as shown below: [source,properties] ---- camel.beans.mymap[table] = 12 camel.beans.mymap[food] = Big Burger camel.beans.mymap[cheese] = yes camel.beans.mymap[quantity] = 1 ---- The Map is registered in the Camel Registry with the name `mymap`. == Defining a List bean This is similar to Map bean where the key is the index, eg 0, 1, 2, etc: [source,properties] ---- camel.beans.myprojects[0] = Camel camel.beans.myprojects[1] = Kafka camel.beans.myprojects[2] = Quarkus ---- The List is registered in the Camel Registry with the name `myprojects`. == Examples You can find a set of examples using `camel-main` in https://github.com/apache/camel-examples[Camel Examples] which demonstrate running Camel in standalone with `camel-main`. ",12461,False,2175.7604868358217,median "[[smpp-component]] = SMPP Component :page-source: components/camel-smpp/src/main/docs/smpp-component.adoc *Since Camel 2.2* // HEADER START *Both producer and consumer is supported* // HEADER END This component provides access to an SMSC (Short Message Service Center) over the http://smsforum.net/SMPP_v3_4_Issue1_2.zip[SMPP] protocol to send and receive SMS. The http://jsmpp.org[JSMPP] library is used for the protocol implementation. The Camel component currently operates as an http://en.wikipedia.org/wiki/ESME[ESME] (External Short Messaging Entity) and not as an SMSC itself. You are also able to execute ReplaceSm, QuerySm, SubmitMulti, CancelSm and DataSm. Maven users will need to add the following dependency to their `pom.xml` for this component: [source,xml] ------------------------------------------------------------ org.apache.camel camel-smpp x.x.x ------------------------------------------------------------ == SMS limitations SMS is neither reliable or secure. Users who require reliable and secure delivery may want to consider using the XMPP or SIP components instead, combined with a smartphone app supporting the chosen protocol. * Reliability: although the SMPP standard offers a range of feedback mechanisms to indicate errors, non-delivery and confirmation of delivery it is not uncommon for mobile networks to hide or simulate these responses. For example, some networks automatically send a delivery confirmation for every message even if the destination number is invalid or not switched on. Some networks silently drop messages if they think they are spam. Spam detection rules in the network may be very crude, sometimes more than 100 messages per day from a single sender may be considered spam. * Security: there is basic encryption for the last hop from the radio tower down to the recipient handset. SMS messages are not encrypted or authenticated in any other part of the network. Some operators allow staff in retail outlets or call centres to browse through the SMS message histories of their customers. Message sender identity can be easily forged. Regulators and even the mobile telephone industry itself has cautioned against the use of SMS in two-factor authentication schemes and other purposes where security is important. While the Camel component makes it as easy as possible to send messages to the SMS network, it can not offer an easy solution to these problems. == Data coding, alphabet and international character sets Data coding and alphabet can be specified on a per-message basis. Default values can be specified for the endpoint. It is important to understand the relationship between these options and the way the component acts when more than one value is set. Data coding is an 8 bit field in the SMPP wire format. Alphabet corresponds to bits 0-3 of the data coding field. For some types of message, where a message class is used (by setting bit 5 of the data coding field), the lower two bits of the data coding field are not interpreted as alphabet and only bits 2 and 3 impact the alphabet. Furthermore, current version of the JSMPP library only seems to support bits 2 and 3, assuming that bits 0 and 1 are used for message class. This is why the Alphabet class in JSMPP doesn't support the value 3 (binary 0011) which indicates ISO-8859-1. Although JSMPP provides a representation of the message class parameter, the Camel component doesn't currently provide a way to set it other than manually setting the corresponding bits in the data coding field. When setting the data coding field in the outgoing message, the Camel component considers the following values and uses the first one it can find: * the data coding specified in a header * the alphabet specified in a header * the data coding specified in the endpoint configuration (URI parameter) Older versions of Camel had bugs in support for international character sets. This feature only worked when a single encoding was used for all messages and was troublesome when users wanted to change it on a per-message basis. Users who require this to work should ensure their version of Camel includes the fix for JIRA Issues Macro: com.atlassian.sal.api.net.ResponseStatusException: Unexpected response received. Status code: 404 . In addition to trying to send the data coding value to the SMSC, the Camel component also tries to analyze the message body, convert it to a Java String (Unicode) and convert that to a byte array in the corresponding alphabet When deciding which alphabet to use in the byte array, the Camel SMPP component does not consider the data coding value (header or configuration), it only considers the specified alphabet (from either the header or endpoint parameter). If some characters in the String can't be represented in the chosen alphabet, they may be replaced by the question mark ( ? ) symbol. Users of the API may want to consider checking if their message body can be converted to ISO-8859-1 before passing it to the component and if not, setting the alphabet header to request UCS-2 encoding. If the alphabet and data coding options are not specified at all then the component may try to detect the required encoding and set the data coding for you. The list of alphabet codes are specified in the SMPP specification v3.4, section 5.2.19. One notable limitation of the SMPP specification is that there is no alphabet code for explicitly requesting use of the GSM 3.38 (7 bit) character set. Choosing the value 0 for the alphabet selects the SMSC _default_ alphabet, this usually means GSM 3.38 but it is not guaranteed. The SMPP gateway Nexmo https://help.nexmo.com/hc/en-us/articles/204015813-How-to-change-the-character-encoding-in-SMPP-[actually allows the default to be mapped to any other character set with a control panel option]. It is suggested that users check with their SMSC operator to confirm exactly which character set is being used as the default. == Message splitting and throttling After transforming a message body from a String to a byte array, the Camel component is also responsible for splitting the message into parts (within the 140 byte SMS size limit) before passing it to JSMPP. This is completed automatically. If the GSM 3.38 alphabet is used, the component will pack up to 160 characters into the 140 byte message body. If an 8 bit character set is used (e.g. ISO-8859-1 for western Europe) then 140 characters will be allowed within the 140 byte message body. If 16 bit UCS-2 encoding is used then just 70 characters fit into each 140 byte message. Some SMSC providers implement throttling rules. Each part of a message that has been split may be counted separately by the provider's throttling mechanism. The Camel Throttler component can be useful for throttling messages in the SMPP route before handing them to the SMSC. == URI format [source,java] -------------------------------------------- smpp://[username@]hostname[:port][?options] smpps://[username@]hostname[:port][?options] -------------------------------------------- If no *username* is provided, then Camel will provide the default value `smppclient`. + If no *port* number is provided, then Camel will provide the default value `2775`. + If the protocol name is ""smpps"", camel-smpp with try to use SSLSocket to init a connection to the server. You can append query options to the URI in the following format, `?option=value&option=value&...` == URI Options // component options: START The SMPP component supports 4 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *configuration* (advanced) | To use the shared SmppConfiguration as configuration. | | SmppConfiguration | *basicPropertyBinding* (advanced) | Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *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 |=== // component options: END // endpoint options: START The SMPP endpoint is configured using URI syntax: ---- smpp:host:port ---- with the following path and query parameters: === Path Parameters (2 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *host* | Hostname for the SMSC server to use. | localhost | String | *port* | Port number for the SMSC server to use. | 2775 | Integer |=== === Query Parameters (40 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *initialReconnectDelay* (common) | Defines the initial delay in milliseconds after the consumer/producer tries to reconnect to the SMSC, after the connection was lost. | 5000 | long | *maxReconnect* (common) | Defines the maximum number of attempts to reconnect to the SMSC, if SMSC returns a negative bind response | 2147483647 | int | *reconnectDelay* (common) | Defines the interval in milliseconds between the reconnect attempts, if the connection to the SMSC was lost and the previous was not succeed. | 5000 | long | *splittingPolicy* (common) | You can specify a policy for handling long messages: ALLOW - the default, long messages are split to 140 bytes per message TRUNCATE - long messages are split and only the first fragment will be sent to the SMSC. Some carriers drop subsequent fragments so this reduces load on the SMPP connection sending parts of a message that will never be delivered. REJECT - if a message would need to be split, it is rejected with an SMPP NegativeResponseException and the reason code signifying the message is too long. | ALLOW | SmppSplittingPolicy | *systemType* (common) | This parameter is used to categorize the type of ESME (External Short Message Entity) that is binding to the SMSC (max. 13 characters). | | String | *addressRange* (consumer) | You can specify the address range for the SmppConsumer as defined in section 5.2.7 of the SMPP 3.4 specification. The SmppConsumer will receive messages only from SMSC's which target an address (MSISDN or IP address) within this range. | | String | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *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 | *destAddr* (producer) | Defines the destination SME address. For mobile terminated messages, this is the directory number of the recipient MS. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. | 1717 | String | *destAddrNpi* (producer) | Defines the type of number (TON) to be used in the SME destination address parameters. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. The following NPI values are defined: 0: Unknown 1: ISDN (E163/E164) 2: Data (X.121) 3: Telex (F.69) 6: Land Mobile (E.212) 8: National 9: Private 10: ERMES 13: Internet (IP) 18: WAP Client Id (to be defined by WAP Forum) | | byte | *destAddrTon* (producer) | Defines the type of number (TON) to be used in the SME destination address parameters. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. The following TON values are defined: 0: Unknown 1: International 2: National 3: Network Specific 4: Subscriber Number 5: Alphanumeric 6: Abbreviated | | byte | *lazySessionCreation* (producer) | Sessions can be lazily created to avoid exceptions, if the SMSC is not available when the Camel producer is started. Camel will check the in message headers 'CamelSmppSystemId' and 'CamelSmppPassword' of the first exchange. If they are present, Camel will use these data to connect to the SMSC. | false | boolean | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *numberingPlanIndicator* (producer) | Defines the numeric plan indicator (NPI) to be used in the SME. The following NPI values are defined: 0: Unknown 1: ISDN (E163/E164) 2: Data (X.121) 3: Telex (F.69) 6: Land Mobile (E.212) 8: National 9: Private 10: ERMES 13: Internet (IP) 18: WAP Client Id (to be defined by WAP Forum) | | byte | *priorityFlag* (producer) | Allows the originating SME to assign a priority level to the short message. Only for SubmitSm and SubmitMulti. Four Priority Levels are supported: 0: Level 0 (lowest) priority 1: Level 1 priority 2: Level 2 priority 3: Level 3 (highest) priority | | byte | *protocolId* (producer) | The protocol id | | byte | *registeredDelivery* (producer) | Is used to request an SMSC delivery receipt and/or SME originated acknowledgements. The following values are defined: 0: No SMSC delivery receipt requested. 1: SMSC delivery receipt requested where final delivery outcome is success or failure. 2: SMSC delivery receipt requested where the final delivery outcome is delivery failure. | | byte | *replaceIfPresentFlag* (producer) | Used to request the SMSC to replace a previously submitted message, that is still pending delivery. The SMSC will replace an existing message provided that the source address, destination address and service type match the same fields in the new message. The following replace if present flag values are defined: 0: Don't replace 1: Replace | | byte | *serviceType* (producer) | The service type parameter can be used to indicate the SMS Application service associated with the message. The following generic service_types are defined: CMT: Cellular Messaging CPT: Cellular Paging VMN: Voice Mail Notification VMA: Voice Mail Alerting WAP: Wireless Application Protocol USSD: Unstructured Supplementary Services Data | | String | *sourceAddr* (producer) | Defines the address of SME (Short Message Entity) which originated this message. | 1616 | String | *sourceAddrNpi* (producer) | Defines the numeric plan indicator (NPI) to be used in the SME originator address parameters. The following NPI values are defined: 0: Unknown 1: ISDN (E163/E164) 2: Data (X.121) 3: Telex (F.69) 6: Land Mobile (E.212) 8: National 9: Private 10: ERMES 13: Internet (IP) 18: WAP Client Id (to be defined by WAP Forum) | | byte | *sourceAddrTon* (producer) | Defines the type of number (TON) to be used in the SME originator address parameters. The following TON values are defined: 0: Unknown 1: International 2: National 3: Network Specific 4: Subscriber Number 5: Alphanumeric 6: Abbreviated | | byte | *typeOfNumber* (producer) | Defines the type of number (TON) to be used in the SME. The following TON values are defined: 0: Unknown 1: International 2: National 3: Network Specific 4: Subscriber Number 5: Alphanumeric 6: Abbreviated | | byte | *basicPropertyBinding* (advanced) | Whether the endpoint should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *enquireLinkTimer* (advanced) | Defines the interval in milliseconds between the confidence checks. The confidence check is used to test the communication path between an ESME and an SMSC. | 5000 | Integer | *sessionStateListener* (advanced) | You can refer to a org.jsmpp.session.SessionStateListener in the Registry to receive callbacks when the session state changed. | | SessionStateListener | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported). | false | boolean | *transactionTimer* (advanced) | Defines the maximum period of inactivity allowed after a transaction, after which an SMPP entity may assume that the session is no longer active. This timer may be active on either communicating SMPP entity (i.e. SMSC or ESME). | 10000 | Integer | *alphabet* (codec) | Defines encoding of data according the SMPP 3.4 specification, section 5.2.19. 0: SMSC Default Alphabet 4: 8 bit Alphabet 8: UCS2 Alphabet | | byte | *dataCoding* (codec) | Defines the data coding according the SMPP 3.4 specification, section 5.2.19. Example data encodings are: 0: SMSC Default Alphabet 3: Latin 1 (ISO-8859-1) 4: Octet unspecified (8-bit binary) 8: UCS2 (ISO/IEC-10646) 13: Extended Kanji JIS(X 0212-1990) | | byte | *encoding* (codec) | Defines the encoding scheme of the short message user data. Only for SubmitSm, ReplaceSm and SubmitMulti. | ISO-8859-1 | String | *httpProxyHost* (proxy) | If you need to tunnel SMPP through a HTTP proxy, set this attribute to the hostname or ip address of your HTTP proxy. | | String | *httpProxyPassword* (proxy) | If your HTTP proxy requires basic authentication, set this attribute to the password required for your HTTP proxy. | | String | *httpProxyPort* (proxy) | If you need to tunnel SMPP through a HTTP proxy, set this attribute to the port of your HTTP proxy. | 3128 | Integer | *httpProxyUsername* (proxy) | If your HTTP proxy requires basic authentication, set this attribute to the username required for your HTTP proxy. | | String | *proxyHeaders* (proxy) | These headers will be passed to the proxy server while establishing the connection. | | Map | *password* (security) | The password for connecting to SMSC server. | | String | *systemId* (security) | The system id (username) for connecting to SMSC server. | smppclient | String | *usingSSL* (security) | Whether using SSL with the smpps protocol | false | boolean |=== // 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.springboot camel-smpp-starter x.x.x ---- The component supports 40 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *camel.component.smpp.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.smpp.bridge-error-handler* | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | Boolean | *camel.component.smpp.configuration.address-range* | You can specify the address range for the SmppConsumer as defined in section 5.2.7 of the SMPP 3.4 specification. The SmppConsumer will receive messages only from SMSC's which target an address (MSISDN or IP address) within this range. | | String | *camel.component.smpp.configuration.alphabet* | Defines encoding of data according the SMPP 3.4 specification, section 5.2.19.
  • 0: SMSC Default Alphabet
  • 4: 8 bit Alphabet
  • 8: UCS2 Alphabet
| | Byte | *camel.component.smpp.configuration.data-coding* | Defines the data coding according the SMPP 3.4 specification, section 5.2.19. Example data encodings are:
  • 0: SMSC Default Alphabet
  • 3: Latin 1 (ISO-8859-1)
  • 4: Octet unspecified (8-bit binary)
  • 8: UCS2 (ISO/IEC-10646)
  • 13: Extended Kanji JIS(X 0212-1990)
| | Byte | *camel.component.smpp.configuration.dest-addr* | Defines the destination SME address. For mobile terminated messages, this is the directory number of the recipient MS. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. | 1717 | String | *camel.component.smpp.configuration.dest-addr-npi* | Defines the type of number (TON) to be used in the SME destination address parameters. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. The following NPI values are defined:
  • 0: Unknown
  • 1: ISDN (E163/E164)
  • 2: Data (X.121)
  • 3: Telex (F.69)
  • 6: Land Mobile (E.212)
  • 8: National
  • 9: Private
  • 10: ERMES
  • 13: Internet (IP)
  • 18: WAP Client Id (to be defined by WAP Forum)
| | Byte | *camel.component.smpp.configuration.dest-addr-ton* | Defines the type of number (TON) to be used in the SME destination address parameters. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. The following TON values are defined:
  • 0: Unknown
  • 1: International
  • 2: National
  • 3: Network Specific
  • 4: Subscriber Number
  • 5: Alphanumeric
  • 6: Abbreviated
| | Byte | *camel.component.smpp.configuration.encoding* | Defines the encoding scheme of the short message user data. Only for SubmitSm, ReplaceSm and SubmitMulti. | ISO-8859-1 | String | *camel.component.smpp.configuration.enquire-link-timer* | Defines the interval in milliseconds between the confidence checks. The confidence check is used to test the communication path between an ESME and an SMSC. | 5000 | Integer | *camel.component.smpp.configuration.host* | Hostname for the SMSC server to use. | localhost | String | *camel.component.smpp.configuration.http-proxy-host* | If you need to tunnel SMPP through a HTTP proxy, set this attribute to the hostname or ip address of your HTTP proxy. | | String | *camel.component.smpp.configuration.http-proxy-password* | If your HTTP proxy requires basic authentication, set this attribute to the password required for your HTTP proxy. | | String | *camel.component.smpp.configuration.http-proxy-port* | If you need to tunnel SMPP through a HTTP proxy, set this attribute to the port of your HTTP proxy. | 3128 | Integer | *camel.component.smpp.configuration.http-proxy-username* | If your HTTP proxy requires basic authentication, set this attribute to the username required for your HTTP proxy. | | String | *camel.component.smpp.configuration.initial-reconnect-delay* | Defines the initial delay in milliseconds after the consumer/producer tries to reconnect to the SMSC, after the connection was lost. | 5000 | Long | *camel.component.smpp.configuration.lazy-session-creation* | Sessions can be lazily created to avoid exceptions, if the SMSC is not available when the Camel producer is started. Camel will check the in message headers 'CamelSmppSystemId' and 'CamelSmppPassword' of the first exchange. If they are present, Camel will use these data to connect to the SMSC. | false | Boolean | *camel.component.smpp.configuration.max-reconnect* | Defines the maximum number of attempts to reconnect to the SMSC, if SMSC returns a negative bind response | 2147483647 | Integer | *camel.component.smpp.configuration.numbering-plan-indicator* | Defines the numeric plan indicator (NPI) to be used in the SME. The following NPI values are defined:
  • 0: Unknown
  • 1: ISDN (E163/E164)
  • 2: Data (X.121)
  • 3: Telex (F.69)
  • 6: Land Mobile (E.212)
  • 8: National
  • 9: Private
  • 10: ERMES
  • 13: Internet (IP)
  • 18: WAP Client Id (to be defined by WAP Forum)
| | Byte | *camel.component.smpp.configuration.password* | Defines the encoding scheme of the short message user data. Only for SubmitSm, ReplaceSm and SubmitMulti. | | String | *camel.component.smpp.configuration.port* | Port number for the SMSC server to use. | 2775 | Integer | *camel.component.smpp.configuration.priority-flag* | Allows the originating SME to assign a priority level to the short message. Only for SubmitSm and SubmitMulti. Four Priority Levels are supported:
  • 0: Level 0 (lowest) priority
  • 1: Level 1 priority
  • 2: Level 2 priority
  • 3: Level 3 (highest) priority
| | Byte | *camel.component.smpp.configuration.protocol-id* | The protocol id | | Byte | *camel.component.smpp.configuration.proxy-headers* | These headers will be passed to the proxy server while establishing the connection. | | Map | *camel.component.smpp.configuration.reconnect-delay* | Defines the interval in milliseconds between the reconnect attempts, if the connection to the SMSC was lost and the previous was not succeed. | 5000 | Long | *camel.component.smpp.configuration.registered-delivery* | Is used to request an SMSC delivery receipt and/or SME originated acknowledgements. The following values are defined:
  • 0: No SMSC delivery receipt requested.
  • 1: SMSC delivery receipt requested where final delivery outcome is success or failure.
  • 2: SMSC delivery receipt requested where the final delivery outcome is delivery failure.
| | Byte | *camel.component.smpp.configuration.replace-if-present-flag* | Used to request the SMSC to replace a previously submitted message, that is still pending delivery. The SMSC will replace an existing message provided that the source address, destination address and service type match the same fields in the new message. The following replace if present flag values are defined:
  • 0: Don't replace
  • 1: Replace
| | Byte | *camel.component.smpp.configuration.service-type* | The service type parameter can be used to indicate the SMS Application service associated with the message. The following generic service_types are defined:
  • CMT: Cellular Messaging
  • CPT: Cellular Paging
  • VMN: Voice Mail Notification
  • VMA: Voice Mail Alerting
  • WAP: Wireless Application Protocol
  • USSD: Unstructured Supplementary Services Data
| | String | *camel.component.smpp.configuration.session-state-listener* | You can refer to a org.jsmpp.session.SessionStateListener in the Registry to receive callbacks when the session state changed. | | SessionStateListener | *camel.component.smpp.configuration.source-addr* | Defines the address of SME (Short Message Entity) which originated this message. | 1616 | String | *camel.component.smpp.configuration.source-addr-npi* | Defines the numeric plan indicator (NPI) to be used in the SME originator address parameters. The following NPI values are defined:
  • 0: Unknown
  • 1: ISDN (E163/E164)
  • 2: Data (X.121)
  • 3: Telex (F.69)
  • 6: Land Mobile (E.212)
  • 8: National
  • 9: Private
  • 10: ERMES
  • 13: Internet (IP)
  • 18: WAP Client Id (to be defined by WAP Forum)
| | Byte | *camel.component.smpp.configuration.source-addr-ton* | Defines the type of number (TON) to be used in the SME originator address parameters. The following TON values are defined:
  • 0: Unknown
  • 1: International
  • 2: National
  • 3: Network Specific
  • 4: Subscriber Number
  • 5: Alphanumeric
  • 6: Abbreviated
| | Byte | *camel.component.smpp.configuration.splitting-policy* | You can specify a policy for handling long messages:
  • ALLOW - the default, long messages are split to 140 bytes per message
  • TRUNCATE - long messages are split and only the first fragment will be sent to the SMSC. Some carriers drop subsequent fragments so this reduces load on the SMPP connection sending parts of a message that will never be delivered.
  • REJECT - if a message would need to be split, it is rejected with an SMPP NegativeResponseException and the reason code signifying the message is too long.
| | SmppSplittingPolicy | *camel.component.smpp.configuration.system-id* | The system id (username) for connecting to SMSC server. | smppclient | String | *camel.component.smpp.configuration.system-type* | This parameter is used to categorize the type of ESME (External Short Message Entity) that is binding to the SMSC (max. 13 characters). | | String | *camel.component.smpp.configuration.transaction-timer* | Defines the maximum period of inactivity allowed after a transaction, after which an SMPP entity may assume that the session is no longer active. This timer may be active on either communicating SMPP entity (i.e. SMSC or ESME). | 10000 | Integer | *camel.component.smpp.configuration.type-of-number* | Defines the type of number (TON) to be used in the SME. The following TON values are defined:
  • 0: Unknown
  • 1: International
  • 2: National
  • 3: Network Specific
  • 4: Subscriber Number
  • 5: Alphanumeric
  • 6: Abbreviated
| | Byte | *camel.component.smpp.configuration.using-s-s-l* | Whether using SSL with the smpps protocol | false | Boolean | *camel.component.smpp.enabled* | Whether to enable auto configuration of the smpp component. This is enabled by default. | | Boolean | *camel.component.smpp.lazy-start-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 |=== // spring-boot-auto-configure options: END You can have as many of these options as you like. [source,java] ------------------------------------------------------------------------------------------------------------------ smpp://smppclient@localhost:2775?password=password&enquireLinkTimer=3000&transactionTimer=5000&systemType=consumer ------------------------------------------------------------------------------------------------------------------ == Producer Message Headers The following message headers can be used to affect the behavior of the SMPP producer [width=""100%"",cols=""10%,10%,80%"",options=""header"",] |======================================================================= |Header |Type |Description |`CamelSmppDestAddr` |`List`/`String` |*only for SubmitSm, SubmitMulti, CancelSm and DataSm* Defines the destination SME address(es). For mobile terminated messages, this is the directory number of the recipient MS. Is must be a `List` for SubmitMulti and a `String` otherwise. |`CamelSmppDestAddrTon` |`Byte` |*only for SubmitSm, SubmitMulti, CancelSm and DataSm* Defines the type of number (TON) to be used in the SME destination address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppDestAddrNpi` |`Byte` |*only for SubmitSm, SubmitMulti, CancelSm and DataSm* Defines the numeric plan indicator (NPI) to be used in the SME destination address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppSourceAddr` |`String` |Defines the address of SME (Short Message Entity) which originated this message. |`CamelSmppSourceAddrTon` |`Byte` |Defines the type of number (TON) to be used in the SME originator address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppSourceAddrNpi` |`Byte` |Defines the numeric plan indicator (NPI) to be used in the SME originator address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppServiceType` |`String` |The service type parameter can be used to indicate the SMS Application service associated with the message. Use the URI option `serviceType` settings above. |`CamelSmppRegisteredDelivery` |`Byte` |*only for SubmitSm, ReplaceSm, SubmitMulti and DataSm* Is used to request an SMSC delivery receipt and/or SME originated acknowledgements. Use the URI option `registeredDelivery` settings above. |`CamelSmppPriorityFlag` |`Byte` |*only for SubmitSm and SubmitMulti* Allows the originating SME to assign a priority level to the short message. Use the URI option `priorityFlag` settings above. |`CamelSmppScheduleDeliveryTime` |`Date` |*only for SubmitSm, SubmitMulti and ReplaceSm* This parameter specifies the scheduled time at which the message delivery should be first attempted. It defines either the absolute date and time or relative time from the current SMSC time at which delivery of this message will be attempted by the SMSC. It can be specified in either absolute time format or relative time format. The encoding of a time format is specified in chapter 7.1.1. in the smpp specification v3.4. |`CamelSmppValidityPeriod` |`String`/`Date` |*only for SubmitSm, SubmitMulti and ReplaceSm* The validity period parameter indicates the SMSC expiration time, after which the message should be discarded if not delivered to the destination. If it's provided as `Date`, it's interpreted as absolute time or relative time format if you provide it as `String` as specified in chapter 7.1.1 in the smpp specification v3.4. |`CamelSmppReplaceIfPresentFlag` |`Byte` |*only for SubmitSm and SubmitMulti* The replace if present flag parameter is used to request the SMSC to replace a previously submitted message, that is still pending delivery. The SMSC will replace an existing message provided that the source address, destination address and service type match the same fields in the new message. The following values are defined: `0`, Don't replace and `1`, Replace |`CamelSmppAlphabet` / `CamelSmppDataCoding` |`Byte` |*For SubmitSm, SubmitMulti and ReplaceSm* The data coding according to the SMPP 3.4 specification, section 5.2.19. Use the URI option `alphabet` settings above. |`CamelSmppOptionalParameter` |`Map` |*only for SubmitSm, SubmitMulti and DataSm* The optional parameter which are send to the SMSC. The value is converted in the following way: `String` -> `org.jsmpp.bean.OptionalParameter.COctetString`, `byte[]` -> `org.jsmpp.bean.OptionalParameter.OctetString`, `Byte` -> `org.jsmpp.bean.OptionalParameter.Byte`, `Integer` -> `org.jsmpp.bean.OptionalParameter.Int`, `Short` -> `org.jsmpp.bean.OptionalParameter.Short`, `null` -> `org.jsmpp.bean.OptionalParameter.Null` |CamelSmppEncoding |String |*only for SubmitSm, SubmitMulti and DataSm*. Specifies the encoding (character set name) of the bytes in the message body. If the message body is a string then this is not relevant because Java Strings are always Unicode. If the body is a byte array then this header can be used to indicate that it is ISO-8859-1 or some other value. Default value is specified by the endpoint configuration parameter _encoding_ |CamelSmppSplittingPolicy |String |*only for SubmitSm, SubmitMulti and DataSm*. Specifies the policy for message splitting for this exchange. Possible values are described in the endpoint configuration parameter _splittingPolicy_ |======================================================================= The following message headers are used by the SMPP producer to set the response from the SMSC in the message header [width=""100%"",cols=""10%,10%,80%"",options=""header"",] |======================================================================= |Header |Type |Description |`CamelSmppId` |`List`/`String` |The id to identify the submitted short message(s) for later use. In case of a ReplaceSm, QuerySm, CancelSm and DataSm this header vaule is a `String`. In case of a SubmitSm or SubmitMultiSm this header vaule is a `List`. |`CamelSmppSentMessageCount` |`Integer` |*only for SubmitSm and SubmitMultiSm* The total number of messages which has been sent. |`CamelSmppError` |`Map>>` |*only for SubmitMultiSm* The errors which occurred by sending the short message(s) the form `Map>>` (messageID : (destAddr : address, error : errorCode)). |`CamelSmppOptionalParameter` |`Map` |*only for DataSm* The optional parameter which are returned from the SMSC by sending the message. The key is the `Short` code for the optional parameter. The value is converted in the following way: `org.jsmpp.bean.OptionalParameter.COctetString` -> `String`, `org.jsmpp.bean.OptionalParameter.OctetString` -> `byte[]`, `org.jsmpp.bean.OptionalParameter.Byte` -> `Byte`, `org.jsmpp.bean.OptionalParameter.Int` -> `Integer`, `org.jsmpp.bean.OptionalParameter.Short` -> `Short`, `org.jsmpp.bean.OptionalParameter.Null` -> `null` |======================================================================= == Consumer Message Headers The following message headers are used by the SMPP consumer to set the request data from the SMSC in the message header [width=""100%"",cols=""10%,10%,80%"",options=""header"",] |======================================================================= |Header |Type |Description |`CamelSmppSequenceNumber` |`Integer` |*only for AlertNotification, DeliverSm and DataSm* A sequence number allows a response PDU to be correlated with a request PDU. The associated SMPP response PDU must preserve this field. |`CamelSmppCommandId` |`Integer` |*only for AlertNotification, DeliverSm and DataSm* The command id field identifies the particular SMPP PDU. For the complete list of defined values see chapter 5.1.2.1 in the smpp specification v3.4. |`CamelSmppSourceAddr` |`String` |*only for AlertNotification, DeliverSm and DataSm* Defines the address of SME (Short Message Entity) which originated this message. |`CamelSmppSourceAddrNpi` |`Byte` |*only for AlertNotification and DataSm* Defines the numeric plan indicator (NPI) to be used in the SME originator address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppSourceAddrTon` |`Byte` |*only for AlertNotification and DataSm* Defines the type of number (TON) to be used in the SME originator address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppEsmeAddr` |`String` |*only for AlertNotification* Defines the destination ESME address. For mobile terminated messages, this is the directory number of the recipient MS. |`CamelSmppEsmeAddrNpi` |`Byte` |*only for AlertNotification* Defines the numeric plan indicator (NPI) to be used in the ESME originator address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppEsmeAddrTon` |`Byte` |*only for AlertNotification* Defines the type of number (TON) to be used in the ESME originator address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppId` |`String` |*only for smsc DeliveryReceipt and DataSm* The message ID allocated to the message by the SMSC when originally submitted. |`CamelSmppDelivered` |`Integer` |*only for smsc DeliveryReceipt* Number of short messages delivered. This is only relevant where the original message was submitted to a distribution list.The value is padded with leading zeros if necessary. |`CamelSmppDoneDate` |`Date` |*only for smsc DeliveryReceipt* The time and date at which the short message reached it's final state. The format is as follows: YYMMDDhhmm. |`CamelSmppStatus` |`DeliveryReceiptState` |*only for smsc DeliveryReceipt:* The final status of the message. The following values are defined: `DELIVRD`: Message is delivered to destination, `EXPIRED`: Message validity period has expired, `DELETED`: Message has been deleted, `UNDELIV`: Message is undeliverable, `ACCEPTD`: Message is in accepted state (i.e. has been manually read on behalf of the subscriber by customer service), `UNKNOWN`: Message is in invalid state, `REJECTD`: Message is in a rejected state |`CamelSmppCommandStatus` |`Integer` |*only for DataSm* The Command status of the message. |`CamelSmppError` |`String` |*only for smsc DeliveryReceipt* Where appropriate this may hold a Network specific error code or an SMSC error code for the attempted delivery of the message. These errors are Network or SMSC specific and are not included here. |`CamelSmppSubmitDate` |`Date` |*only for smsc DeliveryReceipt* The time and date at which the short message was submitted. In the case of a message which has been replaced, this is the date that the original message was replaced. The format is as follows: YYMMDDhhmm. |`CamelSmppSubmitted` |`Integer` |*only for smsc DeliveryReceipt* Number of short messages originally submitted. This is only relevant when the original message was submitted to a distribution list.The value is padded with leading zeros if necessary. |`CamelSmppDestAddr` |`String` |*only for DeliverSm and DataSm:* Defines the destination SME address. For mobile terminated messages, this is the directory number of the recipient MS. |`CamelSmppScheduleDeliveryTime` |`String` |*only for DeliverSm:* This parameter specifies the scheduled time at which the message delivery should be first attempted. It defines either the absolute date and time or relative time from the current SMSC time at which delivery of this message will be attempted by the SMSC. It can be specified in either absolute time format or relative time format. The encoding of a time format is specified in Section 7.1.1. in the smpp specification v3.4. |`CamelSmppValidityPeriod` |`String` |*only for DeliverSm* The validity period parameter indicates the SMSC expiration time, after which the message should be discarded if not delivered to the destination. It can be defined in absolute time format or relative time format. The encoding of absolute and relative time format is specified in Section 7.1.1 in the smpp specification v3.4. |`CamelSmppServiceType` |`String` |*only for DeliverSm and DataSm* The service type parameter indicates the SMS Application service associated with the message. |`CamelSmppRegisteredDelivery` |`Byte` |*only for DataSm* Is used to request an delivery receipt and/or SME originated acknowledgements. Same values as in Producer header list above. |`CamelSmppDestAddrNpi` |`Byte` |*only for DataSm* Defines the numeric plan indicator (NPI) in the destination address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppDestAddrTon` |`Byte` |*only for DataSm* Defines the type of number (TON) in the destination address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppMessageType` |`String` |Identifies the type of an incoming message: `AlertNotification`: an SMSC alert notification, `DataSm`: an SMSC data short message, `DeliveryReceipt`: an SMSC delivery receipt, `DeliverSm`: an SMSC deliver short message |`CamelSmppOptionalParameter` |`Map` |*only for DeliverSm* The optional parameters send back by the SMSC. The key is the `Short` code for the optional parameter. The value is converted in the following way: `org.jsmpp.bean.OptionalParameter.COctetString` -> `String`, `org.jsmpp.bean.OptionalParameter.OctetString` -> `byte[]`, `org.jsmpp.bean.OptionalParameter.Byte` -> `Byte`, `org.jsmpp.bean.OptionalParameter.Int` -> `Integer`, `org.jsmpp.bean.OptionalParameter.Short` -> `Short`, `org.jsmpp.bean.OptionalParameter.Null` -> `null` |======================================================================= TIP: *JSMPP library* See the documentation of the http://jsmpp.org[JSMPP Library] for more details about the underlying library. == Exception handling This component supports the general Camel exception handling capabilities When an error occurs sending a message with SubmitSm (the default action), the org.apache.camel.component.smpp.SmppException is thrown with a nested exception, org.jsmpp.extra.NegativeResponseException. Call NegativeResponseException.getCommandStatus() to obtain the exact SMPP negative response code, the values are explained in the SMPP specification 3.4, section 5.1.3. + When the SMPP consumer receives a `DeliverSm` or `DataSm` short message and the processing of these messages fails, you can also throw a `ProcessRequestException` instead of handle the failure. In this case, this exception is forwarded to the underlying http://jsmpp.org[JSMPP library] which will return the included error code to the SMSC. This feature is useful to e.g. instruct the SMSC to resend the short message at a later time. This could be done with the following lines of code: [source,java] -------------------------------------------------------------------------------------------------------------------------- from(""smpp://smppclient@localhost:2775?password=password&enquireLinkTimer=3000&transactionTimer=5000&systemType=consumer"") .doTry() .to(""bean:dao?method=updateSmsState"") .doCatch(Exception.class) .throwException(new ProcessRequestException(""update of sms state failed"", 100)) .end(); -------------------------------------------------------------------------------------------------------------------------- Please refer to the http://smsforum.net/SMPP_v3_4_Issue1_2.zip[SMPP specification] for the complete list of error codes and their meanings. == Samples A route which sends an SMS using the Java DSL: [source,java] ------------------------------------------------------------------------------------------ from(""direct:start"") .to(""smpp://smppclient@localhost:2775? password=password&enquireLinkTimer=3000&transactionTimer=5000&systemType=producer""); ------------------------------------------------------------------------------------------ A route which sends an SMS using the Spring XML DSL: [source,xml] ----------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------- A route which receives an SMS using the Java DSL: [source,java] -------------------------------------------------------------------------------------------------------------------------- from(""smpp://smppclient@localhost:2775?password=password&enquireLinkTimer=3000&transactionTimer=5000&systemType=consumer"") .to(""bean:foo""); -------------------------------------------------------------------------------------------------------------------------- A route which receives an SMS using the Spring XML DSL: [source,xml] ---------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------- TIP: *SMSC simulator* If you need an SMSC simulator for your test, you can use the simulator provided by http://opensmpp.logica.com/CommonPart/Download/download2.html#simulator[Logica]. == Debug logging This component has log level *DEBUG*, which can be helpful in debugging problems. If you use log4j, you can add the following line to your configuration: [source,java] -------------------------------------------------- log4j.logger.org.apache.camel.component.smpp=DEBUG -------------------------------------------------- ",12140,False,2377.5347618694054,median "CLASS zcl_rest_utility_class DEFINITION PUBLIC FINAL CREATE PUBLIC . PUBLIC SECTION. METHODS constructor . CLASS-METHODS download_payload_file IMPORTING !xstring TYPE xstring !message_id TYPE zmid RAISING zcx_http_client_failed . METHODS retry IMPORTING !message_id TYPE zmid !method TYPE zinterface_method !from_scheduler TYPE char1 OPTIONAL RAISING zcx_interace_config_missing zcx_http_client_failed . CLASS-METHODS get_http_description IMPORTING !code TYPE int4 RETURNING VALUE(description) TYPE string . CLASS-METHODS show_payload IMPORTING !message_id TYPE zmid !response TYPE c OPTIONAL RAISING zcx_http_client_failed . CLASS-METHODS get_config_data IMPORTING !interface_id TYPE zinterface_id !method TYPE zinterface_method RETURNING VALUE(config_data) TYPE zrest_srtuct_config . CLASS-METHODS get_static_headers IMPORTING !interface_id TYPE zinterface_id RETURNING VALUE(static_headers) TYPE tihttpnvp . CLASS-METHODS show_submitted_headers IMPORTING !message_id TYPE zmid RAISING zcx_http_client_failed . CLASS-METHODS unprocessed_data RETURNING VALUE(result) TYPE zrt_payload . CLASS-METHODS reset_all_data RAISING zcx_http_client_failed . CLASS-METHODS check_obfuscation_needed IMPORTING !inetrface_in TYPE zinterface_id RETURNING VALUE(result) TYPE abap_bool . METHODS retry_limit_exceeded EXPORTING !et_retry_report TYPE ztt_rest_retry_limi . METHODS send_email IMPORTING !iv_recepient TYPE ad_smtpadr !iv_subject TYPE so_obj_des !it_body TYPE soli_tab EXPORTING !ew_return TYPE bapiret2 !ev_result TYPE os_boolean . CLASS-METHODS check_authority RAISING zcx_http_client_failed . CLASS-METHODS get_global_params RETURNING VALUE(global_params) TYPE zrest_global . CLASS-METHODS retry_log IMPORTING !message_id TYPE zmid !response TYPE c OPTIONAL RAISING zcx_http_client_failed . CLASS-METHODS write_application_log IMPORTING !iv_object TYPE balobj_d !iv_subobject TYPE balsubobj !iv_extnumber TYPE balnrext !it_message TYPE zrt_applog_message . PROTECTED SECTION. PRIVATE SECTION. DATA rest_handler TYPE REF TO zcl_rest_framework . DATA response TYPE REF TO if_rest_entity . DATA request TYPE REF TO if_rest_entity . CLASS-DATA payload TYPE zrt_payload . CLASS-DATA monitor TYPE zrest_monitor . CLASS-DATA interface_name TYPE zinterface_id . CLASS-DATA it_zobfuscate TYPE ztobfuscate . CLASS-METHODS get_db_data IMPORTING !message_id TYPE zmid . CLASS-METHODS check_messageid IMPORTING !message_id TYPE zmid . CLASS-METHODS obfuscate IMPORTING !input TYPE xstring RETURNING VALUE(result) TYPE xstring . ENDCLASS. CLASS zcl_rest_utility_class IMPLEMENTATION. METHOD check_authority. DATA:lv_textid TYPE scx_t100key. AUTHORITY-CHECK OBJECT 'ZREST_AUTH' ID 'ZBOOLEAN' FIELD 'X'. IF sy-subrc NE 0. lv_textid-msgid = 'Z_FI_MDG'. lv_textid-msgno = '057'. RAISE EXCEPTION TYPE zcx_http_client_failed EXPORTING textid = lv_textid. ENDIF. ENDMETHOD. METHOD check_messageid. IF message_id IS INITIAL . EXIT. ENDIF. ENDMETHOD. METHOD check_obfuscation_needed. SELECT * FROM zobfuscate INTO TABLE it_zobfuscate WHERE inetrface EQ inetrface_in. IF sy-subrc EQ 0. result = abap_true. ELSE. result = abap_false. ENDIF. ENDMETHOD. METHOD constructor. ENDMETHOD. METHOD download_payload_file. TYPES : BEGIN OF ty_string, line TYPE string, END OF ty_string. DATA : wa_payload TYPE zrest_mo_payload, wa_string TYPE ty_string, it_string TYPE STANDARD TABLE OF ty_string, output TYPE xstring. * Check if user has the authority to call. * Begin of changes for VSTF# 2163894 | DGDK903413 * TRY. * check_authority( ). * CATCH zcx_http_client_failed INTO DATA(lv_textid). * DATA(lv_text2) = lv_textid->if_t100_message~t100key. * RAISE EXCEPTION TYPE zcx_http_client_failed EXPORTING textid = lv_text2. * ENDTRY. * End of changes for VSTF 2163894 | DGDK903413 SELECT SINGLE * FROM zrest_mo_payload INTO wa_payload WHERE messageid EQ message_id. AUTHORITY-CHECK OBJECT 'ZREST_AUTH' ID 'ZBOOLEAN' FIELD 'X'. IF sy-subrc NE 0. IF check_obfuscation_needed( inetrface_in = wa_payload-interface_id ) EQ abap_true. output = obfuscate( input = wa_payload-payload ). wa_payload-payload = output. ENDIF. ENDIF. CALL FUNCTION 'ECATT_CONV_XSTRING_TO_STRING' EXPORTING im_xstring = wa_payload-payload im_encoding = 'UTF-8' IMPORTING ex_string = wa_string-line. APPEND wa_string TO it_string. CLEAR wa_string. DATA gv_filename TYPE string. DELETE it_string WHERE line IS INITIAL. IF it_string IS INITIAL. MESSAGE 'Payload not found' TYPE 'I'. RETURN. ENDIF. CALL FUNCTION 'GUI_FILE_SAVE_DIALOG' IMPORTING fullpath = gv_filename. CALL FUNCTION 'GUI_DOWNLOAD' EXPORTING filename = gv_filename filetype = 'ASC' TABLES data_tab = it_string EXCEPTIONS file_write_error = 1 no_batch = 2 gui_refuse_filetransfer = 3 invalid_type = 4 no_authority = 5 unknown_error = 6 header_not_allowed = 7 separator_not_allowed = 8 filesize_not_allowed = 9 header_too_long = 10 dp_error_create = 11 dp_error_send = 12 dp_error_write = 13 unknown_dp_error = 14 access_denied = 15 dp_out_of_memory = 16 disk_full = 17 dp_timeout = 18 file_not_found = 19 dataprovider_exception = 20 control_flush_error = 21 OTHERS = 22. IF sy-subrc <> 0. * Implement suitable error handling here ENDIF. ENDMETHOD. METHOD get_config_data. SELECT SINGLE * FROM zrest_config INTO CORRESPONDING FIELDS OF config_data WHERE interface_id EQ interface_id. "" and method eq method. SELECT SINGLE method max_retry INTO (config_data-method, config_data-max_retry) FROM zrest_conf_misc WHERE interface_id EQ interface_id AND method EQ method. ENDMETHOD. METHOD get_db_data. z_restcall_from_db=>get_calldata_fromdb( EXPORTING message_id = message_id IMPORTING payload = payload monitor = monitor ). ENDMETHOD. METHOD get_global_params. DATA it_global TYPE TABLE OF zrest_global. SELECT * FROM zrest_global INTO TABLE it_global. READ TABLE it_global INTO global_params INDEX 1. ENDMETHOD. METHOD get_http_description. CASE code. WHEN '100'. description = 'Continue'. WHEN '101'. description = 'Switching Protocols'. WHEN '200'. description = 'OK'. WHEN '201'. description = 'Created'. WHEN '202'. description = 'Accepted'. WHEN '203'. description = 'Non-Authoritative Information'. WHEN '204'. description = 'No Content'. WHEN '205'. description = 'Reset Content'. WHEN '206'. description = 'Partial Content'. WHEN '300'. description = 'Multiple Choices'. WHEN '301'. description = 'Moved Permanently'. WHEN '302'. description = 'Found'. WHEN '303'. description = 'See Other'. WHEN '304'. description = 'Not Modified'. WHEN '305'. description = 'Use Proxy'. WHEN '307'. description = 'Temporary Redirect'. WHEN'400'.description = ' Bad Request'. WHEN'401'.description = ' Unauthorized'. WHEN'402'.description = ' Payment Required'. WHEN'403'.description = ' Forbidden'. WHEN'404'.description = ' Not Found'. WHEN'405'.description = ' Method Not Allowed'. WHEN'406'.description = ' Not Acceptable'. WHEN'407'.description = ' Proxy Authentication Required'. WHEN'408'.description = ' Request Timeout'. WHEN'409'.description = ' Conflict'. WHEN'410'.description = ' Gone'. WHEN'411'.description = ' Length Required'. WHEN'412'.description = ' Precondition Failed'. WHEN'413'.description = ' Request Entity Too Large'. WHEN'414'.description = ' Request-URI Too Long'. WHEN'415'.description = ' Unsupported Media Type'. WHEN'416'.description = ' Requested Range Not Satisfiable'. WHEN'417'.description = ' Expectation Failed'. WHEN'500'.description = ' Internal Server Error'. WHEN'501'.description = ' Not Implemented'. WHEN'502'.description = ' Bad Gateway'. WHEN'503'.description = ' Service Unavailable'. WHEN'504'.description = ' Gateway Timeout'. WHEN'505'.description = ' HTTP Version Not Supported'. WHEN'505'. WHEN OTHERS. description = ''. ENDCASE. ENDMETHOD. METHOD get_static_headers. DATA: wa_ihttpnvp TYPE ihttpnvp, lt_headers TYPE TABLE OF zrest_conf_head, wa_headers TYPE zrest_conf_head. SELECT * FROM zrest_conf_head INTO TABLE lt_headers WHERE interface_id EQ interface_id. IF sy-subrc EQ 0. LOOP AT lt_headers INTO wa_headers. wa_ihttpnvp-name = wa_headers-name. wa_ihttpnvp-value = wa_headers-value. APPEND wa_ihttpnvp TO static_headers. CLEAR wa_ihttpnvp. ENDLOOP. ENDIF. ENDMETHOD. METHOD obfuscate. ************************************************************************************ FIELD-SYMBOLS : TYPE any, TYPE any. DATA : converted TYPE REF TO cl_abap_conv_in_ce, regex TYPE REF TO cl_abap_regex, matcher TYPE REF TO cl_abap_matcher, obfuscate_word TYPE REF TO data, lchar_string TYPE REF TO data, regex_result_tab TYPE match_result_tab, regex_result TYPE match_result, st_obfuscate LIKE LINE OF it_zobfuscate, lv_string TYPE string, length_of_word TYPE i. ************************************************************************************ * Convert to string * ************************************************************************************ * Check if the obfuscation is needed and input is not initial CHECK : it_zobfuscate IS NOT INITIAL , input IS NOT INITIAL. * if yes , convert the xstring to string for the processing TRY. converted = cl_abap_conv_in_ce=>create( input = input ). CATCH cx_parameter_invalid_range . CATCH cx_sy_codepage_converter_init . ENDTRY. TRY. converted->read( IMPORTING data = lv_string ). CATCH cx_sy_conversion_codepage . CATCH cx_sy_codepage_converter_init . CATCH cx_parameter_invalid_type . CATCH cx_parameter_invalid_range . ENDTRY. ************************************************************************************ * Loop at the fields which needed to be obfuscated * ************************************************************************************ LOOP AT it_zobfuscate INTO st_obfuscate. CREATE OBJECT : regex EXPORTING pattern = st_obfuscate-fieldtag ignore_case = abap_true, matcher EXPORTING regex = regex text = lv_string. CREATE DATA obfuscate_word TYPE c LENGTH st_obfuscate-length. length_of_word = strlen( lv_string ). CREATE DATA lchar_string TYPE c LENGTH length_of_word. regex_result_tab = matcher->find_all( ). length_of_word = strlen( st_obfuscate-fieldtag ). ASSIGN obfuscate_word->* TO . ASSIGN lchar_string->* TO . = lv_string. DO st_obfuscate-length TIMES. sy-index = sy-index - 1. +sy-index(1) = '*'. ENDDO. * Repace the words in all string LOOP AT regex_result_tab INTO regex_result. length_of_word = strlen( st_obfuscate-fieldtag ). length_of_word = length_of_word + regex_result-offset. +length_of_word(st_obfuscate-length) = . ENDLOOP. CLEAR : st_obfuscate,length_of_word,regex_result_tab,regex_result. lv_string = . UNASSIGN : , . ENDLOOP. ************************************************************************************ * Make it string * ************************************************************************************ CALL FUNCTION 'SCMS_STRING_TO_XSTRING' EXPORTING text = lv_string IMPORTING buffer = result EXCEPTIONS failed = 1 OTHERS = 2. IF sy-subrc <> 0. * Implement suitable error handling here ENDIF. ENDMETHOD. METHOD reset_all_data. *----------------------------------------------------------------------* * Modification History * *----------------------------------------------------------------------* * Date | USER ID | VSTF | Transport | Remarks * *-----------|----------|--------|------------|-------------------------* * 04|28|2016|V-DEVEER |2163894 | DGDK903413 | Authorization Check *----------------------------------------------------------------------* ************************************************************************************** DATA : it_monitor TYPE STANDARD TABLE OF zrest_monitor, it_payload TYPE STANDARD TABLE OF zrest_mo_payload, it_headers TYPE STANDARD TABLE OF zrest_mon_header, del_date TYPE sy-datum, seconds TYPE i, lv_textid TYPE REF TO zcx_http_client_failed, lv_text2 TYPE scx_t100key. CREATE OBJECT lv_textid. ************************************************************************************** * Go back 30 days in time . All the message before this date would need to * * be cleanesed.By default 30 days... * ************************************************************************************** DATA: wa_global TYPE zrest_global. wa_global = zcl_rest_utility_class=>get_global_params( ). seconds = -1 * wa_global-message_retention * 24 * 60. TRY. cl_abap_tstmp=>td_add( EXPORTING date = sy-datum time = sy-uzeit secs = seconds IMPORTING res_date = del_date ). CATCH cx_parameter_invalid_type . CATCH cx_parameter_invalid_range . ENDTRY. ************************************************************************************** * Begin of changes VSTF # 2163894 | DGDK903413 TRY. check_authority( ). CATCH zcx_http_client_failed INTO lv_textid. lv_text2 = lv_textid->if_t100_message~t100key. RAISE EXCEPTION TYPE zcx_http_client_failed EXPORTING textid = lv_text2. ENDTRY. * End of changes VSTF # 2163894 | DGDK903413 ************************************************************************************** SELECT * FROM zrest_monitor INTO TABLE it_monitor WHERE zcompdate < del_date AND httpstatus BETWEEN 200 AND 300 . IF sy-subrc EQ 0. SELECT * FROM zrest_mo_payload INTO TABLE it_payload FOR ALL ENTRIES IN it_monitor WHERE messageid EQ it_monitor-zmessageid. SELECT * FROM zrest_mon_header INTO TABLE it_headers FOR ALL ENTRIES IN it_monitor WHERE messageid EQ it_monitor-zmessageid. ENDIF. ************************************************************************************** * Delete the data from the table * ************************************************************************************** IF it_monitor IS NOT INITIAL. DELETE : zrest_monitor FROM TABLE it_monitor, zrest_mo_payload FROM TABLE it_payload, zrest_mon_header FROM TABLE it_headers. ENDIF. ENDMETHOD. METHOD retry. *----------------------------------------------------------------------* * Modification History * *----------------------------------------------------------------------* * Date | USER ID | VSTF | Transport | Remarks * *-----------|----------|--------|------------|-------------------------* * 04|28|2016|V-DEVEER |2163894 | DGDK903413 | Authorization Check *----------------------------------------------------------------------* * 05|05|2016|V-DEVEER |2163894 | DGDK903444 | SIT Testing issues *----------------------------------------------------------------------* * 12|08|2016|V-JAVEDA |2163894 | MS2K948543 | Enhance delete function *----------------------------------------------------------------------* * 12|16|2016|V-JAVEDA |2163894 | MS2K948920 | Performance improve *----------------------------------------------------------------------* *12/20/2016| V-JAVEDA |2278065 | MS2K948978 |Clearing prog header * *----------------------------------------------------------------------* DATA : lv_string TYPE string, wa_paylod TYPE zrest_mo_payload, lv_text2 TYPE scx_t100key, lv_textid TYPE REF TO zcx_http_client_failed, lv_rfc_destination TYPE zrest_config-destination, lv_srtfd TYPE zadf_con_indx-srtfd, lw_indx TYPE zadf_con_indx, lt_enveloped_data TYPE TABLE OF ssfbin, lv_cert_string TYPE xstring, lt_recipients TYPE TABLE OF ssfinfo, lw_recipient TYPE ssfinfo, lt_input_data TYPE TABLE OF ssfbin, lv_env_data_len TYPE i, lv_env_len_total TYPE i, lv_subject TYPE string, lw_enveloped_data TYPE ssfbin, lv_len_output TYPE i, lv_len_input TYPE i, lv_decoded_str TYPE string, lv_applic TYPE rfcdisplay-sslapplic, lv_psename TYPE ssfpsename, lv_profilename TYPE localfile, lv_profile TYPE ssfparms-pab, lv_current_timestamp TYPE timestampl, lv_date_adf TYPE datum, lv_time_adf TYPE uzeit, lv_seconds_adf TYPE p, lv_input_seconds_adf TYPE p, lv_expiry_time_adf TYPE string, lv_new_expiry_adf TYPE string, lv_format TYPE i, lv_string_to_sign TYPE string, lv_encoded_base_address TYPE string, lv_body_xstring TYPE xstring, lv_sign TYPE string, lv_final_token TYPE string, lv_decoded TYPE xstring, lo_conv TYPE REF TO cl_abap_conv_out_ce, lv_sas_key TYPE string, lw_zadf_config TYPE zadf_config, lv_zone TYPE sy-zonlo, lv_baseaddress TYPE string, http_method TYPE zinterface_method. CONSTANTS: lc_i TYPE c VALUE 'I', lc_servicebus TYPE zadf_config-interface_type VALUE 'SERVICEBUS', lc_eventhub TYPE zadf_config-interface_type VALUE 'EVENTHUB', lc_auth TYPE ihttpnvp-name VALUE 'Authorization'. CREATE OBJECT lv_textid. *-----------------------check message id ------------------------------* check_messageid( message_id = message_id ). *-----------------------get db data -----------------------------------* get_db_data( message_id = message_id ). * ------------------------get the latest payloadv----------------------* * Sort the retry num , so that latest one is picked for reprocessing SORT payload BY retry_num DESCENDING. * READ TABLE payload INTO DATA(wa_paylod) INDEX 1. v-jobpau CLEAR wa_paylod. ""v-javeda | MS2K948978 READ TABLE payload INTO wa_paylod INDEX 1. * ---------------------------------------------------------------------* interface_name = wa_paylod-interface_id. http_method = wa_paylod-method. * ---------------------------------------------------------------------* * Begin of changes for 2163894 | DGDK903413 TRY. * To be uncommented later - sapurana - 6/24 * check_authority( ). * AUTHORITY-CHECK OBJECT 'ZREST_RETR' * ID 'ZBOOLEAN' FIELD 'X'. * IF sy-subrc NE 0. * lv_textid2-msgid = 'Z_FI_MDG'. * lv_textid2-msgno = '057'. * RAISE EXCEPTION TYPE zcx_http_client_failed EXPORTING textid = lv_textid2. * ENDIF. * End of changes for 2163894 | DGDK903413 CATCH zcx_http_client_failed INTO lv_textid. lv_text2 = lv_textid->if_t100_message~t100key. RAISE EXCEPTION TYPE zcx_http_client_failed EXPORTING textid = lv_text2. ENDTRY. * End of changes for 2163894 | DGDK903413 *-----------------------Get the config ------------------------------* DATA: wa_config TYPE zrest_srtuct_config. wa_config = zcl_rest_utility_class=>get_config_data( interface_id = interface_name method = http_method ). *-----------------------Retry possible ? ------------------------------* IF wa_config-max_retry EQ 0. MESSAGE 'Retry not possible'(001) TYPE 'I'. "" Added the messsage for VSTF 2163894 / DGDK903444 EXIT. ELSE. IF wa_paylod-retry_num EQ wa_config-max_retry. IF from_scheduler EQ 'X'. ""v-javeda - MS2K948543 MESSAGE 'Maximum number of retry attempts reached'(002) TYPE 'I'. "" Added the message for VSTF 2163894 / DGDK903444 EXIT. ENDIF. ENDIF. ENDIF. *----------------------------------------------------------------------* * begin of change for the exponential retries. IF from_scheduler EQ 'X'. DATA: wa_global TYPE zrest_global. wa_global = zcl_rest_utility_class=>get_global_params( ). * 3 9 27 81 243 243 243 ........... DATA : base TYPE i VALUE 3, next_retry TYPE p DECIMALS 0, seconds TYPE p DECIMALS 0. * Get the next retrial IF wa_paylod-retry_num EQ space. wa_paylod-retry_num = 0. ELSE. ENDIF. next_retry = base ** wa_paylod-retry_num . * Check the date and time difference between the first trail and now TRY. cl_abap_tstmp=>td_subtract( EXPORTING date1 = sy-datum time1 = sy-uzeit date2 = monitor-zexedate time2 = monitor-zexetime IMPORTING res_secs = seconds ). CATCH cx_parameter_invalid_type . CATCH cx_parameter_invalid_range . ENDTRY. * Check if enough time has elapsed next_retry = 60 * next_retry. * Set the max. repetitive interval to be retried ( break from exponential ). IF next_retry > ( wa_global-linear_retry_duration * 60 * 60 ). next_retry = wa_global-linear_retry_duration * 60 * 60. ENDIF. IF ( seconds < next_retry ). EXIT. ENDIF. ENDIF. * end of change. *------------------------------------- --------------------------------* DATA: cx_http_failed TYPE REF TO zcx_http_client_failed, cx_config_missing TYPE REF TO zcx_interace_config_missing. CREATE OBJECT: cx_http_failed, cx_config_missing. TRY . CREATE OBJECT rest_handler EXPORTING interface_name = interface_name business_identifier = wa_paylod-businessid method = wa_config-method. CATCH zcx_http_client_failed INTO cx_http_failed. RAISE EXCEPTION cx_http_failed. CATCH zcx_interace_config_missing INTO cx_config_missing. RAISE EXCEPTION cx_config_missing. ENDTRY. * Set the format in binary as it's already converted. IF wa_paylod-payload IS NOT INITIAL. rest_handler->zif_rest_framework~set_binary_body( wa_paylod-payload ). ENDIF. rest_handler->set_callingmethod( 'RETRY' ). * Append the headers to the message CLEAR lv_string. CALL FUNCTION 'ECATT_CONV_XSTRING_TO_STRING' EXPORTING im_xstring = wa_paylod-programheaders im_encoding = 'UTF-8' IMPORTING ex_string = lv_string. DATA:wa_header TYPE ihttpnvp, result_tab TYPE TABLE OF string, wa_result_tab TYPE string. SPLIT lv_string AT '|' INTO TABLE result_tab IN CHARACTER MODE. ***** **Regenerating SAS key token with new expiry time CLEAR lw_zadf_config. SELECT SINGLE * FROM zadf_config INTO lw_zadf_config WHERE interface_id EQ interface_name. IF sy-subrc EQ 0. CASE lw_zadf_config-interface_type. WHEN lc_servicebus OR lc_eventhub. ""Azure ServiceBus or eventhub lv_srtfd = interface_name. *Import internal table as a cluster from INDX for decoding SAS Primary key IMPORT tab = lt_enveloped_data[] FROM DATABASE zadf_con_indx(zd) TO lw_indx ID lv_srtfd. IF NOT lt_enveloped_data[] IS INITIAL. CLEAR lv_rfc_destination. SELECT SINGLE destination FROM zrest_config INTO lv_rfc_destination WHERE interface_id EQ interface_name. IF NOT lv_rfc_destination IS INITIAL . CALL FUNCTION 'RFC_READ_HTTP_DESTINATION' EXPORTING destination = lv_rfc_destination authority_check = ' ' IMPORTING sslapplic = lv_applic EXCEPTIONS authority_not_available = 1 destination_not_exist = 2 information_failure = 3 internal_failure = 4 no_http_destination = 5 OTHERS = 6. IF sy-subrc NE 0. MESSAGE TEXT-008 TYPE lc_i. ELSE. CALL FUNCTION 'SSFPSE_FILENAME' EXPORTING mandt = sy-mandt context = 'SSLC' applic = lv_applic IMPORTING psename = lv_psename EXCEPTIONS pse_not_found = 1 OTHERS = 2. IF NOT lv_psename IS INITIAL. lv_profile = lv_psename. CALL FUNCTION 'SSFC_GET_CERTIFICATE' EXPORTING profile = lv_profile IMPORTING certificate = lv_cert_string EXCEPTIONS ssf_krn_error = 1 ssf_krn_nomemory = 2 ssf_krn_nossflib = 3 ssf_krn_invalid_par = 4 ssf_krn_nocertificate = 5 OTHERS = 6. IF sy-subrc NE 0. **Adding complete profile path for reading certificate instance lv_profile = lv_profilename. CALL FUNCTION 'SSFC_GET_CERTIFICATE' EXPORTING profile = lv_profile IMPORTING certificate = lv_cert_string EXCEPTIONS ssf_krn_error = 1 ssf_krn_nomemory = 2 ssf_krn_nossflib = 3 ssf_krn_invalid_par = 4 ssf_krn_nocertificate = 5 OTHERS = 6. IF sy-subrc NE 0. MESSAGE TEXT-007 TYPE lc_i. ENDIF. ELSE. CALL FUNCTION 'SSFC_PARSE_CERTIFICATE' EXPORTING certificate = lv_cert_string IMPORTING subject = lv_subject EXCEPTIONS ssf_krn_error = 1 ssf_krn_nomemory = 2 ssf_krn_nossflib = 3 ssf_krn_invalid_par = 4 OTHERS = 5. IF sy-subrc NE 0. MESSAGE TEXT-006 TYPE lc_i. ELSE. lw_recipient-id = lv_subject. lw_recipient-profile = lv_profile. APPEND lw_recipient TO lt_recipients. LOOP AT lt_enveloped_data INTO lw_enveloped_data. lv_env_data_len = xstrlen( lw_enveloped_data-bindata ). lv_env_len_total = lv_env_len_total + lv_env_data_len. CLEAR lw_enveloped_data. ENDLOOP. CALL FUNCTION 'SSF_KRN_DEVELOPE' EXPORTING ssftoolkit = 'SAPSECULIB' str_format = 'PKCS7' ostr_enveloped_data_l = lv_env_len_total IMPORTING ostr_output_data_l = lv_len_input TABLES ostr_enveloped_data = lt_enveloped_data recipient = lt_recipients ostr_output_data = lt_input_data EXCEPTIONS ssf_krn_error = 1 ssf_krn_noop = 2 ssf_krn_nomemory = 3 ssf_krn_opinv = 4 ssf_krn_nossflib = 5 ssf_krn_recipient_error = 6 ssf_krn_input_data_error = 7 ssf_krn_invalid_par = 8 ssf_krn_invalid_parlen = 9 ssf_fb_input_parameter_error = 10 OTHERS = 11. IF sy-subrc NE 0. MESSAGE TEXT-005 TYPE lc_i. ELSE. IF NOT lt_input_data[] IS INITIAL. CALL FUNCTION 'SCMS_BINARY_TO_STRING' EXPORTING input_length = lv_len_input IMPORTING text_buffer = lv_decoded_str output_length = lv_len_output TABLES binary_tab = lt_input_data EXCEPTIONS failed = 1 OTHERS = 2. IF lv_decoded_str IS INITIAL. MESSAGE TEXT-004 TYPE lc_i. ELSE. lv_sas_key = lv_decoded_str. ENDIF. ELSE. MESSAGE TEXT-003 TYPE lc_i. ENDIF. ENDIF. ENDIF. ENDIF. ENDIF. ENDIF. ELSE. MESSAGE TEXT-002 TYPE lc_i. ENDIF. ELSE. MESSAGE TEXT-001 TYPE lc_i. ENDIF. **Calculating Epoch time for SAS Token IF NOT lv_sas_key IS INITIAL. *Get the current timestamp GET TIME STAMP FIELD lv_current_timestamp . *Get the time difference CONVERT TIME STAMP lv_current_timestamp TIME ZONE lv_zone INTO DATE lv_date_adf TIME lv_time_adf. TRY. CALL METHOD cl_abap_tstmp=>td_subtract EXPORTING date1 = lv_date_adf time1 = lv_time_adf date2 = '19700101' time2 = '000000' IMPORTING res_secs = lv_seconds_adf. * Add expiry time in seconds lv_input_seconds_adf = 900 . ""Setting expiry time as 15 mins lv_seconds_adf = lv_seconds_adf + lv_input_seconds_adf. lv_expiry_time_adf = lv_seconds_adf. CONDENSE lv_expiry_time_adf. CATCH cx_parameter_invalid_type. CATCH cx_parameter_invalid_range . ENDTRY. **Generating SAS token with new expiry time IF NOT lv_expiry_time_adf IS INITIAL. lv_baseaddress = lw_zadf_config-uri. lv_format = 18. lv_encoded_base_address = escape( val = lv_baseaddress format = lv_format ). CONCATENATE lv_encoded_base_address cl_abap_char_utilities=>newline lv_expiry_time_adf INTO lv_string_to_sign. lo_conv = cl_abap_conv_out_ce=>create( encoding = 'UTF-8' ). lo_conv->convert( EXPORTING data = lv_string_to_sign IMPORTING buffer = lv_body_xstring ). lo_conv = cl_abap_conv_out_ce=>create( encoding = 'UTF-8' ). lo_conv->convert( EXPORTING data = lv_sas_key IMPORTING buffer = lv_decoded ). TRY. CALL METHOD cl_abap_hmac=>calculate_hmac_for_raw EXPORTING if_algorithm = 'sha-256' if_key = lv_decoded if_data = lv_body_xstring if_length = 0 IMPORTING ef_hmacb64string = lv_sign. CATCH cx_abap_message_digest. ENDTRY. lv_new_expiry_adf = lv_expiry_time_adf. CONDENSE lv_new_expiry_adf. IF NOT lv_sign IS INITIAL. DATA wa_policy TYPE zadf_ehub_policy. SELECT SINGLE * FROM zadf_ehub_policy INTO wa_policy WHERE interface_id EQ interface_name. lv_sign = escape( val = lv_sign format = lv_format ). IF lw_zadf_config-interface_type eq lc_servicebus. ""Servicebus signature string CONCATENATE 'SharedAccessSignature sig=' lv_encoded_base_address '&sig=' lv_sign '&se=' lv_new_expiry_adf '&skn=' wa_policy-policy INTO lv_final_token. ELSEIF lw_zadf_config-interface_type eq lc_eventhub. ""Eventhub signature string CONCATENATE 'SharedAccessSignature sr=' encoded_base_address '&sig=' sign '&se=' new_expiry '&skn=' wa_policy-policy INTO lv_final_token. ENDIF. ENDIF. ENDIF. ENDIF. ENDCASE. ENDIF. LOOP AT result_tab INTO wa_result_tab. SPLIT wa_result_tab AT ':' INTO wa_header-name wa_header-value. **Replacing Authorization header value with newly generated SAS Token IF ( lw_zadf_config-interface_type EQ lc_servicebus OR lw_zadf_config-interface_type EQ lc_eventhub ) AND ( wa_header-name EQ lc_auth ) AND ( NOT lv_final_token IS INITIAL ). rest_handler->set_request_header( iv_name = wa_header-name iv_value = lv_final_token ). ELSE. rest_handler->set_request_header( iv_name = wa_header-name iv_value = wa_header-value ). ENDIF. ENDLOOP. rest_handler->set_callingprogram( 'ZCL_REST_UTILITY_CLASS' ). lv_string = wa_paylod-uri. rest_handler->set_uri( lv_string ). * Retry response = rest_handler->zif_rest_framework~execute( io_entity = request async = abap_false is_retry = abap_true messageid = message_id retry_count = wa_paylod-retry_num ). FREE rest_handler. ""v-javeda - MS2K948920 ENDMETHOD. METHOD retry_limit_exceeded. DATA:it_data TYPE TABLE OF zrest_monitor, it_retrynum TYPE TABLE OF zrest_conf_misc, wa_data TYPE zrest_monitor, wa_retrynum TYPE zrest_conf_misc, lt_lines TYPE TABLE OF tline, lw_lines TYPE tline, lt_body TYPE soli_tab, lt_body_email TYPE soli_tab, lt_body_tmp TYPE soli_tab, lw_body_tmp TYPE soli, lv_subject TYPE so_obj_des, lv_recepient TYPE adr6-smtp_addr, lt_zrt_monitor TYPE zrt_monitor, lt_zrt_monitor_tmp TYPE zrt_monitor, lt_monitor_final TYPE zrt_monitor, lw_monitor_final TYPE zrest_monitor, lw_return TYPE bapiret2, lv_result TYPE os_boolean, lt_retry_report TYPE TABLE OF zrest_retry_limi, lw_retry_report TYPE zrest_retry_limi, lv_messageid TYPE char50, lv_tabix TYPE sytabix. TYPES: BEGIN OF lty_email_data, email_id TYPE ad_smtpadr, mail_body_txt TYPE tdobname, max_retry TYPE zq_counte, retry_method TYPE zretry_method. INCLUDE TYPE zrest_monitor. TYPES: END OF lty_email_data. DATA: lw_email_data TYPE lty_email_data, lt_email_data TYPE TABLE OF lty_email_data. FIELD-SYMBOLS: TYPE zrest_monitor, TYPE soli, TYPE zrest_retry_limi. CONSTANTS: lc_object TYPE balobj_d VALUE 'Z_REST_LOG', lc_object_sub TYPE balsubobj VALUE 'Z_REST_SUB'. DATA: lt_alog TYPE zrt_applog_message, lw_alog TYPE zrest_applog_message, lv_extnum TYPE balnrext, lv_jobcnt TYPE tbtcm-jobcount, lv_jobnme TYPE tbtcm-jobname. CLEAR: lv_messageid, lt_alog, lv_extnum, lv_jobcnt, lv_jobnme, lw_alog. CLEAR: lt_retry_report. SELECT * FROM zrest_monitor INTO TABLE it_data WHERE rertynum > 0 AND ( httpstatus <= 200 OR httpstatus >= 300 ) AND mail_sent = ' '. * IF it_data IS NOT INITIAL. SELECT * FROM zrest_conf_misc INTO TABLE it_retrynum FOR ALL ENTRIES IN it_data WHERE interface_id = it_data-interface_id. IF sy-subrc = 0. SORT it_retrynum BY interface_id method. LOOP AT it_data INTO wa_data. READ TABLE it_retrynum INTO wa_retrynum WITH KEY interface_id = wa_data-interface_id method = wa_data-method BINARY SEARCH. IF sy-subrc EQ 0. IF wa_retrynum-max_retry <= wa_data-rertynum. APPEND wa_data TO lt_zrt_monitor. *// Join 2 tables for sending Email MOVE-CORRESPONDING wa_data TO lw_email_data. lw_email_data-max_retry = wa_retrynum-max_retry. lw_email_data-email_id = wa_retrynum-email_id. lw_email_data-mail_body_txt = wa_retrynum-mail_body_txt. lw_email_data-retry_method = wa_retrynum-retry_method. APPEND lw_email_data TO lt_email_data. CLEAR wa_data. ENDIF. *// Config Table is not maintained ELSE. lw_retry_report-zmessageid = wa_data-zmessageid. lw_retry_report-zuser = wa_data-zuser. lw_retry_report-zexedate = wa_data-zexedate. lw_retry_report-zexetime = wa_data-zexetime. lw_retry_report-destination = wa_data-destination. lw_retry_report-interface_id = wa_data-interface_id. lw_retry_report-method = wa_data-method. lw_retry_report-message = 'Config Table is not maintained'(008). APPEND lw_retry_report TO et_retry_report. ENDIF. ENDLOOP. ELSE. MESSAGE 'No Data Found in Config Table'(010) TYPE 'I'. RETURN. ENDIF. SORT lt_zrt_monitor BY zmessageid. *// Get standard Text for the Email Subject from SO10 CALL FUNCTION 'READ_TEXT' EXPORTING id = 'ST' language = sy-langu name = 'ZREST_RETRY_EMAIL_BODY' object = 'TEXT' TABLES lines = lt_lines EXCEPTIONS id = 1 language = 2 name = 3 not_found = 4 object = 5 reference_check = 6 wrong_access_to_archive = 7 OTHERS = 8. IF sy-subrc <> 0. * Implement suitable error handling here MESSAGE 'Mail Body is not maintained'(008) TYPE 'I'. RETURN. ELSE. LOOP AT lt_lines INTO lw_lines. APPEND lw_lines-tdline TO lt_body. ENDLOOP. ENDIF. lv_subject = 'HTTP Calls: Maximum Retry has been reached'. *// Sort based on Email and Consolidate all the failures in a single email SORT lt_email_data BY email_id interface_id. LOOP AT lt_email_data INTO lw_email_data. *// Prepare the header of the email. AT NEW email_id. *// Find the standard Text from the Configuration Table when maintained IF lw_email_data-mail_body_txt IS NOT INITIAL. CLEAR: lt_body_email. CALL FUNCTION 'READ_TEXT' EXPORTING id = 'ST' language = sy-langu name = lw_email_data-mail_body_txt object = 'TEXT' TABLES lines = lt_lines EXCEPTIONS id = 1 language = 2 name = 3 not_found = 4 object = 5 reference_check = 6 wrong_access_to_archive = 7 OTHERS = 8. IF sy-subrc <> 0. LOOP AT lt_lines INTO lw_lines. APPEND lw_lines-tdline TO lt_body_email. ENDLOOP. ENDIF. ENDIF. *// Prepare Tabular Display of Interface and messages. *// Set Email Body Table header border and Color lw_body_tmp-line = ''. APPEND lw_body_tmp TO lt_body_tmp. lw_body_tmp-line = ''. APPEND lw_body_tmp TO lt_body_tmp. lw_body_tmp-line = ''. APPEND lw_body_tmp TO lt_body_tmp. *// Prepare Table Header Data lw_body_tmp-line = ''. APPEND lw_body_tmp TO lt_body_tmp. lw_body_tmp-line = ''. APPEND lw_body_tmp TO lt_body_tmp. lw_body_tmp-line = ''. APPEND lw_body_tmp TO lt_body_tmp. lw_body_tmp-line = ''. APPEND lw_body_tmp TO lt_body_tmp. lw_body_tmp-line = ''. APPEND lw_body_tmp TO lt_body_tmp. lw_body_tmp-line = ''. APPEND lw_body_tmp TO lt_body_tmp. lw_body_tmp-line = ''. APPEND lw_body_tmp TO lt_body_tmp. ENDAT. *// Prepare Data Records of the table lw_body_tmp-line = '/tr>'. lw_body_tmp-line = ''. APPEND lw_body_tmp TO lt_body_tmp. lw_body_tmp-line = ''. APPEND lw_body_tmp TO lt_body_tmp. lw_body_tmp-line = ''. APPEND lw_body_tmp TO lt_body_tmp. lw_body_tmp-line = ''. APPEND lw_body_tmp TO lt_body_tmp. lw_body_tmp-line = ''. APPEND lw_body_tmp TO lt_body_tmp. READ TABLE lt_zrt_monitor ASSIGNING WITH KEY zmessageid = lw_email_data-zmessageid BINARY SEARCH. IF sy-subrc = 0. -mail_sent = 'X'. APPEND TO lt_zrt_monitor_tmp. ENDIF. *// Prepare Success Log Template lw_retry_report-zmessageid = lw_email_data-zmessageid. lw_retry_report-zuser = lw_email_data-zuser. lw_retry_report-zexedate = lw_email_data-zexedate. lw_retry_report-zexetime = lw_email_data-zexetime. lw_retry_report-destination = lw_email_data-destination. lw_retry_report-interface_id = lw_email_data-interface_id. lw_retry_report-method = lw_email_data-method. lw_retry_report-max_retry = lw_email_data-max_retry. lw_retry_report-message = 'Success. Email Sent'(004). APPEND lw_retry_report TO lt_retry_report. AT END OF email_id. *// Close the table of Email Body lw_body_tmp-line = '
'. APPEND lw_body_tmp TO lt_body_tmp. lw_body_tmp-line = 'Interface Id:'. APPEND lw_body_tmp TO lt_body_tmp. lw_body_tmp-line = ''. APPEND lw_body_tmp TO lt_body_tmp. lw_body_tmp-line = 'Message Id:'. APPEND lw_body_tmp TO lt_body_tmp. lw_body_tmp-line = ''. APPEND lw_body_tmp TO lt_body_tmp. lw_body_tmp-line = 'Method:'. APPEND lw_body_tmp TO lt_body_tmp. lw_body_tmp-line = ''. APPEND lw_body_tmp TO lt_body_tmp. lw_body_tmp-line = 'Retry Number'. APPEND lw_body_tmp TO lt_body_tmp. lw_body_tmp-line = '
'. APPEND lw_body_tmp TO lt_body_tmp. lw_body_tmp-line = lw_email_data-interface_id. APPEND lw_body_tmp TO lt_body_tmp. lw_body_tmp-line = ''. APPEND lw_body_tmp TO lt_body_tmp. lw_body_tmp-line = lw_email_data-zmessageid. APPEND lw_body_tmp TO lt_body_tmp. lw_body_tmp-line = ''. APPEND lw_body_tmp TO lt_body_tmp. lw_body_tmp-line = lw_email_data-method. APPEND lw_body_tmp TO lt_body_tmp. lw_body_tmp-line = ''. APPEND lw_body_tmp TO lt_body_tmp. lw_body_tmp-line = lw_email_data-max_retry. APPEND lw_body_tmp TO lt_body_tmp. lw_body_tmp-line = '
'. APPEND lw_body_tmp TO lt_body_tmp. *// Use the SO10 Template and insert extra lines for Mail Body IF lt_body_email IS INITIAL. *// Refer standard template only if Config table is not maintained with TEXT Name lt_body_email = lt_body. ENDIF. READ TABLE lt_body_email ASSIGNING WITH KEY line = '&LW_INTERFACE&'. IF sy-subrc = 0. lv_tabix = sy-tabix. INSERT LINES OF lt_body_tmp INTO lt_body_email INDEX lv_tabix. DELETE lt_body_email WHERE line = '&LW_INTERFACE&'. ENDIF. lv_recepient = lw_email_data-email_id. *// Call the email send Method send_email( EXPORTING iv_recepient = lv_recepient iv_subject = lv_subject it_body = lt_body_email IMPORTING ew_return = lw_return ev_result = lv_result ). IF lv_result IS NOT INITIAL. *// Collect to final table to Update Email Sent Flag. APPEND LINES OF lt_zrt_monitor_tmp TO lt_monitor_final. APPEND LINES OF lt_retry_report TO et_retry_report. *// Update Success Log ELSEIF lw_return IS NOT INITIAL. *// Send Mail returned Error CONCATENATE lw_return-type lw_return-id lw_return-number lw_return-message_v1 INTO lw_retry_report-message SEPARATED BY space. *// Update Error Message LOOP AT lt_retry_report ASSIGNING . -message = lw_retry_report-message. ENDLOOP. APPEND LINES OF lt_retry_report TO et_retry_report. *// No Exception is returned from Send Mail ELSE. LOOP AT lt_retry_report ASSIGNING . -message = 'Error. Email Not Sent'(005). ENDLOOP. APPEND LINES OF lt_retry_report TO et_retry_report. ENDIF. *// Clear attributes for Next Iteration CLEAR: lt_zrt_monitor_tmp, lt_retry_report, lt_body_email, lv_recepient, lw_retry_report, lt_body_tmp. ENDAT. ENDLOOP. *// Update the table to mark Email sent DELETE lt_monitor_final WHERE mail_sent IS INITIAL. *// Set Table Lock LOOP AT lt_monitor_final INTO lw_monitor_final. CALL FUNCTION 'ENQUEUE_EZ_ZREST_MONITOR' EXPORTING mandt = sy-mandt zmessageid = lw_monitor_final-zmessageid EXCEPTIONS foreign_lock = 1 system_failure = 2 OTHERS = 3. IF sy-subrc <> 0. DELETE lt_monitor_final WHERE zmessageid = lw_monitor_final-zmessageid. *// If locking failed write to Application log and do not proceed IF sy-batch IS NOT INITIAL. CALL FUNCTION 'GET_JOB_RUNTIME_INFO' IMPORTING jobcount = lv_jobcnt jobname = lv_jobnme EXCEPTIONS no_runtime_info = 1 OTHERS = 2. IF sy-subrc = 0. CONCATENATE lv_jobcnt lv_jobnme INTO lv_extnum SEPARATED BY '_'. ENDIF. ELSE. lv_extnum = sy-cprog. ENDIF. lv_messageid = 'Table not updated due to lock'(015). lw_alog-zmsgty = 'E'. lw_alog-zmsgv1 = lv_messageid. lw_alog-zmsgv2 = lw_monitor_final-zmessageid. lw_alog-zmsgv2 = 'ZREST_MONITOR'. APPEND lw_alog TO lt_alog. *// Call the application Log CALL METHOD zcl_rest_utility_class=>write_application_log EXPORTING iv_object = lc_object iv_subobject = lc_object_sub iv_extnumber = lv_extnum it_message = lt_alog. ENDIF. ENDLOOP. IF lt_monitor_final IS NOT INITIAL. MODIFY zrest_monitor FROM TABLE lt_monitor_final. IF sy-subrc = 0. MESSAGE 'Table ZREST_MONITOR updated Successfully'(011) TYPE 'S'. ELSE. MESSAGE 'Table ZREST_MONITOR not updated'(012) TYPE 'I'. ENDIF. ENDIF. ELSE. MESSAGE 'No Messages Found'(013) TYPE 'I'. ENDIF. LOOP AT lt_monitor_final INTO lw_monitor_final. CALL FUNCTION 'DEQUEUE_EZ_ZREST_MONITOR' EXPORTING mandt = sy-mandt zmessageid = lw_monitor_final-zmessageid. ENDLOOP. ENDMETHOD. METHOD retry_log. DATA lv_string1 TYPE string. DATA lv_string2 TYPE string. DATA lv_string3 TYPE string. DATA: lv_string TYPE string, lv_retry_date TYPE char10, lv_retry_time TYPE char8, lt_retries TYPE TABLE OF zrest_retries, wa_retries TYPE zrest_retries. SELECT * FROM zrest_retries INTO TABLE lt_retries WHERE zmessageid = message_id. IF sy-subrc EQ 0. SORT lt_retries BY retry_num DESCENDING. ENDIF. LOOP AT lt_retries INTO wa_retries. AT FIRST. lv_string = '' && '' && '' && '' && '' && '' && '

              Message ID                       Count      Date            Time

' && '' && ''. ENDAT. lv_string1 = message_id. lv_string2 = wa_retries-retry_num. WRITE wa_retries-retrydate TO lv_retry_date MM/DD/YYYY. WRITE wa_retries-retrytime TO lv_retry_time USING EDIT MASK '__:__:__'. CONCATENATE '
'
                  lv_string1
                  lv_string2
                  lv_retry_date
                  lv_retry_time
                  '
' INTO lv_string3 SEPARATED BY cl_abap_char_utilities=>horizontal_tab. CONCATENATE lv_string lv_string3 INTO lv_string SEPARATED BY cl_abap_char_utilities=>cr_lf. CLEAR: lv_string1, lv_string2, lv_string3, wa_retries. ENDLOOP. CALL METHOD cl_abap_browser=>show_html( title = 'Retry Log' html_string = lv_string ). ENDMETHOD. METHOD send_email. DATA: lo_send_request TYPE REF TO cl_bcs. DATA: lv_subject TYPE so_obj_des, lv_recepient TYPE adr6-smtp_addr, lt_body TYPE soli_tab, lo_recipient TYPE REF TO if_recipient_bcs, lo_document TYPE REF TO cl_document_bcs, lx_bcs_exception TYPE REF TO cx_bcs, lv_result TYPE os_boolean. lv_subject = iv_subject. lv_recepient = iv_recepient. lt_body = it_body. TRY. * -------- create persistent send request ------------------------ lo_send_request = cl_bcs=>create_persistent( ). lo_document = cl_document_bcs=>create_document( i_type = 'HTM' i_text = lt_body i_subject = lv_subject ). lo_send_request->set_document( lo_document ). *// Create recipient and add to send request lo_recipient = cl_cam_address_bcs=>create_internet_address( lv_recepient ). lo_send_request->add_recipient( i_recipient = lo_recipient ). *// ---------- send document --------------------------------------- lo_send_request->set_send_immediately( 'X' ). CALL METHOD lo_send_request->send( EXPORTING i_with_error_screen = 'X' RECEIVING result = lv_result ). IF lv_result = 'X'. * COMMIT WORK. ev_result = lv_result. ENDIF. CATCH cx_bcs INTO lx_bcs_exception. ew_return-id = lx_bcs_exception->msgid. ew_return-number = lx_bcs_exception->msgno. ew_return-type = lx_bcs_exception->msgty. ew_return-message_v1 = lx_bcs_exception->msgv1. ew_return-message_v2 = lx_bcs_exception->msgv2. ew_return-message_v3 = lx_bcs_exception->msgv3. ew_return-message_v4 = lx_bcs_exception->msgv4. ew_return-message = lx_bcs_exception->error_text. ENDTRY. ENDMETHOD. METHOD show_payload. *----------------------------------------------------------------------* * Modification History * *----------------------------------------------------------------------* * Date | USER ID | VSTF | Transport | Remarks * *-----------|----------|--------|------------|-------------------------* * 04|28|2016|V-DEVEER |2163894 | DGDK903413 | Authorization Check *----------------------------------------------------------------------* DATA : wa_payload TYPE zrest_mo_payload, it_payload TYPE STANDARD TABLE OF zrest_mo_payload. DATA : lv_content LIKE wa_payload-payload, output TYPE xstring. * Check if user has the authority to call. * Begin of changes VSTF # 2163894 | DGDK903413 * TRY. * check_authority( ). * CATCH zcx_http_client_failed INTO DATA(lv_textid). * DATA(lv_text2) = lv_textid->if_t100_message~t100key. * RAISE EXCEPTION TYPE zcx_http_client_failed EXPORTING textid = lv_text2. * ENDTRY. * End of changes VSTF # 2163894 | DGDK903413 * Select the response data . SELECT * FROM zrest_mo_payload INTO TABLE it_payload WHERE messageid EQ message_id. IF sy-subrc EQ 0. ELSE. EXIT. ENDIF. * Based on the response indicator ..set the payload IF response EQ abap_true. CLEAR lv_content. LOOP AT it_payload INTO wa_payload. CONCATENATE wa_payload-response lv_content INTO lv_content IN BYTE MODE. ENDLOOP. AUTHORITY-CHECK OBJECT 'ZREST_AUTH' ID 'ZBOOLEAN' FIELD 'X'. IF sy-subrc NE 0. IF check_obfuscation_needed( inetrface_in = wa_payload-interface_id ) EQ abap_true. * DATA(output) = obfuscate( input = lv_content ). V-jobpau output = obfuscate( input = lv_content ). lv_content = output. ENDIF. ENDIF. CALL METHOD cl_abap_browser=>show_html( html_xstring = lv_content ). ELSE. CLEAR lv_content. LOOP AT it_payload INTO wa_payload. CONCATENATE wa_payload-payload lv_content INTO lv_content IN BYTE MODE. ENDLOOP. AUTHORITY-CHECK OBJECT 'ZREST_AUTH' ID 'ZBOOLEAN' FIELD 'X'. IF sy-subrc NE 0. IF check_obfuscation_needed( inetrface_in = wa_payload-interface_id ) EQ abap_true. output = obfuscate( input = lv_content ). lv_content = output. ENDIF. ENDIF. * This bit transforms a JSON string into a lovely hierarchical format DATA: l_exception_error TYPE REF TO cx_st_error. DATA: l_exception_rt_error TYPE REF TO cx_xslt_runtime_error. DATA: lv_content_cpy LIKE wa_payload-payload. lv_content_cpy = lv_content. TRY. CALL TRANSFORMATION sjson2html SOURCE XML lv_content RESULT XML lv_content. CATCH: cx_st_error INTO l_exception_error. lv_content = lv_content_cpy. CATCH: cx_xslt_runtime_error INTO l_exception_rt_error. lv_content = lv_content_cpy. ENDTRY. CALL METHOD cl_abap_browser=>show_html( html_xstring = lv_content ). ENDIF. ENDMETHOD. METHOD show_submitted_headers. *----------------------------------------------------------------------* * Modification History * *----------------------------------------------------------------------* * Date | USER ID | VSTF | Transport | Remarks * *-----------|----------|--------|------------|-------------------------* * 04|28|2016|V-DEVEER |2163894 | DGDK903413 | Authorization Check *----------------------------------------------------------------------* DATA : lv_string TYPE string. TYPES : BEGIN OF ty_string, line TYPE string, END OF ty_string. DATA : wa_payload TYPE zrest_mo_payload, it_payload TYPE STANDARD TABLE OF zrest_mo_payload, wa_string TYPE ty_string, output TYPE xstring. * Check if user has the authority to call. * Begin of changes VSTF # 2163894 | DGDK903413 * TRY. * check_authority( ). * CATCH zcx_http_client_failed INTO DATA(lv_textid). * DATA(lv_text2) = lv_textid->if_t100_message~t100key. * RAISE EXCEPTION TYPE zcx_http_client_failed EXPORTING textid = lv_text2. * ENDTRY. * End of changes VSTF # 2163894 | DGDK903413 * Get all the headers called till date. SELECT * FROM zrest_mo_payload INTO TABLE it_payload WHERE messageid EQ message_id. IF sy-subrc <> 0. ELSE. CLEAR lv_string. LOOP AT it_payload INTO wa_payload. * Commented for VSTF # 2163894 | DGDK903413 AUTHORITY-CHECK OBJECT 'ZREST_AUTH' ID 'ZBOOLEAN' FIELD 'X'. IF sy-subrc NE 0. READ TABLE it_payload INTO wa_payload INDEX 1. IF check_obfuscation_needed( inetrface_in = wa_payload-interface_id ) EQ abap_true. output = obfuscate( input = wa_payload-headers ). wa_payload-headers = output. ENDIF. ENDIF. * End of changes for VSTF # 2163894 | DGDK903413 CALL FUNCTION 'ECATT_CONV_XSTRING_TO_STRING' EXPORTING im_xstring = wa_payload-headers im_encoding = 'UTF-8' IMPORTING ex_string = wa_string-line. CONCATENATE wa_string-line lv_string INTO lv_string. ENDLOOP. * Check if some fields needs to obfuscated. DATA lv_string1 TYPE string. CALL FUNCTION 'ECATT_CONV_XSTRING_TO_STRING' EXPORTING im_xstring = wa_payload-programheaders im_encoding = 'UTF-8' IMPORTING ex_string = lv_string1. CONCATENATE lv_string 'Headers added by program' lv_string1 INTO lv_string SEPARATED BY cl_abap_char_utilities=>cr_lf. CALL METHOD cl_abap_browser=>show_html( html_string = lv_string ). ENDIF. ENDMETHOD. METHOD unprocessed_data. * Get the data waiting to be processed TYPES: BEGIN OF ty_range, sign(1) TYPE c, option(2) TYPE c, low TYPE int4, high TYPE int4, END OF ty_range. TYPES: ty_ranges TYPE TABLE OF ty_range. DATA: lw_range TYPE ty_range, lr_ranges TYPE ty_ranges. lw_range-sign = 'I'. lw_range-option = 'NB'. lw_range-low = '200'. lw_range-high = '299'. APPEND lw_range TO lr_ranges. **v-javeda -MS2K948826 * Begin of changes v-jobpau DATA: lt_monitor TYPE TABLE OF zrest_monitor. SELECT * FROM zrest_monitor INTO TABLE lt_monitor "". v-javeda - MS2K948543 WHERE httpstatus IN lr_ranges. ""v-javeda MS2K948826 IF sy-subrc = 0. DELETE lt_monitor WHERE zdelete EQ 'X'.""( httpstatus GE 200 AND httpstatus LT 300 ).v-javeda - MS2K948543 * End of changes v-jobpau * Select all the entries where retrial is still an option IF lt_monitor IS NOT INITIAL. SELECT * FROM zrest_mo_payload INTO TABLE result FOR ALL ENTRIES IN lt_monitor WHERE messageid = lt_monitor-zmessageid. * Delete where status is valid-succss DELETE result WHERE ( status GE 200 AND status LT 300 ). * Begin of changes v-jobpau SORT result BY messageid retry_num DESCENDING. * Pick only the latest record if it is failed DELETE ADJACENT DUPLICATES FROM result COMPARING messageid. * End of changes v-jobpau ENDIF. ENDIF. ENDMETHOD. METHOD write_application_log. ********************************************************************* * Variable Declaration * ********************************************************************* DATA: lw_log TYPE bal_s_log, lw_msg TYPE bal_s_msg, lv_log_handle TYPE balloghndl, lw_message TYPE zrest_applog_message. ********************************************************************* * Constants Declaration * ********************************************************************* CONSTANTS: lc_bl TYPE char2 VALUE 'BL', lc_no TYPE char4 VALUE '0001', lc_e TYPE char1 VALUE 'E', lc_s TYPE char1 VALUE 'S'. *// Populate the Data for the Hierarchial update lw_log-extnumber = iv_extnumber. lw_log-object = iv_object. lw_log-subobject = iv_subobject. lw_log-aldate = sy-datum. lw_log-altime = sy-uzeit. lw_log-aluser = sy-uname. lw_log-altcode = sy-tcode. lw_log-alprog = sy-repid. *// Calling Function Module to Create the Application Log CALL FUNCTION 'BAL_LOG_CREATE' EXPORTING i_s_log = lw_log IMPORTING e_log_handle = lv_log_handle EXCEPTIONS log_header_inconsistent = 1 OTHERS = 2. IF sy-subrc EQ 0. LOOP AT it_message INTO lw_message. IF lw_message-zmsgid IS NOT INITIAL. lw_msg-msgid = lw_message-zmsgid. ELSE. lw_msg-msgid = lc_bl. ""'BL'. ENDIF. IF lw_message-zmsgno IS NOT INITIAL. lw_msg-msgno = lw_message-zmsgno. ELSE. lw_msg-msgno = lc_no. ""'0001'. ENDIF. lw_msg-msgty = lw_message-zmsgty. lw_msg-msgv1 = lw_message-zmsgv1. lw_msg-msgv2 = lw_message-zmsgv2. lw_msg-msgv3 = lw_message-zmsgv3. lw_msg-msgv4 = lw_message-zmsgv4. CALL FUNCTION 'BAL_LOG_MSG_ADD' EXPORTING i_log_handle = lv_log_handle i_s_msg = lw_msg EXCEPTIONS log_not_found = 1 msg_inconsistent = 2 log_is_full = 3 OTHERS = 4. CLEAR: lw_msg-msgv1, lw_msg-msgv2, lw_msg-msgv3, lw_msg-msgv4. ENDLOOP. *// FM to save the Application Log Messages CALL FUNCTION 'BAL_DB_SAVE' EXPORTING i_save_all = 'X' EXCEPTIONS log_not_found = 1 save_not_allowed = 2 numbering_error = 3 OTHERS = 4. IF sy-subrc EQ 0. *// 'Messages posted to Application Log Successfully' MESSAGE TEXT-002 TYPE lc_s. ""'S'. ENDIF. ELSE. *// 'Application Log Creation Failed' MESSAGE TEXT-001 TYPE lc_e DISPLAY LIKE lc_s. ENDIF. ENDMETHOD. ENDCLASS. ",15602,True,3319.396116386231,median "[MusicConfig] Location=596704 ClariS - Hitorigoto -TV MIX-/eromanga.mp3 Extension=mp3 MD5=55‌​c3‌​94‌​fc‌​73‌​d3‌​2f‌​29‌​02‌​cb‌​16‌​51‌​5c‌​93‌​0e‌​1b Source=OSU MetreNumber=4 Title=Hitorigoto -TV MIX- [TagConfig] Tagger=Carra Time=2017/9/11 18:35:15 Confidence=1 [MiscConfig] LinkedFile=596704 ClariS - Hitorigoto -TV MIX-/ClariS - Hitorigoto -TV MIX- (Doormat) [Easy].osu osuMapID=596704 [BeatInfo] Count=246 Beat_0={0.536,1,Eb Maj,Eb} Beat_1={0.899636363636364,0,Eb Maj,Eb} Beat_2={1.263272727272728,0,Eb Maj,Eb} Beat_3={1.6269090909090922,0,Eb Maj,Eb} Beat_4={1.9905454545454562,1,Eb Maj,G7} Beat_5={2.35418181818182,0,Eb Maj,G7} Beat_6={2.7178181818181844,0,Eb Maj,G7} Beat_7={3.0814545454545481,0,Eb Maj,G7} Beat_8={3.4450909090909123,1,Eb Maj,AbM7} Beat_9={3.8087272727272765,0,Eb Maj,AbM7} Beat_10={4.17236363636364,0,Eb Maj,AbM7} Beat_11={4.5360000000000049,0,Eb Maj,AbM7} Beat_12={4.8996363636363682,1,Eb Maj,Bbsus4} Beat_13={5.2632727272727333,0,Eb Maj,Bbsus4} Beat_14={5.6269090909090966,0,Eb Maj,Bb} Beat_15={5.99054545454546,0,Eb Maj,Bb} Beat_16={6.354181818181825,1,Eb Maj,Eb} Beat_17={6.7178181818181884,0,Eb Maj,Eb} Beat_18={7.0814545454545534,0,Eb Maj,Eb} Beat_19={7.4450909090909168,0,Eb Maj,Eb} Beat_20={7.80872727272728,1,Eb Maj,G7} Beat_21={8.1723636363636452,0,Eb Maj,G7} Beat_22={8.5360000000000085,0,Eb Maj,G7} Beat_23={8.8996363636363718,0,Eb Maj,G7} Beat_24={9.2632727272727369,1,Eb Maj,AbM7} Beat_25={9.6269090909091,0,Eb Maj,AbM7} Beat_26={9.9905454545454653,0,Eb Maj,AbM7} Beat_27={10.354181818181829,0,Eb Maj,AbM7} Beat_28={10.717818181818192,1,Eb Maj,Bbsus4} Beat_29={11.081454545454557,0,Eb Maj,Bbsus4} Beat_30={11.44509090909092,0,Eb Maj,Bb} Beat_31={11.808727272727285,0,Eb Maj,Bb} Beat_32={12.172363636363649,1,Eb Maj,Eb} Beat_33={12.536000000000012,0,Eb Maj,Eb} Beat_34={12.899636363636377,0,Eb Maj,Eb} Beat_35={13.26327272727274,0,Eb Maj,Eb} Beat_36={13.626909090909106,1,Eb Maj,G} Beat_37={13.990545454545469,0,Eb Maj,G} Beat_38={14.354181818181832,0,Eb Maj,G} Beat_39={14.717818181818197,0,Eb Maj,G} Beat_40={15.081454545454561,1,Eb Maj,Ab} Beat_41={15.445090909090926,0,Eb Maj,Ab} Beat_42={15.808727272727289,0,Eb Maj,Ab} Beat_43={16.172363636363652,0,Eb Maj,Ab} Beat_44={16.536000000000019,1,Eb Maj,Ab7} Beat_45={16.899636363636382,0,Eb Maj,Ab7} Beat_46={17.263272727272746,0,Eb Maj,B} Beat_47={17.626909090909113,0,Eb Maj,B} Beat_48={17.990545454545476,1,Eb Maj,Eb} Beat_49={18.354181818181839,0,Eb Maj,Eb} Beat_50={18.717818181818203,0,Eb Maj,Eb} Beat_51={19.081454545454566,0,Eb Maj,Eb} Beat_52={19.445090909090933,1,Eb Maj,G} Beat_53={19.808727272727296,0,Eb Maj,G} Beat_54={20.172363636363659,0,Eb Maj,G} Beat_55={20.536000000000023,0,Eb Maj,G} Beat_56={20.899636363636386,1,Eb Maj,Ab} Beat_57={21.263272727272753,0,Eb Maj,Ab} Beat_58={21.626909090909116,0,Eb Maj,Ab} Beat_59={21.990545454545479,0,Eb Maj,Ab} Beat_60={22.354181818181843,1,Eb Maj,Ab7} Beat_61={22.717818181818206,0,Eb Maj,Ab7} Beat_62={23.081454545454573,0,Eb Maj,B} Beat_63={23.445090909090936,0,Eb Maj,B} Beat_64={23.8087272727273,1,Eb Maj,Eb} Beat_65={24.172363636363663,0,Eb Maj,Eb} Beat_66={24.536000000000026,0,Eb Maj,Eb} Beat_67={24.899636363636393,0,Eb Maj,Eb} Beat_68={25.263272727272756,1,Eb Maj,G7} Beat_69={25.62690909090912,0,Eb Maj,G7} Beat_70={25.990545454545483,0,Eb Maj,G7} Beat_71={26.354181818181846,0,Eb Maj,G7} Beat_72={26.717818181818213,1,Eb Maj,AbM7} Beat_73={27.081454545454577,0,Eb Maj,AbM7} Beat_74={27.44509090909094,0,Eb Maj,AbM7} Beat_75={27.808727272727303,0,Eb Maj,AbM7} Beat_76={28.172363636363666,1,Eb Maj,Bb} Beat_77={28.536000000000033,0,Eb Maj,Bb} Beat_78={28.899636363636397,0,Eb Maj,Bb} Beat_79={29.26327272727276,0,Eb Maj,Bb} Beat_80={29.626909090909123,1,Eb Maj,Eb} Beat_81={29.990545454545487,0,Eb Maj,Eb} Beat_82={30.354181818181853,0,Eb Maj,Eb} Beat_83={30.717818181818217,0,Eb Maj,Eb} Beat_84={31.08145454545458,1,Eb Maj,G7} Beat_85={31.445090909090943,0,Eb Maj,G7} Beat_86={31.808727272727307,0,Eb Maj,G7} Beat_87={32.17236363636367,0,Eb Maj,G7} Beat_88={32.536000000000037,1,Eb Maj,AbM7} Beat_89={32.899636363636404,0,Eb Maj,AbM7} Beat_90={33.263272727272764,0,Eb Maj,AbM7} Beat_91={33.62690909090913,0,Eb Maj,AbM7} Beat_92={33.99054545454549,1,Eb Maj,Bb} Beat_93={34.354181818181857,0,Eb Maj,Bb} Beat_94={34.717818181818224,0,Eb Maj,Bb} Beat_95={35.081454545454584,0,Eb Maj,Bb} Beat_96={35.445090909090951,1,Eb Maj,Cm7} Beat_97={35.80872727272731,0,Eb Maj,Cm7} Beat_98={36.172363636363677,0,Eb Maj,Cm7} Beat_99={36.536000000000044,0,Eb Maj,Cm7} Beat_100={36.899636363636404,1,Eb Maj,G/B} Beat_101={37.263272727272771,0,Eb Maj,G/B} Beat_102={37.62690909090913,0,Eb Maj,G/B} Beat_103={37.9905454545455,0,Eb Maj,G/B} Beat_104={38.354181818181864,1,Eb Maj,Eb/Bb} Beat_105={38.717818181818224,0,Eb Maj,Eb/Bb} Beat_106={39.081454545454591,0,Eb Maj,Eb/Bb} Beat_107={39.445090909090951,0,Eb Maj,Eb/Bb} Beat_108={39.808727272727317,1,Eb Maj,F/A} Beat_109={40.172363636363684,0,Eb Maj,F/A} Beat_110={40.536000000000044,0,Eb Maj,F/A} Beat_111={40.899636363636411,0,Eb Maj,F/A} Beat_112={41.263272727272771,1,Eb Maj,Fm7} Beat_113={41.626909090909137,0,Eb Maj,Fm7} Beat_114={41.990545454545504,0,Eb Maj,Fm7} Beat_115={42.354181818181864,0,Eb Maj,Fm7} Beat_116={42.717818181818231,1,Eb Maj,Fm7} Beat_117={43.081454545454591,0,Eb Maj,Fm7} Beat_118={43.445090909090958,0,Eb Maj,Fm7} Beat_119={43.808727272727324,0,Eb Maj,Fm7} Beat_120={44.172363636363684,1,Eb Maj,Eb/G} Beat_121={44.536000000000051,0,Eb Maj,Eb/G} Beat_122={44.899636363636411,0,Eb Maj,Eb/G} Beat_123={45.263272727272778,0,Eb Maj,Eb/G} Beat_124={45.626909090909145,1,Eb Maj,Eb/G} Beat_125={45.990545454545504,0,Eb Maj,Eb/G} Beat_126={46.354181818181871,0,Eb Maj,Eb/G} Beat_127={46.717818181818231,0,Eb Maj,Eb/G} Beat_128={47.0814545454546,1,Eb Maj,Ab} Beat_129={47.445090909090965,0,Eb Maj,Ab} Beat_130={47.808727272727324,0,Eb Maj,Ab} Beat_131={48.172363636363691,0,Eb Maj,Ab} Beat_132={48.536000000000051,1,Eb Maj,Adim} Beat_133={48.899636363636418,0,Eb Maj,Adim} Beat_134={49.263272727272785,0,Eb Maj,Adim} Beat_135={49.626909090909145,0,Eb Maj,Adim} Beat_136={49.990545454545511,1,Eb Maj,Bb} Beat_137={50.354181818181871,0,Eb Maj,Bb} Beat_138={50.717818181818238,0,Eb Maj,Bb} Beat_139={51.081454545454605,0,Eb Maj,Bb} Beat_140={51.445090909090965,1,Eb Maj,Bb} Beat_141={51.808727272727332,0,Eb Maj,Bb} Beat_142={52.172363636363691,0,Eb Maj,Bb} Beat_143={52.536000000000058,0,Eb Maj,Bb} Beat_144={52.899636363636425,1,Eb Maj,Fsus4} Beat_145={53.263272727272785,0,Eb Maj,Fsus4,0.5,F} Beat_146={53.626909090909152,0,Eb Maj,F} Beat_147={53.990545454545511,0,Eb Maj,F} Beat_148={54.354181818181878,1,Bb Maj,Bb} Beat_149={54.717818181818245,0,Bb Maj,Bb} Beat_150={55.081454545454605,0,Bb Maj,Bb} Beat_151={55.445090909090972,0,Bb Maj,Bb} Beat_152={55.808727272727332,1,Bb Maj,F/A} Beat_153={56.1723636363637,0,Bb Maj,F/A} Beat_154={56.536000000000065,0,Bb Maj,D} Beat_155={56.899636363636425,0,Bb Maj,D} Beat_156={57.263272727272792,1,Bb Maj,Gm7} Beat_157={57.626909090909152,0,Bb Maj,Gm7} Beat_158={57.990545454545519,0,Bb Maj,Gm7} Beat_159={58.354181818181885,0,Bb Maj,Gm7} Beat_160={58.717818181818245,1,Bb Maj,Fm} Beat_161={59.081454545454612,0,Bb Maj,Fm} Beat_162={59.445090909090972,0,Bb Maj,Bb} Beat_163={59.808727272727339,0,Bb Maj,Bb} Beat_164={60.172363636363706,1,Bb Maj,Eb} Beat_165={60.536000000000065,0,Bb Maj,Eb} Beat_166={60.899636363636432,0,Bb Maj,Eb} Beat_167={61.263272727272792,0,Bb Maj,Eb} Beat_168={61.626909090909159,1,Bb Maj,Bb/D} Beat_169={61.990545454545526,0,Bb Maj,Bb/D} Beat_170={62.354181818181885,0,Bb Maj,Bb/D} Beat_171={62.717818181818252,0,Bb Maj,Bb/D} Beat_172={63.081454545454612,1,Bb Maj,Cm7} Beat_173={63.445090909090979,0,Bb Maj,Cm7} Beat_174={63.808727272727346,0,Bb Maj,Cm7} Beat_175={64.1723636363637,0,Bb Maj,Cm7} Beat_176={64.536000000000072,1,Bb Maj,F} Beat_177={64.899636363636432,0,Bb Maj,F} Beat_178={65.2632727272728,0,Bb Maj,F} Beat_179={65.626909090909166,0,Bb Maj,F} Beat_180={65.990545454545526,1,Bb Maj,Bb} Beat_181={66.354181818181885,0,Bb Maj,Bb} Beat_182={66.717818181818259,0,Bb Maj,Bb} Beat_183={67.081454545454619,0,Bb Maj,Bb} Beat_184={67.445090909090979,1,Bb Maj,F/A} Beat_185={67.808727272727353,0,Bb Maj,F/A} Beat_186={68.172363636363713,0,Bb Maj,D} Beat_187={68.536000000000072,0,Bb Maj,D} Beat_188={68.899636363636446,1,Bb Maj,Gm7} Beat_189={69.2632727272728,0,Bb Maj,Gm7} Beat_190={69.626909090909166,0,Bb Maj,Gm7} Beat_191={69.990545454545526,0,Bb Maj,Gm7} Beat_192={70.3541818181819,1,Bb Maj,Fm} Beat_193={70.717818181818259,0,Bb Maj,Fm} Beat_194={71.081454545454619,0,Bb Maj,Bb} Beat_195={71.445090909091,0,Bb Maj,Bb} Beat_196={71.808727272727353,1,Bb Maj,Eb} Beat_197={72.172363636363713,0,Bb Maj,Eb} Beat_198={72.536000000000087,0,Bb Maj,Eb} Beat_199={72.899636363636446,0,Bb Maj,Eb} Beat_200={73.2632727272728,1,Bb Maj,Bb/D} Beat_201={73.626909090909166,0,Bb Maj,Bb/D} Beat_202={73.99054545454554,0,Bb Maj,Bb/D} Beat_203={74.3541818181819,0,Bb Maj,Bb/D} Beat_204={74.717818181818259,1,Bb Maj,Cm7} Beat_205={75.081454545454633,0,Bb Maj,Cm7} Beat_206={75.445090909091,0,Bb Maj,Cm7} Beat_207={75.808727272727353,0,Bb Maj,Cm7} Beat_208={76.172363636363727,1,Bb Maj,F} Beat_209={76.536000000000087,0,Bb Maj,F} Beat_210={76.899636363636446,0,Bb Maj,F} Beat_211={77.2632727272728,0,Bb Maj,F} Beat_212={77.62690909090918,1,Bb Maj,Eb} Beat_213={77.99054545454554,0,Bb Maj,Eb} Beat_214={78.3541818181819,0,Bb Maj,Eb} Beat_215={78.717818181818274,0,Bb Maj,Eb} Beat_216={79.081454545454633,1,Bb Maj,F} Beat_217={79.445090909091,0,Bb Maj,F} Beat_218={79.808727272727367,0,Bb Maj,F} Beat_219={80.172363636363727,0,Bb Maj,F} Beat_220={80.536000000000087,1,Bb Maj,Bb} Beat_221={80.899636363636446,0,Bb Maj,Bb} Beat_222={81.26327272727282,0,Bb Maj,Bb} Beat_223={81.62690909090918,0,Bb Maj,Bb} Beat_224={81.99054545454554,1,Bb Maj,Gm7} Beat_225={82.354181818181914,0,Bb Maj,Gm7} Beat_226={82.717818181818274,0,Bb Maj,Gm7} Beat_227={83.081454545454633,0,Bb Maj,Gm7} Beat_228={83.445090909091007,1,Bb Maj,Eb} Beat_229={83.808727272727367,0,Bb Maj,Eb} Beat_230={84.172363636363727,0,Bb Maj,Eb} Beat_231={84.536000000000087,0,Bb Maj,Eb} Beat_232={84.899636363636461,1,Bb Maj,F} Beat_233={85.26327272727282,0,Bb Maj,F} Beat_234={85.62690909090918,0,Bb Maj,F} Beat_235={85.990545454545554,0,Bb Maj,F} Beat_236={86.354181818181914,1,Bb Maj,Bb} Beat_237={86.717818181818274,0,Bb Maj,Bb} Beat_238={87.081454545454648,0,Bb Maj,Bb} Beat_239={87.445090909091007,0,Bb Maj,Bb} Beat_240={87.808727272727367,1,Bb Maj,Bb} Beat_241={88.172363636363727,0,Bb Maj,Bb} Beat_242={88.5360000000001,0,Bb Maj,Bb} Beat_243={88.899636363636461,0,Bb Maj,Bb} Beat_244={89.26327272727282,1,Bb Maj,N} Beat_245={89.6269090909092,0,Eb Maj,N} ",7979,True,2827.3889692611215,median " SUMMARY OF PM7 CALCULATION, Site No: 31305 MOPAC2016 (Version: 18.305L) Sat Apr 6 17:27:17 2019 No. of days remaining = 209 Empirical Formula: C51 H78 O39 = 168 atoms AUX LARGE CHARGE=0 SINGLET PM7 Title HERBERTS TEST WAS SATISFIED IN BFGS SCF FIELD WAS ACHIEVED HEAT OF FORMATION = -1762.39113 KCAL/MOL = -7373.84450 KJ/MOL TOTAL ENERGY = -18834.52796 EV ELECTRONIC ENERGY = -333152.69604 EV CORE-CORE REPULSION = 314318.16809 EV GRADIENT NORM = 0.98455 = 0.07596 PER ATOM DIPOLE = 10.27747 DEBYE POINT GROUP: C1 NO. OF FILLED LEVELS = 258 IONIZATION POTENTIAL = 9.784081 EV HOMO LUMO ENERGIES (EV) = -9.784 -0.686 MOLECULAR WEIGHT = 1315.1538 COSMO AREA = 743.28 SQUARE ANGSTROMS COSMO VOLUME = 1356.07 CUBIC ANGSTROMS MOLECULAR DIMENSIONS (Angstroms) Atom Atom Distance H 98 H 39 15.19435 H 143 H 56 13.82444 H 145 H 103 9.16974 SCF CALCULATIONS = 927 WALL-CLOCK TIME = 10 MINUTES AND 30.445 SECONDS COMPUTATION TIME = 10 MINUTES AND 59.156 SECONDS FINAL GEOMETRY OBTAINED AUX LARGE CHARGE=0 SINGLET PM7 Title H -32.79219823 +1 -31.15855811 +1 -12.18234815 +1 C -22.07444629 +1 -26.32031269 +1 -10.99788829 +1 C -22.15823105 +1 -26.69849710 +1 -9.49868884 +1 C -23.47965026 +1 -27.43296874 +1 -9.24640622 +1 C -24.65856998 +1 -26.54843888 +1 -9.70690115 +1 C -24.45657654 +1 -26.18760628 +1 -11.19563037 +1 C -25.40772359 +1 -25.09286228 +1 -11.71556857 +1 O -21.06422665 +1 -27.55494053 +1 -9.22394834 +1 O -23.53189433 +1 -27.61404510 +1 -7.85104514 +1 O -25.82746773 +1 -27.35763187 +1 -9.62580713 +1 O -23.19123577 +1 -25.54221608 +1 -11.32086624 +1 O -26.74874232 +1 -25.49549009 +1 -11.61704097 +1 H -21.20784166 +1 -25.67804626 +1 -11.26864495 +1 H -22.05106995 +1 -25.80095609 +1 -8.84930277 +1 H -23.50312003 +1 -28.42796941 +1 -9.74902083 +1 H -24.75598800 +1 -25.63997360 +1 -9.07753326 +1 H -24.49685709 +1 -27.09874590 +1 -11.83505780 +1 H -25.26991901 +1 -24.13897561 +1 -11.17743066 +1 H -25.26073393 +1 -24.93023905 +1 -12.80467853 +1 H -21.17893462 +1 -27.92150790 +1 -8.31058732 +1 H -24.23577313 +1 -28.27158224 +1 -7.63561449 +1 H -26.95189317 +1 -25.79852501 +1 -10.70505806 +1 C -20.03449291 +1 -29.80778287 +1 -14.31273863 +1 C -19.95028078 +1 -30.24193884 +1 -12.83162809 +1 C -21.02935363 +1 -29.50498749 +1 -12.02782615 +1 C -20.94243158 +1 -27.98173286 +1 -12.29470225 +1 C -20.93812907 +1 -27.68142272 +1 -13.80667767 +1 C -20.57788550 +1 -26.22858387 +1 -14.16432936 +1 O -20.16335591 +1 -31.64163043 +1 -12.82970821 +1 O -20.77106849 +1 -29.79703877 +1 -10.67737917 +1 O -22.15991806 +1 -27.51207760 +1 -11.74803814 +1 O -19.87644381 +1 -28.42388540 +1 -14.40697128 +1 O -21.37882178 +1 -25.32779464 +1 -13.44325000 +1 H -19.23713312 +1 -30.22692813 +1 -14.95645527 +1 H -18.93310303 +1 -30.06815453 +1 -12.41328148 +1 H -22.05027130 +1 -29.89685503 +1 -12.24741447 +1 H -20.06071509 +1 -27.54002255 +1 -11.78384660 +1 H -21.91298144 +1 -27.96175250 +1 -14.27256732 +1 H -19.54656974 +1 -25.96452977 +1 -13.87211027 +1 H -20.71437954 +1 -26.05590823 +1 -15.25123679 +1 H -20.46911852 +1 -31.92697058 +1 -11.93694772 +1 H -20.94059938 +1 -28.99771552 +1 -10.11244121 +1 H -22.33754349 +1 -25.54917917 +1 -13.54691066 +1 C -23.26666474 +1 -31.96299669 +1 -17.87575991 +1 C -22.26671894 +1 -32.80500917 +1 -17.05239047 +1 C -22.05144401 +1 -32.12981571 +1 -15.69607346 +1 C -21.46233121 +1 -30.73411010 +1 -15.98947744 +1 C -22.47647499 +1 -29.91185488 +1 -16.79821219 +1 C -21.88965795 +1 -28.59991909 +1 -17.35949135 +1 O -22.80378255 +1 -34.10007461 +1 -16.91363108 +1 O -21.12620463 +1 -32.92014519 +1 -14.99971795 +1 O -21.34464265 +1 -30.14513482 +1 -14.71517052 +1 O -22.84723889 +1 -30.62389984 +1 -17.98633745 +1 O -22.29516554 +1 -27.49885256 +1 -16.59659052 +1 H -23.33579728 +1 -32.28529619 +1 -18.93871845 +1 H -21.30652562 +1 -32.93311872 +1 -17.60921936 +1 H -22.98831596 +1 -32.07206467 +1 -15.09415228 +1 H -20.48399825 +1 -30.81071545 +1 -16.51022854 +1 H -23.39546531 +1 -29.72466145 +1 -16.19627836 +1 H -20.78627743 +1 -28.56314557 +1 -17.28320181 +1 H -22.19097758 +1 -28.45436332 +1 -18.41669697 +1 H -22.47510856 +1 -34.50294784 +1 -16.07080192 +1 H -20.79811382 +1 -32.44230610 +1 -14.19208243 +1 H -23.27586717 +1 -27.40810206 +1 -16.56564366 +1 C -28.46828635 +1 -32.78565438 +1 -18.10156933 +1 C -27.48854413 +1 -33.97313228 +1 -18.05732754 +1 C -26.20888907 +1 -33.56720690 +1 -17.31233121 +1 C -25.62665558 +1 -32.30980672 +1 -17.99683537 +1 C -26.67847890 +1 -31.18347081 +1 -17.92254429 +1 C -26.32201183 +1 -29.90853654 +1 -18.70983768 +1 O -28.15375551 +1 -35.02457803 +1 -17.38664847 +1 O -25.36526339 +1 -34.67598371 +1 -17.46176666 +1 O -24.50541117 +1 -31.95234151 +1 -17.20548487 +1 O -27.84282213 +1 -31.63836386 +1 -18.62239778 +1 O -25.18515720 +1 -29.28734441 +1 -18.17695815 +1 H -29.32707535 +1 -32.94152847 +1 -18.79004020 +1 H -27.25716936 +1 -34.34250227 +1 -19.08518265 +1 H -26.38147065 +1 -33.39697583 +1 -16.22476769 +1 H -25.34170194 +1 -32.52380186 +1 -19.04907386 +1 H -26.94102442 +1 -30.94221460 +1 -16.86687629 +1 H -26.15264685 +1 -30.11489501 +1 -19.78151064 +1 H -27.12018478 +1 -29.13813783 +1 -18.60084766 +1 H -27.48154711 +1 -35.69670762 +1 -17.10819163 +1 H -24.43203463 +1 -34.45091828 +1 -17.21423553 +1 H -24.39601092 +1 -29.86807808 +1 -18.17883805 +1 C -32.10058856 +1 -31.80256257 +1 -14.45681026 +1 C -31.78578333 +1 -33.28198792 +1 -14.75695758 +1 C -30.34444047 +1 -33.37646082 +1 -15.26560515 +1 C -30.22444500 +1 -32.48030507 +1 -16.51496802 +1 C -30.63636060 +1 -31.02684301 +1 -16.22444238 +1 C -30.89120390 +1 -30.21495488 +1 -17.51416715 +1 O -31.93816249 +1 -33.97886050 +1 -13.53554563 +1 O -30.14974042 +1 -34.72399849 +1 -15.60520412 +1 O -28.83255723 +1 -32.49281168 +1 -16.77848092 +1 O -31.91874007 +1 -30.99400523 +1 -15.59046039 +1 O -29.69623130 +1 -29.75003585 +1 -18.07259748 +1 H -33.16022003 +1 -31.61591049 +1 -14.17968709 +1 H -32.51377858 +1 -33.71957698 +1 -15.47801893 +1 H -29.59940003 +1 -33.10650329 +1 -14.48173200 +1 H -30.81156881 +1 -32.91285476 +1 -17.35476384 +1 H -29.89155660 +1 -30.51354348 +1 -15.57202130 +1 H -31.45505391 +1 -30.79292883 +1 -18.26529804 +1 H -31.44416100 +1 -29.27781323 +1 -17.28150778 +1 H -31.52597942 +1 -34.87542486 +1 -13.63295293 +1 H -29.36573812 +1 -34.82493914 +1 -16.20310638 +1 H -29.04776538 +1 -30.46230352 +1 -18.22046044 +1 C -31.07510479 +1 -29.51316273 +1 -9.85006982 +1 C -31.28634593 +1 -31.04502762 +1 -9.83434727 +1 C -30.89154714 +1 -31.63118980 +1 -11.19712855 +1 C -31.71410526 +1 -30.90605169 +1 -12.28046007 +1 C -31.47200948 +1 -29.38903338 +1 -12.21039502 +1 C -32.41898936 +1 -28.58715285 +1 -13.12576696 +1 O -30.46475769 +1 -31.55798464 +1 -8.80699570 +1 O -31.23252584 +1 -32.99097502 +1 -11.13274457 +1 O -31.16578997 +1 -31.37897066 +1 -13.49516175 +1 O -31.81135288 +1 -28.94027235 +1 -10.90015090 +1 O -31.90152063 +1 -28.55031151 +1 -14.42635343 +1 H -31.46398215 +1 -28.99700711 +1 -8.94794862 +1 H -32.33900733 +1 -31.30049281 +1 -9.56849070 +1 H -29.79573108 +1 -31.56373732 +1 -11.38803043 +1 H -30.40838845 +1 -29.14125474 +1 -12.43415673 +1 H -33.44552631 +1 -28.98736584 +1 -13.12813344 +1 H -32.44812213 +1 -27.51788625 +1 -12.82616046 +1 H -30.37412028 +1 -32.53789661 +1 -8.92757841 +1 H -31.39900171 +1 -33.35973705 +1 -12.03692083 +1 H -31.87548546 +1 -29.43634231 +1 -14.83681130 +1 C -26.53521976 +1 -27.24260237 +1 -8.41506033 +1 C -26.83921140 +1 -28.66285911 +1 -7.87872783 +1 C -27.71470396 +1 -29.41999773 +1 -8.88922050 +1 C -29.00289448 +1 -28.59203452 +1 -9.08626633 +1 C -28.62313440 +1 -27.19446249 +1 -9.60935525 +1 C -29.80642432 +1 -26.21240870 +1 -9.68205837 +1 O -25.60904016 +1 -29.30564134 +1 -7.64816117 +1 O -27.98121235 +1 -30.66372384 +1 -8.29847004 +1 O -29.71153589 +1 -29.27120870 +1 -10.10779526 +1 O -27.74366130 +1 -26.57297762 +1 -8.67990811 +1 O -30.39995522 +1 -26.28342109 +1 -10.95387692 +1 H -26.04045644 +1 -26.58504000 +1 -7.66626865 +1 H -27.33383878 +1 -28.60473621 +1 -6.87865219 +1 H -27.18951210 +1 -29.61220884 +1 -9.85299186 +1 H -29.58535879 +1 -28.54117297 +1 -8.14215879 +1 H -28.12608491 +1 -27.27725308 +1 -10.60821828 +1 H -30.55986584 +1 -26.38851405 +1 -8.89832338 +1 H -29.45246115 +1 -25.16193449 +1 -9.61777794 +1 H -25.66421623 +1 -30.25906368 +1 -7.88962002 +1 H -28.86427419 +1 -31.00951220 +1 -8.58333534 +1 H -30.78898615 +1 -27.17669700 +1 -11.09552630 +1 O -27.58998941 +1 -28.88253769 +1 -15.42114056 +1 H -28.18745705 +1 -31.23369689 +1 -14.52147842 +1 C -26.74350206 +1 -29.63780102 +1 -14.68090824 +1 C -27.16973489 +1 -30.91582244 +1 -14.30389681 +1 H -25.26542655 +1 -28.27988140 +1 -16.77660604 +1 O -24.94511162 +1 -27.57100112 +1 -16.13699128 +1 O -28.72278120 +1 -27.05061638 +1 -15.72504751 +1 C -26.26760360 +1 -31.76095835 +1 -13.66938195 +1 C -28.20248616 +1 -27.72562481 +1 -14.89354979 +1 C -25.44068107 +1 -29.20164081 +1 -14.42948968 +1 C -24.97379885 +1 -27.85723199 +1 -14.81591926 +1 H -26.58019570 +1 -32.76326157 +1 -13.37474983 +1 C -24.96439964 +1 -31.33273734 +1 -13.39825148 +1 C -24.55419019 +1 -30.05791723 +1 -13.77284846 +1 O -24.58339047 +1 -27.00686072 +1 -14.05954033 +1 H -24.27193268 +1 -31.99783605 +1 -12.88619424 +1 H -23.53644830 +1 -29.71841829 +1 -13.55254655 +1 C -28.11813793 +1 -27.54471054 +1 -13.43121488 +1 H -28.21986958 +1 -28.47702093 +1 -12.86254416 +1 H -28.89678160 +1 -26.84086310 +1 -13.06956497 +1 H -27.15651388 +1 -27.07069503 +1 -13.13138831 +1 ",8331,True,2793.1414753129993,median "// Automatically generated by 'openshift-apidocs-gen'. Do not edit. :_content-type: ASSEMBLY [id=""node-v1""] = Node [v1] ifdef::product-title[] include::_attributes/common-attributes.adoc[] endif::[] toc::[] Description:: + -- Node is a worker node in Kubernetes. Each node will have a unique identifier in the cache (i.e. in etcd). -- Type:: `object` == Specification [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `apiVersion` | `string` | APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources | `kind` | `string` | Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds | `metadata` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta[`ObjectMeta`] | Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata | `spec` | `object` | NodeSpec describes the attributes that a node is created with. | `status` | `object` | NodeStatus is information about the current status of a node. |=== === .spec Description:: + -- NodeSpec describes the attributes that a node is created with. -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `configSource` | `object` | NodeConfigSource specifies a source of node configuration. Exactly one subfield (excluding metadata) must be non-nil. This API is deprecated since 1.22 | `externalID` | `string` | Deprecated. Not all kubelets will set this field. Remove field after 1.13. see: https://issues.k8s.io/61966 | `podCIDR` | `string` | PodCIDR represents the pod IP range assigned to the node. | `podCIDRs` | `array (string)` | podCIDRs represents the IP ranges assigned to the node for usage by Pods on that node. If this field is specified, the 0th entry must match the podCIDR field. It may contain at most 1 value for each of IPv4 and IPv6. | `providerID` | `string` | ID of the node assigned by the cloud provider in the format: :// | `taints` | `array` | If specified, the node's taints. | `taints[]` | `object` | The node this Taint is attached to has the ""effect"" on any pod that does not tolerate the Taint. | `unschedulable` | `boolean` | Unschedulable controls node schedulability of new pods. By default, node is schedulable. More info: https://kubernetes.io/docs/concepts/nodes/node/#manual-node-administration |=== === .spec.configSource Description:: + -- NodeConfigSource specifies a source of node configuration. Exactly one subfield (excluding metadata) must be non-nil. This API is deprecated since 1.22 -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `configMap` | `object` | ConfigMapNodeConfigSource contains the information to reference a ConfigMap as a config source for the Node. This API is deprecated since 1.22: https://git.k8s.io/enhancements/keps/sig-node/281-dynamic-kubelet-configuration |=== === .spec.configSource.configMap Description:: + -- ConfigMapNodeConfigSource contains the information to reference a ConfigMap as a config source for the Node. This API is deprecated since 1.22: https://git.k8s.io/enhancements/keps/sig-node/281-dynamic-kubelet-configuration -- Type:: `object` Required:: - `namespace` - `name` - `kubeletConfigKey` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `kubeletConfigKey` | `string` | KubeletConfigKey declares which key of the referenced ConfigMap corresponds to the KubeletConfiguration structure This field is required in all cases. | `name` | `string` | Name is the metadata.name of the referenced ConfigMap. This field is required in all cases. | `namespace` | `string` | Namespace is the metadata.namespace of the referenced ConfigMap. This field is required in all cases. | `resourceVersion` | `string` | ResourceVersion is the metadata.ResourceVersion of the referenced ConfigMap. This field is forbidden in Node.Spec, and required in Node.Status. | `uid` | `string` | UID is the metadata.UID of the referenced ConfigMap. This field is forbidden in Node.Spec, and required in Node.Status. |=== === .spec.taints Description:: + -- If specified, the node's taints. -- Type:: `array` === .spec.taints[] Description:: + -- The node this Taint is attached to has the ""effect"" on any pod that does not tolerate the Taint. -- Type:: `object` Required:: - `key` - `effect` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `effect` | `string` | Required. The effect of the taint on pods that do not tolerate the taint. Valid effects are NoSchedule, PreferNoSchedule and NoExecute. | `key` | `string` | Required. The taint key to be applied to a node. | `timeAdded` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Time[`Time`] | TimeAdded represents the time at which the taint was added. It is only written for NoExecute taints. | `value` | `string` | The taint value corresponding to the taint key. |=== === .status Description:: + -- NodeStatus is information about the current status of a node. -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `addresses` | `array` | List of addresses reachable to the node. Queried from cloud provider, if available. More info: https://kubernetes.io/docs/concepts/nodes/node/#addresses Note: This field is declared as mergeable, but the merge key is not sufficiently unique, which can cause data corruption when it is merged. Callers should instead use a full-replacement patch. See http://pr.k8s.io/79391 for an example. | `addresses[]` | `object` | NodeAddress contains information for the node's address. | `allocatable` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.api.resource.Quantity[`object (Quantity)`] | Allocatable represents the resources of a node that are available for scheduling. Defaults to Capacity. | `capacity` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.api.resource.Quantity[`object (Quantity)`] | Capacity represents the total resources of a node. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#capacity | `conditions` | `array` | Conditions is an array of current observed node conditions. More info: https://kubernetes.io/docs/concepts/nodes/node/#condition | `conditions[]` | `object` | NodeCondition contains condition information for a node. | `config` | `object` | NodeConfigStatus describes the status of the config assigned by Node.Spec.ConfigSource. | `daemonEndpoints` | `object` | NodeDaemonEndpoints lists ports opened by daemons running on the Node. | `images` | `array` | List of container images on this node | `images[]` | `object` | Describe a container image | `nodeInfo` | `object` | NodeSystemInfo is a set of ids/uuids to uniquely identify the node. | `phase` | `string` | NodePhase is the recently observed lifecycle phase of the node. More info: https://kubernetes.io/docs/concepts/nodes/node/#phase The field is never populated, and now is deprecated. | `volumesAttached` | `array` | List of volumes that are attached to the node. | `volumesAttached[]` | `object` | AttachedVolume describes a volume attached to a node | `volumesInUse` | `array (string)` | List of attachable volumes in use (mounted) by the node. |=== === .status.addresses Description:: + -- List of addresses reachable to the node. Queried from cloud provider, if available. More info: https://kubernetes.io/docs/concepts/nodes/node/#addresses Note: This field is declared as mergeable, but the merge key is not sufficiently unique, which can cause data corruption when it is merged. Callers should instead use a full-replacement patch. See http://pr.k8s.io/79391 for an example. -- Type:: `array` === .status.addresses[] Description:: + -- NodeAddress contains information for the node's address. -- Type:: `object` Required:: - `type` - `address` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `address` | `string` | The node address. | `type` | `string` | Node address type, one of Hostname, ExternalIP or InternalIP. |=== === .status.conditions Description:: + -- Conditions is an array of current observed node conditions. More info: https://kubernetes.io/docs/concepts/nodes/node/#condition -- Type:: `array` === .status.conditions[] Description:: + -- NodeCondition contains condition information for a node. -- Type:: `object` Required:: - `type` - `status` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `lastHeartbeatTime` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Time[`Time`] | Last time we got an update on a given condition. | `lastTransitionTime` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Time[`Time`] | Last time the condition transit from one status to another. | `message` | `string` | Human readable message indicating details about last transition. | `reason` | `string` | (brief) reason for the condition's last transition. | `status` | `string` | Status of the condition, one of True, False, Unknown. | `type` | `string` | Type of node condition. |=== === .status.config Description:: + -- NodeConfigStatus describes the status of the config assigned by Node.Spec.ConfigSource. -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `active` | `object` | NodeConfigSource specifies a source of node configuration. Exactly one subfield (excluding metadata) must be non-nil. This API is deprecated since 1.22 | `assigned` | `object` | NodeConfigSource specifies a source of node configuration. Exactly one subfield (excluding metadata) must be non-nil. This API is deprecated since 1.22 | `error` | `string` | Error describes any problems reconciling the Spec.ConfigSource to the Active config. Errors may occur, for example, attempting to checkpoint Spec.ConfigSource to the local Assigned record, attempting to checkpoint the payload associated with Spec.ConfigSource, attempting to load or validate the Assigned config, etc. Errors may occur at different points while syncing config. Earlier errors (e.g. download or checkpointing errors) will not result in a rollback to LastKnownGood, and may resolve across Kubelet retries. Later errors (e.g. loading or validating a checkpointed config) will result in a rollback to LastKnownGood. In the latter case, it is usually possible to resolve the error by fixing the config assigned in Spec.ConfigSource. You can find additional information for debugging by searching the error message in the Kubelet log. Error is a human-readable description of the error state; machines can check whether or not Error is empty, but should not rely on the stability of the Error text across Kubelet versions. | `lastKnownGood` | `object` | NodeConfigSource specifies a source of node configuration. Exactly one subfield (excluding metadata) must be non-nil. This API is deprecated since 1.22 |=== === .status.config.active Description:: + -- NodeConfigSource specifies a source of node configuration. Exactly one subfield (excluding metadata) must be non-nil. This API is deprecated since 1.22 -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `configMap` | `object` | ConfigMapNodeConfigSource contains the information to reference a ConfigMap as a config source for the Node. This API is deprecated since 1.22: https://git.k8s.io/enhancements/keps/sig-node/281-dynamic-kubelet-configuration |=== === .status.config.active.configMap Description:: + -- ConfigMapNodeConfigSource contains the information to reference a ConfigMap as a config source for the Node. This API is deprecated since 1.22: https://git.k8s.io/enhancements/keps/sig-node/281-dynamic-kubelet-configuration -- Type:: `object` Required:: - `namespace` - `name` - `kubeletConfigKey` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `kubeletConfigKey` | `string` | KubeletConfigKey declares which key of the referenced ConfigMap corresponds to the KubeletConfiguration structure This field is required in all cases. | `name` | `string` | Name is the metadata.name of the referenced ConfigMap. This field is required in all cases. | `namespace` | `string` | Namespace is the metadata.namespace of the referenced ConfigMap. This field is required in all cases. | `resourceVersion` | `string` | ResourceVersion is the metadata.ResourceVersion of the referenced ConfigMap. This field is forbidden in Node.Spec, and required in Node.Status. | `uid` | `string` | UID is the metadata.UID of the referenced ConfigMap. This field is forbidden in Node.Spec, and required in Node.Status. |=== === .status.config.assigned Description:: + -- NodeConfigSource specifies a source of node configuration. Exactly one subfield (excluding metadata) must be non-nil. This API is deprecated since 1.22 -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `configMap` | `object` | ConfigMapNodeConfigSource contains the information to reference a ConfigMap as a config source for the Node. This API is deprecated since 1.22: https://git.k8s.io/enhancements/keps/sig-node/281-dynamic-kubelet-configuration |=== === .status.config.assigned.configMap Description:: + -- ConfigMapNodeConfigSource contains the information to reference a ConfigMap as a config source for the Node. This API is deprecated since 1.22: https://git.k8s.io/enhancements/keps/sig-node/281-dynamic-kubelet-configuration -- Type:: `object` Required:: - `namespace` - `name` - `kubeletConfigKey` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `kubeletConfigKey` | `string` | KubeletConfigKey declares which key of the referenced ConfigMap corresponds to the KubeletConfiguration structure This field is required in all cases. | `name` | `string` | Name is the metadata.name of the referenced ConfigMap. This field is required in all cases. | `namespace` | `string` | Namespace is the metadata.namespace of the referenced ConfigMap. This field is required in all cases. | `resourceVersion` | `string` | ResourceVersion is the metadata.ResourceVersion of the referenced ConfigMap. This field is forbidden in Node.Spec, and required in Node.Status. | `uid` | `string` | UID is the metadata.UID of the referenced ConfigMap. This field is forbidden in Node.Spec, and required in Node.Status. |=== === .status.config.lastKnownGood Description:: + -- NodeConfigSource specifies a source of node configuration. Exactly one subfield (excluding metadata) must be non-nil. This API is deprecated since 1.22 -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `configMap` | `object` | ConfigMapNodeConfigSource contains the information to reference a ConfigMap as a config source for the Node. This API is deprecated since 1.22: https://git.k8s.io/enhancements/keps/sig-node/281-dynamic-kubelet-configuration |=== === .status.config.lastKnownGood.configMap Description:: + -- ConfigMapNodeConfigSource contains the information to reference a ConfigMap as a config source for the Node. This API is deprecated since 1.22: https://git.k8s.io/enhancements/keps/sig-node/281-dynamic-kubelet-configuration -- Type:: `object` Required:: - `namespace` - `name` - `kubeletConfigKey` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `kubeletConfigKey` | `string` | KubeletConfigKey declares which key of the referenced ConfigMap corresponds to the KubeletConfiguration structure This field is required in all cases. | `name` | `string` | Name is the metadata.name of the referenced ConfigMap. This field is required in all cases. | `namespace` | `string` | Namespace is the metadata.namespace of the referenced ConfigMap. This field is required in all cases. | `resourceVersion` | `string` | ResourceVersion is the metadata.ResourceVersion of the referenced ConfigMap. This field is forbidden in Node.Spec, and required in Node.Status. | `uid` | `string` | UID is the metadata.UID of the referenced ConfigMap. This field is forbidden in Node.Spec, and required in Node.Status. |=== === .status.daemonEndpoints Description:: + -- NodeDaemonEndpoints lists ports opened by daemons running on the Node. -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `kubeletEndpoint` | `object` | DaemonEndpoint contains information about a single Daemon endpoint. |=== === .status.daemonEndpoints.kubeletEndpoint Description:: + -- DaemonEndpoint contains information about a single Daemon endpoint. -- Type:: `object` Required:: - `Port` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `Port` | `integer` | Port number of the given endpoint. |=== === .status.images Description:: + -- List of container images on this node -- Type:: `array` === .status.images[] Description:: + -- Describe a container image -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `names` | `array (string)` | Names by which this image is known. e.g. [""k8s.gcr.io/hyperkube:v1.0.7"", ""dockerhub.io/google_containers/hyperkube:v1.0.7""] | `sizeBytes` | `integer` | The size of the image in bytes. |=== === .status.nodeInfo Description:: + -- NodeSystemInfo is a set of ids/uuids to uniquely identify the node. -- Type:: `object` Required:: - `machineID` - `systemUUID` - `bootID` - `kernelVersion` - `osImage` - `containerRuntimeVersion` - `kubeletVersion` - `kubeProxyVersion` - `operatingSystem` - `architecture` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `architecture` | `string` | The Architecture reported by the node | `bootID` | `string` | Boot ID reported by the node. | `containerRuntimeVersion` | `string` | ContainerRuntime Version reported by the node through runtime remote API (e.g. docker://1.5.0). | `kernelVersion` | `string` | Kernel Version reported by the node from 'uname -r' (e.g. 3.16.0-0.bpo.4-amd64). | `kubeProxyVersion` | `string` | KubeProxy Version reported by the node. | `kubeletVersion` | `string` | Kubelet Version reported by the node. | `machineID` | `string` | MachineID reported by the node. For unique machine identification in the cluster this field is preferred. Learn more from man(5) machine-id: http://man7.org/linux/man-pages/man5/machine-id.5.html | `operatingSystem` | `string` | The Operating System reported by the node | `osImage` | `string` | OS Image reported by the node from /etc/os-release (e.g. Debian GNU/Linux 7 (wheezy)). | `systemUUID` | `string` | SystemUUID reported by the node. For unique machine identification MachineID is preferred. This field is specific to Red Hat hosts https://access.redhat.com/documentation/en-us/red_hat_subscription_management/1/html/rhsm/uuid |=== === .status.volumesAttached Description:: + -- List of volumes that are attached to the node. -- Type:: `array` === .status.volumesAttached[] Description:: + -- AttachedVolume describes a volume attached to a node -- Type:: `object` Required:: - `name` - `devicePath` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `devicePath` | `string` | DevicePath represents the device path where the volume should be available | `name` | `string` | Name of the attached volume |=== == API endpoints The following API endpoints are available: * `/api/v1/nodes` - `DELETE`: delete collection of Node - `GET`: list or watch objects of kind Node - `POST`: create a Node * `/api/v1/watch/nodes` - `GET`: watch individual changes to a list of Node. deprecated: use the 'watch' parameter with a list operation instead. * `/api/v1/nodes/{name}` - `DELETE`: delete a Node - `GET`: read the specified Node - `PATCH`: partially update the specified Node - `PUT`: replace the specified Node * `/api/v1/watch/nodes/{name}` - `GET`: watch changes to an object of kind Node. deprecated: use the 'watch' parameter with a list operation instead, filtered to a single item with the 'fieldSelector' parameter. * `/api/v1/nodes/{name}/status` - `GET`: read status of the specified Node - `PATCH`: partially update status of the specified Node - `PUT`: replace status of the specified Node === /api/v1/nodes .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `DELETE` Description:: delete collection of Node .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `continue` | `string` | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `gracePeriodSeconds` | `integer` | The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. | `orphanDependents` | `boolean` | Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. | `propagationPolicy` | `string` | Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.DeleteOptions[`DeleteOptions`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Status[`Status`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `GET` Description:: list or watch objects of kind Node .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `allowWatchBookmarks` | `boolean` | allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. | `continue` | `string` | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. | `watch` | `boolean` | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.k8s.api.core.v1.NodeList[`NodeList`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `POST` Description:: create a Node .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../node_apis/node-v1.adoc#node-v1[`Node`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../node_apis/node-v1.adoc#node-v1[`Node`] schema | 201 - Created | xref:../node_apis/node-v1.adoc#node-v1[`Node`] schema | 202 - Accepted | xref:../node_apis/node-v1.adoc#node-v1[`Node`] schema | 401 - Unauthorized | Empty |=== === /api/v1/watch/nodes .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `allowWatchBookmarks` | `boolean` | allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. | `continue` | `string` | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. | `pretty` | `string` | If 'true', then the output is pretty printed. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. | `watch` | `boolean` | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== HTTP method:: `GET` Description:: watch individual changes to a list of Node. deprecated: use the 'watch' parameter with a list operation instead. .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.WatchEvent[`WatchEvent`] schema | 401 - Unauthorized | Empty |=== === /api/v1/nodes/{name} .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the Node |=== .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `DELETE` Description:: delete a Node .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `gracePeriodSeconds` | `integer` | The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. | `orphanDependents` | `boolean` | Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. | `propagationPolicy` | `string` | Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.DeleteOptions[`DeleteOptions`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Status[`Status`] schema | 202 - Accepted | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Status[`Status`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `GET` Description:: read the specified Node .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../node_apis/node-v1.adoc#node-v1[`Node`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `PATCH` Description:: partially update the specified Node .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). | `force` | `boolean` | Force is going to "force" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Patch[`Patch`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../node_apis/node-v1.adoc#node-v1[`Node`] schema | 201 - Created | xref:../node_apis/node-v1.adoc#node-v1[`Node`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `PUT` Description:: replace the specified Node .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../node_apis/node-v1.adoc#node-v1[`Node`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../node_apis/node-v1.adoc#node-v1[`Node`] schema | 201 - Created | xref:../node_apis/node-v1.adoc#node-v1[`Node`] schema | 401 - Unauthorized | Empty |=== === /api/v1/watch/nodes/{name} .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the Node |=== .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `allowWatchBookmarks` | `boolean` | allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. | `continue` | `string` | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. | `pretty` | `string` | If 'true', then the output is pretty printed. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. | `watch` | `boolean` | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== HTTP method:: `GET` Description:: watch changes to an object of kind Node. deprecated: use the 'watch' parameter with a list operation instead, filtered to a single item with the 'fieldSelector' parameter. .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.WatchEvent[`WatchEvent`] schema | 401 - Unauthorized | Empty |=== === /api/v1/nodes/{name}/status .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the Node |=== .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `GET` Description:: read status of the specified Node .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../node_apis/node-v1.adoc#node-v1[`Node`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `PATCH` Description:: partially update status of the specified Node .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). | `force` | `boolean` | Force is going to "force" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Patch[`Patch`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../node_apis/node-v1.adoc#node-v1[`Node`] schema | 201 - Created | xref:../node_apis/node-v1.adoc#node-v1[`Node`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `PUT` Description:: replace status of the specified Node .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../node_apis/node-v1.adoc#node-v1[`Node`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../node_apis/node-v1.adoc#node-v1[`Node`] schema | 201 - Created | xref:../node_apis/node-v1.adoc#node-v1[`Node`] schema | 401 - Unauthorized | Empty |=== ",12537,True,2579.706965522556,median "CLASS zcl_abapgit_object_tran DEFINITION PUBLIC INHERITING FROM zcl_abapgit_objects_super FINAL. PUBLIC SECTION. INTERFACES zif_abapgit_object. ALIASES mo_files FOR zif_abapgit_object~mo_files. PROTECTED SECTION. PRIVATE SECTION. TYPES: tty_param_values TYPE STANDARD TABLE OF rsparam WITH NON-UNIQUE DEFAULT KEY . CONSTANTS: c_oo_program(9) VALUE '\\PROGRAM=' ##NO_TEXT. CONSTANTS: c_oo_class(7) VALUE '\\CLASS=' ##NO_TEXT. CONSTANTS: c_oo_method(8) VALUE '\\METHOD=' ##NO_TEXT. CONSTANTS c_oo_tcode TYPE tcode VALUE 'OS_APPLICATION' ##NO_TEXT. CONSTANTS: c_oo_frclass(30) VALUE 'CLASS' ##NO_TEXT. CONSTANTS: c_oo_frmethod(30) VALUE 'METHOD' ##NO_TEXT. CONSTANTS: c_oo_frupdtask(30) VALUE 'UPDATE_MODE' ##NO_TEXT. CONSTANTS c_oo_synchron TYPE c VALUE 'S' ##NO_TEXT. CONSTANTS c_oo_asynchron TYPE c VALUE 'U' ##NO_TEXT. CONSTANTS c_true TYPE c VALUE 'X' ##NO_TEXT. CONSTANTS c_false TYPE c VALUE space ##NO_TEXT. DATA: mt_bcdata TYPE STANDARD TABLE OF bdcdata . METHODS shift_param CHANGING !ct_rsparam TYPE s_param !cs_tstcp TYPE tstcp . METHODS add_data IMPORTING !iv_fnam TYPE bdcdata-fnam !iv_fval TYPE clike . METHODS call_se93 RAISING zcx_abapgit_exception . METHODS set_oo_parameters IMPORTING !it_rsparam TYPE s_param CHANGING !cs_rsstcd TYPE rsstcd . METHODS split_parameters CHANGING !ct_rsparam TYPE s_param !cs_rsstcd TYPE rsstcd !cs_tstcp TYPE tstcp !cs_tstc TYPE tstc . METHODS split_parameters_comp IMPORTING !ig_type TYPE any !ig_param TYPE any CHANGING !cg_value TYPE any . METHODS serialize_texts IMPORTING !io_xml TYPE REF TO zcl_abapgit_xml_output RAISING zcx_abapgit_exception . METHODS deserialize_texts IMPORTING !io_xml TYPE REF TO zcl_abapgit_xml_input RAISING zcx_abapgit_exception . METHODS deserialize_oo_transaction IMPORTING !iv_package TYPE devclass !is_tstc TYPE tstc !is_tstcc TYPE tstcc !is_tstct TYPE tstct !is_rsstcd TYPE rsstcd RAISING zcx_abapgit_exception . ENDCLASS. CLASS ZCL_ABAPGIT_OBJECT_TRAN IMPLEMENTATION. METHOD add_data. DATA: ls_bcdata LIKE LINE OF mt_bcdata. ls_bcdata-fnam = iv_fnam. ls_bcdata-fval = iv_fval. APPEND ls_bcdata TO mt_bcdata. ENDMETHOD. METHOD call_se93. DATA: lt_message TYPE STANDARD TABLE OF bdcmsgcoll. FIELD-SYMBOLS: TYPE bdcmsgcoll. CALL FUNCTION 'ABAP4_CALL_TRANSACTION' EXPORTING tcode = 'SE93' mode_val = 'N' TABLES using_tab = mt_bcdata mess_tab = lt_message EXCEPTIONS OTHERS = 1. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( |Error deserializing { ms_item-obj_type } { ms_item-obj_name }| ). ENDIF. LOOP AT lt_message ASSIGNING WHERE msgtyp CA 'EAX'. MESSAGE ID -msgid TYPE -msgtyp NUMBER -msgnr WITH -msgv1 -msgv2 -msgv3 -msgv4 INTO sy-msgli. zcx_abapgit_exception=>raise_t100( ). ENDLOOP. ENDMETHOD. METHOD deserialize_oo_transaction. "" You should remember that we don't use batch input just for fun, "" but because FM RPY_TRANSACTION_INSERT doesn't support OO transactions. DATA: ls_bcdata TYPE bdcdata. CLEAR mt_bcdata. ls_bcdata-program = 'SAPLSEUK'. ls_bcdata-dynpro = '0390'. ls_bcdata-dynbegin = 'X'. APPEND ls_bcdata TO mt_bcdata. add_data( iv_fnam = 'TSTC-TCODE' iv_fval = is_tstc-tcode ). IF zif_abapgit_object~exists( ) = abap_true. add_data( iv_fnam = 'BDC_OKCODE' iv_fval = '=CHNG' ). ELSE. add_data( iv_fnam = 'BDC_OKCODE' iv_fval = '=ADD' ). ENDIF. ls_bcdata-program = 'SAPLSEUK'. ls_bcdata-dynpro = '0300'. ls_bcdata-dynbegin = 'X'. APPEND ls_bcdata TO mt_bcdata. add_data( iv_fnam = 'TSTCT-TTEXT' iv_fval = is_tstct-ttext ). add_data( iv_fnam = 'RSSTCD-S_CLASS' iv_fval = 'X' ). add_data( iv_fnam = 'BDC_OKCODE' iv_fval = '=ENTR' ). ls_bcdata-program = 'SAPLSEUK'. ls_bcdata-dynpro = '0360'. ls_bcdata-dynbegin = 'X'. APPEND ls_bcdata TO mt_bcdata. add_data( iv_fnam = 'RSSTCD-S_TRFRAME' iv_fval = is_rsstcd-s_trframe ). add_data( iv_fnam = 'RSSTCD-S_UPDTASK' iv_fval = is_rsstcd-s_updtask ). add_data( iv_fnam = 'BDC_OKCODE' iv_fval = '=TR_FRAMEWORK' ). ls_bcdata-program = 'SAPLSEUK'. ls_bcdata-dynpro = '0360'. ls_bcdata-dynbegin = 'X'. APPEND ls_bcdata TO mt_bcdata. add_data( iv_fnam = 'RSSTCD-CLASSNAME' iv_fval = is_rsstcd-classname ). add_data( iv_fnam = 'RSSTCD-METHOD' iv_fval = is_rsstcd-method ). IF is_rsstcd-s_local IS NOT INITIAL. add_data( iv_fnam = 'RSSTCD-S_LOCAL' iv_fval = is_rsstcd-s_local ). ENDIF. IF is_rsstcd-s_updlok IS NOT INITIAL. add_data( iv_fnam = 'RSSTCD-S_UPDLOK' iv_fval = is_rsstcd-s_updlok ). ENDIF. add_data( iv_fnam = 'TSTC-PGMNA' iv_fval = is_tstc-pgmna ). IF is_tstcc-s_webgui = '2'. add_data( iv_fnam = 'G_IAC_EWT' iv_fval = abap_true ). add_data( iv_fnam = 'BDC_OKCODE' iv_fval = 'MAKE_PROFI' ). ls_bcdata-program = 'SAPLSEUK'. ls_bcdata-dynpro = '0360'. ls_bcdata-dynbegin = 'X'. APPEND ls_bcdata TO mt_bcdata. ELSEIF is_tstcc-s_webgui IS NOT INITIAL. add_data( iv_fnam = 'TSTCC-S_WEBGUI' iv_fval = is_tstcc-s_webgui ). ENDIF. IF is_tstcc-s_pervas IS NOT INITIAL. add_data( iv_fnam = 'TSTCC-S_PERVAS' iv_fval = is_tstcc-s_pervas ). ENDIF. IF is_tstcc-s_service IS NOT INITIAL. add_data( iv_fnam = 'TSTCC-S_SERVICE' iv_fval = is_tstcc-s_service ). ENDIF. IF is_tstcc-s_platin IS NOT INITIAL. add_data( iv_fnam = 'TSTCC-S_PLATIN' iv_fval = is_tstcc-s_platin ). ENDIF. IF is_tstcc-s_win32 IS NOT INITIAL. add_data( iv_fnam = 'TSTCC-S_WIN32' iv_fval = is_tstcc-s_win32 ). ENDIF. add_data( iv_fnam = 'BDC_OKCODE' iv_fval = '=WB_SAVE' ). ls_bcdata-program = 'SAPLSTRD'. ls_bcdata-dynpro = '0100'. ls_bcdata-dynbegin = 'X'. APPEND ls_bcdata TO mt_bcdata. add_data( iv_fnam = 'KO007-L_DEVCLASS' iv_fval = iv_package ). add_data( iv_fnam = 'BDC_OKCODE' iv_fval = '=ADD' ). ls_bcdata-program = 'BDC_OKCODE'. ls_bcdata-dynpro = '0360'. ls_bcdata-dynbegin = 'X'. APPEND ls_bcdata TO mt_bcdata. add_data( iv_fnam = 'BDC_OKCODE' iv_fval = '=WB_BACK' ). ls_bcdata-program = 'BDC_OKCODE'. ls_bcdata-dynpro = '0360'. ls_bcdata-dynbegin = 'X'. APPEND ls_bcdata TO mt_bcdata. add_data( iv_fnam = 'BDC_OKCODE' iv_fval = '=WB_BACK' ). call_se93( ). ENDMETHOD. METHOD deserialize_texts. DATA lt_tpool_i18n TYPE TABLE OF tstct. FIELD-SYMBOLS LIKE LINE OF lt_tpool_i18n. "" Read XML-files data io_xml->read( EXPORTING iv_name = 'I18N_TPOOL' CHANGING cg_data = lt_tpool_i18n ). "" Force t-code name (security reasons) LOOP AT lt_tpool_i18n ASSIGNING . -tcode = ms_item-obj_name. ENDLOOP. IF lines( lt_tpool_i18n ) > 0. MODIFY tstct FROM TABLE lt_tpool_i18n. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'Update of t-code translations failed' ). ENDIF. ENDIF. ENDMETHOD. METHOD serialize_texts. DATA lt_tpool_i18n TYPE TABLE OF tstct. "" Skip master language - it was already serialized "" Don't serialize t-code itself SELECT sprsl ttext INTO CORRESPONDING FIELDS OF TABLE lt_tpool_i18n FROM tstct WHERE sprsl <> mv_language AND tcode = ms_item-obj_name. ""#EC CI_GENBUFF IF lines( lt_tpool_i18n ) > 0. SORT lt_tpool_i18n BY sprsl ASCENDING. io_xml->add( iv_name = 'I18N_TPOOL' ig_data = lt_tpool_i18n ). ENDIF. ENDMETHOD. METHOD set_oo_parameters. DATA: ls_param LIKE LINE OF it_rsparam. IF cs_rsstcd-call_tcode = c_oo_tcode. cs_rsstcd-s_trframe = c_true. LOOP AT it_rsparam INTO ls_param. CASE ls_param-field. WHEN c_oo_frclass. cs_rsstcd-classname = ls_param-value. WHEN c_oo_frmethod. cs_rsstcd-method = ls_param-value. WHEN c_oo_frupdtask. IF ls_param-value = c_oo_synchron. cs_rsstcd-s_upddir = c_true. cs_rsstcd-s_updtask = c_false. cs_rsstcd-s_updlok = c_false. ELSEIF ls_param-value = c_oo_asynchron. cs_rsstcd-s_upddir = c_false. cs_rsstcd-s_updtask = c_true. cs_rsstcd-s_updlok = c_false. ELSE. cs_rsstcd-s_upddir = c_false. cs_rsstcd-s_updtask = c_false. cs_rsstcd-s_updlok = c_true. ENDIF. ENDCASE. ENDLOOP. ENDIF. ENDMETHOD. METHOD shift_param. DATA: ls_param LIKE LINE OF ct_rsparam, lv_length TYPE i. FIELD-SYMBOLS TYPE any. DO 254 TIMES. IF cs_tstcp-param = space. EXIT. ENDIF. CLEAR ls_param. IF cs_tstcp-param CA '='. CHECK sy-fdpos <> 0. ASSIGN cs_tstcp-param(sy-fdpos) TO . ls_param-field = . IF ls_param-field(1) = space. SHIFT ls_param-field. ENDIF. sy-fdpos = sy-fdpos + 1. SHIFT cs_tstcp-param BY sy-fdpos PLACES. IF cs_tstcp-param CA ';'. IF sy-fdpos <> 0. ASSIGN cs_tstcp-param(sy-fdpos) TO . ls_param-value = . IF ls_param-value(1) = space. SHIFT ls_param-value. ENDIF. ENDIF. sy-fdpos = sy-fdpos + 1. SHIFT cs_tstcp-param BY sy-fdpos PLACES. APPEND ls_param TO ct_rsparam. ELSE. lv_length = strlen( cs_tstcp-param ). CHECK lv_length > 0. ASSIGN cs_tstcp-param(lv_length) TO . ls_param-value = . IF ls_param-value(1) = space. SHIFT ls_param-value. ENDIF. lv_length = lv_length + 1. SHIFT cs_tstcp-param BY lv_length PLACES. APPEND ls_param TO ct_rsparam. ENDIF. ENDIF. ENDDO. ENDMETHOD. METHOD split_parameters. * see subroutine split_parameters in include LSEUKF01 DATA: lv_off TYPE i, lv_param_beg TYPE i. CLEAR cs_rsstcd-s_vari. IF cs_tstcp-param(1) = '\\'. "" OO-Transaktion ohne FR split_parameters_comp( EXPORTING ig_type = c_oo_program ig_param = cs_tstcp-param CHANGING cg_value = cs_tstc-pgmna ). split_parameters_comp( EXPORTING ig_type = c_oo_class ig_param = cs_tstcp-param CHANGING cg_value = cs_rsstcd-classname ). split_parameters_comp( EXPORTING ig_type = c_oo_method ig_param = cs_tstcp-param CHANGING cg_value = cs_rsstcd-method ). IF NOT cs_tstc-pgmna IS INITIAL. cs_rsstcd-s_local = c_true. ENDIF. RETURN. ELSEIF cs_tstcp-param(1) = '@'. "" Transaktionsvariante cs_rsstcd-s_vari = c_true. IF cs_tstcp-param(2) = '@@'. cs_rsstcd-s_ind_vari = c_true. lv_off = 2. ELSE. CLEAR cs_rsstcd-s_ind_vari. lv_off = 1. ENDIF. IF cs_tstcp-param CA ' '. ENDIF. sy-fdpos = sy-fdpos - lv_off. IF sy-fdpos > 0. cs_rsstcd-call_tcode = cs_tstcp-param+lv_off(sy-fdpos). sy-fdpos = sy-fdpos + 1 + lv_off. cs_rsstcd-variant = cs_tstcp-param+sy-fdpos. ENDIF. ELSEIF cs_tstcp-param(1) = '/'. cs_rsstcd-st_tcode = c_true. cs_rsstcd-st_prog = space. IF cs_tstcp-param+1(1) = '*'. cs_rsstcd-st_skip_1 = c_true. ELSE. CLEAR cs_rsstcd-st_skip_1. ENDIF. IF cs_tstcp-param CA ' '. ENDIF. lv_param_beg = sy-fdpos + 1. sy-fdpos = sy-fdpos - 2. IF sy-fdpos > 0. cs_rsstcd-call_tcode = cs_tstcp-param+2(sy-fdpos). ENDIF. SHIFT cs_tstcp-param BY lv_param_beg PLACES. ELSE. cs_rsstcd-st_tcode = space. cs_rsstcd-st_prog = c_true. ENDIF. shift_param( CHANGING ct_rsparam = ct_rsparam cs_tstcp = cs_tstcp ). set_oo_parameters( EXPORTING it_rsparam = ct_rsparam CHANGING cs_rsstcd = cs_rsstcd ). ENDMETHOD. METHOD split_parameters_comp. DATA: lv_off TYPE i. IF ig_param CS ig_type. lv_off = sy-fdpos + strlen( ig_type ). cg_value = ig_param+lv_off. IF cg_value CA '\\'. CLEAR cg_value+sy-fdpos. ENDIF. ENDIF. ENDMETHOD. METHOD zif_abapgit_object~changed_by. rv_user = c_user_unknown. "" todo ENDMETHOD. METHOD zif_abapgit_object~delete. DATA: lv_transaction TYPE tstc-tcode. lv_transaction = ms_item-obj_name. CALL FUNCTION 'RPY_TRANSACTION_DELETE' EXPORTING transaction = lv_transaction EXCEPTIONS not_excecuted = 1 object_not_found = 0 OTHERS = 3. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'Error from RPY_TRANSACTION_DELETE' ). ENDIF. ENDMETHOD. METHOD zif_abapgit_object~deserialize. CONSTANTS: lc_hex_tra TYPE x VALUE '00', * c_hex_men TYPE x VALUE '01', lc_hex_par TYPE x VALUE '02', lc_hex_rep TYPE x VALUE '80', * c_hex_rpv TYPE x VALUE '10', lc_hex_obj TYPE x VALUE '08'. DATA: lv_dynpro TYPE d020s-dnum, ls_tstc TYPE tstc, lv_type TYPE rglif-docutype, ls_tstct TYPE tstct, ls_tstcc TYPE tstcc, ls_tstcp TYPE tstcp, lt_param_values TYPE tty_param_values, ls_rsstcd TYPE rsstcd. ""Do not delete now (2019-09-10) MIJ *** IF zif_abapgit_object~exists( ) = abap_true. *** zif_abapgit_object~delete( ). *** ENDIF. io_xml->read( EXPORTING iv_name = 'TSTC' CHANGING cg_data = ls_tstc ). io_xml->read( EXPORTING iv_name = 'TSTCC' CHANGING cg_data = ls_tstcc ). io_xml->read( EXPORTING iv_name = 'TSTCT' CHANGING cg_data = ls_tstct ). io_xml->read( EXPORTING iv_name = 'TSTCP' CHANGING cg_data = ls_tstcp ). lv_dynpro = ls_tstc-dypno. CASE ls_tstc-cinfo. WHEN lc_hex_tra. lv_type = ststc_c_type_dialog. WHEN lc_hex_rep. lv_type = ststc_c_type_report. WHEN lc_hex_par. lv_type = ststc_c_type_parameters. WHEN lc_hex_obj. lv_type = ststc_c_type_object. * todo, or ststc_c_type_variant? WHEN OTHERS. zcx_abapgit_exception=>raise( 'Transaction, unknown CINFO' ). ENDCASE. ""Do deletion only in cse CINFO is known (2019-09-10) MIJ IF zif_abapgit_object~exists( ) = abap_true. zif_abapgit_object~delete( ). ENDIF. IF ls_tstcp IS NOT INITIAL. split_parameters( CHANGING ct_rsparam = lt_param_values cs_rsstcd = ls_rsstcd cs_tstcp = ls_tstcp cs_tstc = ls_tstc ). ENDIF. CASE lv_type. WHEN ststc_c_type_object. deserialize_oo_transaction( iv_package = iv_package is_tstc = ls_tstc is_tstcc = ls_tstcc is_tstct = ls_tstct is_rsstcd = ls_rsstcd ). WHEN OTHERS. CALL FUNCTION 'RPY_TRANSACTION_INSERT' EXPORTING transaction = ls_tstc-tcode program = ls_tstc-pgmna dynpro = lv_dynpro language = mv_language development_class = iv_package transaction_type = lv_type shorttext = ls_tstct-ttext called_transaction = ls_rsstcd-call_tcode called_transaction_skip = ls_rsstcd-st_skip_1 variant = ls_rsstcd-variant cl_independend = ls_rsstcd-s_ind_vari html_enabled = ls_tstcc-s_webgui java_enabled = ls_tstcc-s_platin wingui_enabled = ls_tstcc-s_win32 TABLES param_values = lt_param_values EXCEPTIONS cancelled = 1 already_exist = 2 permission_error = 3 name_not_allowed = 4 name_conflict = 5 illegal_type = 6 object_inconsistent = 7 db_access_error = 8 OTHERS = 9. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'Error from RPY_TRANSACTION_INSERT' ). ENDIF. ENDCASE. "" Texts deserializing (translations) deserialize_texts( io_xml ). ENDMETHOD. METHOD zif_abapgit_object~exists. DATA: lv_tcode TYPE tstc-tcode. SELECT SINGLE tcode FROM tstc INTO lv_tcode WHERE tcode = ms_item-obj_name. ""#EC CI_GENBUFF rv_bool = boolc( sy-subrc = 0 ). ENDMETHOD. METHOD zif_abapgit_object~get_comparator. RETURN. ENDMETHOD. METHOD zif_abapgit_object~get_deserialize_steps. APPEND zif_abapgit_object=>gc_step_id-abap TO rt_steps. ENDMETHOD. METHOD zif_abapgit_object~get_metadata. rs_metadata = get_metadata( ). ENDMETHOD. METHOD zif_abapgit_object~is_active. rv_active = is_active( ). ENDMETHOD. METHOD zif_abapgit_object~is_locked. DATA: lv_object TYPE eqegraarg. lv_object = |TN{ ms_item-obj_name }|. OVERLAY lv_object WITH ' '. lv_object = lv_object && '*'. rv_is_locked = exists_a_lock_entry_for( iv_lock_object = 'EEUDB' iv_argument = lv_object ). ENDMETHOD. METHOD zif_abapgit_object~jump. DATA: lt_bdcdata TYPE TABLE OF bdcdata. FIELD-SYMBOLS: LIKE LINE OF lt_bdcdata. APPEND INITIAL LINE TO lt_bdcdata ASSIGNING . -program = 'SAPLSEUK'. -dynpro = '0390'. -dynbegin = abap_true. APPEND INITIAL LINE TO lt_bdcdata ASSIGNING . -fnam = 'BDC_OKCODE'. -fval = '=SHOW'. APPEND INITIAL LINE TO lt_bdcdata ASSIGNING . -fnam = 'TSTC-TCODE'. -fval = ms_item-obj_name. CALL FUNCTION 'ABAP4_CALL_TRANSACTION' STARTING NEW TASK 'GIT' EXPORTING tcode = 'SE93' mode_val = 'E' TABLES using_tab = lt_bdcdata EXCEPTIONS system_failure = 1 communication_failure = 2 resource_failure = 3 OTHERS = 4 ##fm_subrc_ok. ""#EC CI_SUBRC ENDMETHOD. METHOD zif_abapgit_object~serialize. DATA: lv_transaction TYPE tstc-tcode, lt_tcodes TYPE TABLE OF tstc, ls_tcode LIKE LINE OF lt_tcodes, ls_tstct TYPE tstct, ls_tstcp TYPE tstcp, lt_gui_attr TYPE TABLE OF tstcc, ls_gui_attr LIKE LINE OF lt_gui_attr. lv_transaction = ms_item-obj_name. CALL FUNCTION 'RPY_TRANSACTION_READ' EXPORTING transaction = lv_transaction TABLES tcodes = lt_tcodes gui_attributes = lt_gui_attr EXCEPTIONS permission_error = 1 cancelled = 2 not_found = 3 object_not_found = 4 OTHERS = 5. IF sy-subrc = 4 OR sy-subrc = 3. RETURN. ELSEIF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'Error from RPY_TRANSACTION_READ' ). ENDIF. SELECT SINGLE * FROM tstct INTO ls_tstct WHERE sprsl = mv_language AND tcode = lv_transaction. ""#EC CI_SUBRC ""#EC CI_GENBUFF SELECT SINGLE * FROM tstcp INTO ls_tstcp WHERE tcode = lv_transaction. ""#EC CI_SUBRC ""#EC CI_GENBUFF READ TABLE lt_tcodes INDEX 1 INTO ls_tcode. ASSERT sy-subrc = 0. READ TABLE lt_gui_attr INDEX 1 INTO ls_gui_attr. ASSERT sy-subrc = 0. io_xml->add( iv_name = 'TSTC' ig_data = ls_tcode ). io_xml->add( iv_name = 'TSTCC' ig_data = ls_gui_attr ). io_xml->add( iv_name = 'TSTCT' ig_data = ls_tstct ). IF ls_tstcp IS NOT INITIAL. io_xml->add( iv_name = 'TSTCP' ig_data = ls_tstcp ). ENDIF. "" Texts serializing (translations) serialize_texts( io_xml ). ENDMETHOD. ENDCLASS. ",6344,False,1324.0174200709396,median "class ZCL_EXCEL_CONVERTER_ALV definition public abstract create public . *""* public components of class ZCL_EXCEL_CONVERTER_ALV *""* do not include other source files here!!! public section. type-pools ABAP . type-pools KKBLO . interfaces ZIF_EXCEL_CONVERTER all methods abstract . class-methods CLASS_CONSTRUCTOR . *""* protected components of class ZCL_EXCEL_CONVERTER_ALV *""* do not include other source files here!!! protected section. data WT_SORT type LVC_T_SORT . data WT_FILT type LVC_T_FILT . data WT_FCAT type LVC_T_FCAT . data WS_LAYO type LVC_S_LAYO . data WS_OPTION type ZEXCEL_S_CONVERTER_OPTION . methods UPDATE_CATALOG changing !CS_LAYOUT type ZEXCEL_S_CONVERTER_LAYO !CT_FIELDCATALOG type ZEXCEL_T_CONVERTER_FCAT . methods APPLY_SORT importing !IT_TABLE type STANDARD TABLE exporting !EO_TABLE type ref to DATA . methods GET_COLOR importing !IO_TABLE type ref to DATA exporting !ET_COLORS type ZEXCEL_T_CONVERTER_COL . methods GET_FILTER exporting !ET_FILTER type ZEXCEL_T_CONVERTER_FIL changing !XO_TABLE type ref to DATA . *""* private components of class ZCL_EXCEL_CONVERTER_ALV *""* do not include other source files here!!! private section. class-data WT_COLORS type TT_COL_CONVERTER . ENDCLASS. CLASS ZCL_EXCEL_CONVERTER_ALV IMPLEMENTATION. method APPLY_SORT. DATA: lt_otab TYPE abap_sortorder_tab, ls_otab TYPE abap_sortorder. FIELD-SYMBOLS: TYPE STANDARD TABLE, TYPE lvc_s_sort. CREATE DATA eo_table LIKE it_table. ASSIGN eo_table->* TO . = it_table. SORT wt_sort BY spos. LOOP AT wt_sort ASSIGNING . IF -up = abap_true. ls_otab-name = -fieldname. ls_otab-descending = abap_false. * ls_otab-astext = abap_true. "" not only text fields INSERT ls_otab INTO TABLE lt_otab. ENDIF. IF -down = abap_true. ls_otab-name = -fieldname. ls_otab-descending = abap_true. * ls_otab-astext = abap_true. "" not only text fields INSERT ls_otab INTO TABLE lt_otab. ENDIF. ENDLOOP. IF lt_otab IS NOT INITIAL. SORT BY (lt_otab). ENDIF. endmethod. method CLASS_CONSTRUCTOR. * let's fill the color conversion routines. DATA: ls_color TYPE ts_col_converter. * 0 all combination the same ls_color-col = 0. ls_color-int = 0. ls_color-inv = 0. ls_color-fontcolor = 'FF000000'. "" 000 000 000 Black ls_color-fillcolor = 'FFFFFFFF'. "" 255 255 255 White INSERT ls_color INTO TABLE wt_colors. ls_color-col = 0. ls_color-int = 0. ls_color-inv = 1. ls_color-fontcolor = 'FF000000'. "" 000 000 000 Black ls_color-fillcolor = 'FFFFFFFF'. "" 255 255 255 White INSERT ls_color INTO TABLE wt_colors. ls_color-col = 0. ls_color-int = 1. ls_color-inv = 0. ls_color-fontcolor = 'FF000000'. "" 000 000 000 Black ls_color-fillcolor = 'FFFFFFFF'. "" 255 255 255 White INSERT ls_color INTO TABLE wt_colors. ls_color-col = 0. ls_color-int = 1. ls_color-inv = 1. ls_color-fontcolor = 'FF000000'. "" 000 000 000 Black ls_color-fillcolor = 'FFFFFFFF'. "" 255 255 255 White INSERT ls_color INTO TABLE wt_colors. * Blue ls_color-col = 1. ls_color-int = 0. ls_color-inv = 0. ls_color-fontcolor = 'FF000000'. "" 000 000 000 Black ls_color-fillcolor = 'FFB0E4FC'. "" 176 228 252 blue INSERT ls_color INTO TABLE wt_colors. ls_color-col = 1. ls_color-int = 0. ls_color-inv = 1. ls_color-fontcolor = 'FFB0E4FC'. "" 176 228 252 blue ls_color-fillcolor = 'FFFFFFFF'. "" 255 255 255 White INSERT ls_color INTO TABLE wt_colors. ls_color-col = 1. ls_color-int = 1. ls_color-inv = 0. ls_color-fontcolor = 'FF000000'. "" 000 000 000 Black ls_color-fillcolor = 'FF5FCBFE'. "" 095 203 254 Int blue INSERT ls_color INTO TABLE wt_colors. ls_color-col = 1. ls_color-int = 1. ls_color-inv = 1. ls_color-fontcolor = 'FF5FCBFE'. "" 095 203 254 ls_color-fillcolor = 'FFFFFFFF'. "" 255 255 255 INSERT ls_color INTO TABLE wt_colors. * Gray ls_color-col = 2. ls_color-int = 0. ls_color-inv = 0. ls_color-fontcolor = 'FF000000'. ls_color-fillcolor = 'FFE5EAF0'. "" 229 234 240 gray INSERT ls_color INTO TABLE wt_colors. ls_color-col = 2. ls_color-int = 0. ls_color-inv = 1. ls_color-fontcolor = 'FFE5EAF0'. "" 229 234 240 gray ls_color-fillcolor = 'FFFFFFFF'. "" 255 255 255 White INSERT ls_color INTO TABLE wt_colors. ls_color-col = 2. ls_color-int = 1. ls_color-inv = 0. ls_color-fontcolor = 'FF000000'. "" 000 000 000 Black ls_color-fillcolor = 'FFD8E8F4'. "" 216 234 244 int gray INSERT ls_color INTO TABLE wt_colors. ls_color-col = 2. ls_color-int = 1. ls_color-inv = 1. ls_color-fontcolor = 'FFD8E8F4'. "" 216 234 244 int gray ls_color-fillcolor = 'FFFFFFFF'. "" 255 255 255 White INSERT ls_color INTO TABLE wt_colors. *Yellow ls_color-col = 3. ls_color-int = 0. ls_color-inv = 0. ls_color-fontcolor = 'FF000000'. "" 000 000 000 Black ls_color-fillcolor = 'FFFEFEB8'. "" 254 254 184 yellow INSERT ls_color INTO TABLE wt_colors. ls_color-col = 3. ls_color-int = 0. ls_color-inv = 1. ls_color-fontcolor = 'FFFEFEB8'. "" 254 254 184 yellow ls_color-fillcolor = 'FFFFFFFF'. "" 255 255 255 White INSERT ls_color INTO TABLE wt_colors. ls_color-col = 3. ls_color-int = 1. ls_color-inv = 0. ls_color-fontcolor = 'FF000000'. "" 000 000 000 Black ls_color-fillcolor = 'FFF9ED5D'. "" 249 237 093 int yellow INSERT ls_color INTO TABLE wt_colors. ls_color-col = 3. ls_color-int = 1. ls_color-inv = 1. ls_color-fontcolor = 'FFF9ED5D'. "" 249 237 093 int yellow ls_color-fillcolor = 'FFFFFFFF'. "" 255 255 255 White INSERT ls_color INTO TABLE wt_colors. * light blue ls_color-col = 4. ls_color-int = 0. ls_color-inv = 0. ls_color-fontcolor = 'FF000000'. "" 000 000 000 Black ls_color-fillcolor = 'FFCEE7FB'. "" 206 231 251 light blue INSERT ls_color INTO TABLE wt_colors. ls_color-col = 4. ls_color-int = 0. ls_color-inv = 1. ls_color-fontcolor = 'FFCEE7FB'. "" 206 231 251 light blue ls_color-fillcolor = 'FFFFFFFF'. "" 255 255 255 White INSERT ls_color INTO TABLE wt_colors. ls_color-col = 4. ls_color-int = 1. ls_color-inv = 0. ls_color-fontcolor = 'FF000000'. "" 000 000 000 Black ls_color-fillcolor = 'FF9ACCEF'. "" 154 204 239 int light blue INSERT ls_color INTO TABLE wt_colors. ls_color-col = 4. ls_color-int = 1. ls_color-inv = 1. ls_color-fontcolor = 'FF9ACCEF'. "" 154 204 239 int light blue ls_color-fillcolor = 'FFFFFFFF'. "" 255 255 255 White INSERT ls_color INTO TABLE wt_colors. * Green ls_color-col = 5. ls_color-int = 0. ls_color-inv = 0. ls_color-fontcolor = 'FF000000'. "" 000 000 000 Black ls_color-fillcolor = 'FFCEF8AE'. "" 206 248 174 Green INSERT ls_color INTO TABLE wt_colors. ls_color-col = 5. ls_color-int = 0. ls_color-inv = 1. ls_color-fontcolor = 'FFCEF8AE'. "" 206 248 174 Green ls_color-fillcolor = 'FFFFFFFF'. "" 255 255 255 White INSERT ls_color INTO TABLE wt_colors. ls_color-col = 5. ls_color-int = 1. ls_color-inv = 0. ls_color-fontcolor = 'FF000000'. "" 000 000 000 Black ls_color-fillcolor = 'FF7AC769'. "" 122 199 105 int Green INSERT ls_color INTO TABLE wt_colors. ls_color-col = 5. ls_color-int = 1. ls_color-inv = 1. ls_color-fontcolor = 'FF7AC769'. "" 122 199 105 int Green ls_color-fillcolor = 'FFFFFFFF'. "" 255 255 255 White INSERT ls_color INTO TABLE wt_colors. * Red ls_color-col = 6. ls_color-int = 0. ls_color-inv = 0. ls_color-fontcolor = 'FF000000'. "" 000 000 000 Black ls_color-fillcolor = 'FFFDBBBC'. "" 253 187 188 Red INSERT ls_color INTO TABLE wt_colors. ls_color-col = 6. ls_color-int = 0. ls_color-inv = 1. ls_color-fontcolor = 'FFFDBBBC'. "" 253 187 188 Red ls_color-fillcolor = 'FFFFFFFF'. "" 255 255 255 White INSERT ls_color INTO TABLE wt_colors. ls_color-col = 6. ls_color-int = 1. ls_color-inv = 0. ls_color-fontcolor = 'FF000000'. "" 000 000 000 Black ls_color-fillcolor = 'FFFB6B6B'. "" 251 107 107 int Red INSERT ls_color INTO TABLE wt_colors. ls_color-col = 6. ls_color-int = 1. ls_color-inv = 1. ls_color-fontcolor = 'FFFB6B6B'. "" 251 107 107 int Red ls_color-fillcolor = 'FFFFFFFF'. "" 255 255 255 White INSERT ls_color INTO TABLE wt_colors. endmethod. method GET_COLOR. DATA: ls_con_col TYPE zexcel_s_converter_col, ls_color TYPE ts_col_converter, l_line TYPE i, l_color(4) TYPE c. FIELD-SYMBOLS: TYPE STANDARD TABLE, TYPE ANY, TYPE ANY, type standard table, type any. * Loop trough the table to set the color properties of each line. The color properties field is * Char 4 and the characters is set as follows: * Char 1 = C = This is a color property * Char 2 = 6 = Color code (1 - 7) * Char 3 = Intensified on/of = 1 = on * Char 4 = Inverse display = 0 = of ASSIGN io_table->* TO . IF ws_layo-info_fname IS NOT INITIAL OR ws_layo-ctab_fname IS NOT INITIAL. LOOP AT ASSIGNING . l_line = sy-tabix. IF ws_layo-info_fname IS NOT INITIAL. ASSIGN COMPONENT ws_layo-info_fname OF STRUCTURE TO . IF sy-subrc = 0 AND IS NOT INITIAL. l_color = . IF l_color(1) = 'C'. READ TABLE wt_colors INTO ls_color WITH TABLE KEY col = l_color+1(1) int = l_color+2(1) inv = l_color+3(1). IF sy-subrc = 0. ls_con_col-rownumber = l_line. ls_con_col-columnname = space. ls_con_col-fontcolor = ls_color-fontcolor. ls_con_col-fillcolor = ls_color-fillcolor. INSERT ls_con_col INTO TABLE et_colors. ENDIF. ENDIF. ENDIF. ENDIF. if ws_layo-ctab_fname is not initial. assign component ws_layo-ctab_fname of structure to . if sy-subrc = 0. loop at assigning . assign component 'COLOR' of structure to . if sy-subrc = 0. if is not initial. field-symbols: type any, type any, type any, type any, type any. assign component 'COL' of structure to . assign component 'INT' of structure to . assign component 'INV' of structure to . read table wt_colors into ls_color with table key col = int = inv = . if sy-subrc = 0. ls_con_col-rownumber = l_line. assign component 'FNAME' of structure to . if sy-subrc ne 0. assign component 'FIELDNAME' of structure to . if sy-subrc eq 0. ls_con_col-columnname = . endif. else. ls_con_col-columnname = . endif. ls_con_col-fontcolor = ls_color-fontcolor. ls_con_col-fillcolor = ls_color-fillcolor. assign component 'NOKEYCOL' of structure to . if sy-subrc eq 0. ls_con_col-nokeycol = . endif. insert ls_con_col into table et_colors. endif. endif. endif. endloop. endif. endif. ENDLOOP. ENDIF. endmethod. METHOD get_filter. DATA: ls_filt TYPE lvc_s_filt, l_line TYPE i, ls_filter TYPE zexcel_s_converter_fil. DATA: lo_addit TYPE REF TO cl_abap_elemdescr, lt_components_tab TYPE cl_abap_structdescr=>component_table, ls_components TYPE abap_componentdescr, lo_table TYPE REF TO cl_abap_tabledescr, lo_struc TYPE REF TO cl_abap_structdescr, lo_trange TYPE REF TO data, lo_srange TYPE REF TO data, lo_ltabdata TYPE REF TO data. FIELD-SYMBOLS: TYPE STANDARD TABLE, TYPE STANDARD TABLE, TYPE any, TYPE any, TYPE any, TYPE any, TYPE STANDARD TABLE. IF ws_option-filter = abap_false. REFRESH et_filter. RETURN. ENDIF. ASSIGN xo_table->* TO . CREATE DATA lo_ltabdata LIKE . ASSIGN lo_ltabdata->* TO . LOOP AT wt_filt INTO ls_filt. LOOP AT ASSIGNING . l_line = sy-tabix. ASSIGN COMPONENT ls_filt-fieldname OF STRUCTURE TO . IF sy-subrc = 0. IF l_line = 1. REFRESH lt_components_tab. ls_components-name = 'SIGN'. lo_addit ?= cl_abap_typedescr=>describe_by_data( ls_filt-sign ). ls_components-type = lo_addit . INSERT ls_components INTO TABLE lt_components_tab. ls_components-name = 'OPTION'. lo_addit ?= cl_abap_typedescr=>describe_by_data( ls_filt-option ). ls_components-type = lo_addit . INSERT ls_components INTO TABLE lt_components_tab. ls_components-name = 'LOW'. lo_addit ?= cl_abap_typedescr=>describe_by_data( ). ls_components-type = lo_addit . INSERT ls_components INTO TABLE lt_components_tab. ls_components-name = 'HIGH'. lo_addit ?= cl_abap_typedescr=>describe_by_data( ). ls_components-type = lo_addit . INSERT ls_components INTO TABLE lt_components_tab. ""create new line type TRY. lo_struc = cl_abap_structdescr=>create( p_components = lt_components_tab p_strict = abap_false ). CATCH cx_sy_struct_creation. CONTINUE. ENDTRY. lo_table = cl_abap_tabledescr=>create( lo_struc ). CREATE DATA lo_trange TYPE HANDLE lo_table. CREATE DATA lo_srange TYPE HANDLE lo_struc. ASSIGN lo_trange->* TO . ASSIGN lo_srange->* TO . ENDIF. REFRESH . ASSIGN COMPONENT 'SIGN' OF STRUCTURE TO . = ls_filt-sign. ASSIGN COMPONENT 'OPTION' OF STRUCTURE TO . = ls_filt-option. ASSIGN COMPONENT 'LOW' OF STRUCTURE TO . = ls_filt-low. ASSIGN COMPONENT 'HIGH' OF STRUCTURE TO . = ls_filt-high. INSERT INTO TABLE . IF IN . IF ws_option-filter = abap_true. ls_filter-rownumber = l_line. ls_filter-columnname = ls_filt-fieldname. INSERT ls_filter INTO TABLE et_filter. ELSE. INSERT INTO TABLE . ENDIF. ENDIF. ENDIF. ENDLOOP. IF ws_option-filter = abap_undefined. = . REFRESH . ENDIF. ENDLOOP. ENDMETHOD. method UPDATE_CATALOG. DATA: ls_fieldcatalog TYPE zexcel_s_converter_fcat, ls_fcat TYPE lvc_s_fcat, ls_sort TYPE lvc_s_sort, l_decimals TYPE lvc_decmls. FIELD-SYMBOLS: TYPE zexcel_s_converter_fcat. IF ws_layo-zebra IS NOT INITIAL. cs_layout-is_stripped = abap_true. ENDIF. IF ws_layo-no_keyfix IS INITIAL OR ws_layo-no_keyfix = '0'. cs_layout-is_fixed = abap_true. ENDIF. LOOP AT wt_fcat INTO ls_fcat. CLEAR: ls_fieldcatalog, l_decimals. CASE ws_option-hidenc. WHEN abap_false. "" We make hiden columns visible CLEAR ls_fcat-no_out. WHEN abap_true. * We convert column and hide it. WHEN abap_undefined. ""We don't convert hiden columns IF ls_fcat-no_out = abap_true. ls_fcat-tech = abap_true. ENDIF. ENDCASE. IF ls_fcat-tech = abap_false. ls_fieldcatalog-tabname = ls_fcat-tabname. ls_fieldcatalog-fieldname = ls_fcat-fieldname . ls_fieldcatalog-columnname = ls_fcat-fieldname . ls_fieldcatalog-position = ls_fcat-col_pos. ls_fieldcatalog-col_id = ls_fcat-col_id. ls_fieldcatalog-convexit = ls_fcat-convexit. ls_fieldcatalog-inttype = ls_fcat-inttype. ls_fieldcatalog-scrtext_s = ls_fcat-scrtext_s . ls_fieldcatalog-scrtext_m = ls_fcat-scrtext_m . ls_fieldcatalog-scrtext_l = ls_fcat-scrtext_l. l_decimals = ls_fcat-decimals_o. IF l_decimals IS NOT INITIAL. ls_fieldcatalog-decimals = l_decimals. ELSE. ls_fieldcatalog-decimals = ls_fcat-decimals . ENDIF. CASE ws_option-subtot. WHEN abap_false. "" We ignore subtotals CLEAR ls_fcat-do_sum. WHEN abap_true. "" We convert subtotals and detail WHEN abap_undefined. "" We should only take subtotals and displayed detail * for now abap_true ENDCASE. CASE ls_fcat-do_sum. WHEN abap_true. ls_fieldcatalog-totals_function = zcl_excel_table=>totals_function_sum. WHEN 'A'. ls_fieldcatalog-totals_function = zcl_excel_table=>totals_function_min. WHEN 'B' . ls_fieldcatalog-totals_function = zcl_excel_table=>totals_function_max. WHEN 'C' . ls_fieldcatalog-totals_function = zcl_excel_table=>totals_function_average. WHEN OTHERS. CLEAR ls_fieldcatalog-totals_function . ENDCASE. ls_fieldcatalog-fix_column = ls_fcat-fix_column. IF ws_layo-cwidth_opt IS INITIAL. IF ls_fcat-col_opt IS NOT INITIAL. ls_fieldcatalog-is_optimized = abap_true. ENDIF. ELSE. ls_fieldcatalog-is_optimized = abap_true. ENDIF. IF ls_fcat-no_out IS NOT INITIAL. ls_fieldcatalog-is_hidden = abap_true. ls_fieldcatalog-position = ls_fieldcatalog-col_id. "" We hide based on orginal data structure ENDIF. * Alignment in each cell CASE ls_fcat-just. WHEN 'R'. ls_fieldcatalog-alignment = zcl_excel_style_alignment=>c_horizontal_right. WHEN 'L'. ls_fieldcatalog-alignment = zcl_excel_style_alignment=>c_horizontal_left. WHEN 'C'. ls_fieldcatalog-alignment = zcl_excel_style_alignment=>c_horizontal_center. WHEN OTHERS. CLEAR ls_fieldcatalog-alignment. ENDCASE. * Check for subtotals. READ TABLE wt_sort INTO ls_sort WITH KEY fieldname = ls_fcat-fieldname. IF sy-subrc = 0 AND ws_option-subtot <> abap_false. ls_fieldcatalog-sort_level = 0 . * IF ls_fieldcatalog-totals_function IS INITIAL. "" Not clear why not * CLEAR ls_fieldcatalog-is_subtotalled. * ELSE. ls_fieldcatalog-is_subtotalled = ls_sort-subtot. * ENDIF. ls_fieldcatalog-is_collapsed = ls_sort-expa. IF ls_fieldcatalog-is_subtotalled = abap_true. ls_fieldcatalog-sort_level = ls_sort-spos. ls_fieldcatalog-totals_function = zcl_excel_table=>totals_function_sum. "" we need function for text ENDIF. ENDIF. APPEND ls_fieldcatalog TO ct_fieldcatalog. ENDIF. ENDLOOP. SORT ct_fieldcatalog BY sort_level ASCENDING. cs_layout-max_subtotal_level = 0. LOOP AT ct_fieldcatalog ASSIGNING WHERE sort_level > 0. cs_layout-max_subtotal_level = cs_layout-max_subtotal_level + 1. -sort_level = cs_layout-max_subtotal_level. ENDLOOP. endmethod. ENDCLASS. ",6228,False,1216.0482793413978,median "CLASS zcl_abapgit_services_repo DEFINITION PUBLIC FINAL CREATE PUBLIC . PUBLIC SECTION. CLASS-METHODS new_online IMPORTING !iv_url TYPE string RETURNING VALUE(ro_repo) TYPE REF TO zcl_abapgit_repo_online RAISING zcx_abapgit_exception zcx_abapgit_cancel . CLASS-METHODS refresh IMPORTING !iv_key TYPE zif_abapgit_persistence=>ty_repo-key RAISING zcx_abapgit_exception . CLASS-METHODS remove IMPORTING !iv_key TYPE zif_abapgit_persistence=>ty_repo-key RAISING zcx_abapgit_exception zcx_abapgit_cancel . CLASS-METHODS purge IMPORTING !iv_key TYPE zif_abapgit_persistence=>ty_repo-key RAISING zcx_abapgit_exception zcx_abapgit_cancel . CLASS-METHODS new_offline RAISING zcx_abapgit_exception zcx_abapgit_cancel . CLASS-METHODS remote_attach IMPORTING !iv_key TYPE zif_abapgit_persistence=>ty_repo-key RAISING zcx_abapgit_exception zcx_abapgit_cancel . CLASS-METHODS remote_detach IMPORTING !iv_key TYPE zif_abapgit_persistence=>ty_repo-key RAISING zcx_abapgit_exception zcx_abapgit_cancel . CLASS-METHODS remote_change IMPORTING !iv_key TYPE zif_abapgit_persistence=>ty_repo-key RAISING zcx_abapgit_exception zcx_abapgit_cancel . CLASS-METHODS refresh_local_checksums IMPORTING !iv_key TYPE zif_abapgit_persistence=>ty_repo-key RAISING zcx_abapgit_exception zcx_abapgit_cancel . CLASS-METHODS toggle_favorite IMPORTING !iv_key TYPE zif_abapgit_persistence=>ty_repo-key RAISING zcx_abapgit_exception . CLASS-METHODS open_se80 IMPORTING !iv_package TYPE devclass RAISING zcx_abapgit_exception . CLASS-METHODS transport_to_branch IMPORTING !iv_repository_key TYPE zif_abapgit_persistence=>ty_value RAISING zcx_abapgit_exception zcx_abapgit_cancel . CLASS-METHODS gui_deserialize IMPORTING !io_repo TYPE REF TO zcl_abapgit_repo RAISING zcx_abapgit_exception . PRIVATE SECTION. CLASS-METHODS popup_overwrite CHANGING !ct_overwrite TYPE zif_abapgit_definitions=>ty_overwrite_tt RAISING zcx_abapgit_exception zcx_abapgit_cancel . CLASS-METHODS popup_package_overwrite CHANGING !ct_overwrite TYPE zif_abapgit_definitions=>ty_overwrite_tt RAISING zcx_abapgit_exception zcx_abapgit_cancel . ENDCLASS. CLASS ZCL_ABAPGIT_SERVICES_REPO IMPLEMENTATION. METHOD gui_deserialize. DATA: ls_checks TYPE zif_abapgit_definitions=>ty_deserialize_checks, lt_requirements TYPE zif_abapgit_dot_abapgit=>ty_requirement_tt. * find troublesome objects ls_checks = io_repo->deserialize_checks( ). * and let the user decide what to do TRY. popup_overwrite( CHANGING ct_overwrite = ls_checks-overwrite ). popup_package_overwrite( CHANGING ct_overwrite = ls_checks-warning_package ). IF ls_checks-requirements-met = 'N'. lt_requirements = io_repo->get_dot_abapgit( )->get_data( )-requirements. zcl_abapgit_requirement_helper=>requirements_popup( lt_requirements ). ls_checks-requirements-decision = 'Y'. ENDIF. IF ls_checks-transport-required = abap_true. ls_checks-transport-transport = zcl_abapgit_ui_factory=>get_popups( )->popup_transport_request( is_transport_type = ls_checks-transport-type ). ENDIF. CATCH zcx_abapgit_cancel. RETURN. ENDTRY. * and pass decisions to deserialize io_repo->deserialize( ls_checks ). ENDMETHOD. METHOD new_offline. DATA: lo_repo TYPE REF TO zcl_abapgit_repo, ls_popup TYPE zif_abapgit_popups=>ty_popup. ls_popup = zcl_abapgit_ui_factory=>get_popups( )->repo_new_offline( ). IF ls_popup-cancel = abap_true. RAISE EXCEPTION TYPE zcx_abapgit_cancel. ENDIF. lo_repo = zcl_abapgit_repo_srv=>get_instance( )->new_offline( iv_url = ls_popup-url iv_package = ls_popup-package ). zcl_abapgit_persistence_user=>get_instance( )->set_repo_show( lo_repo->get_key( ) ). "" Set default repo for user toggle_favorite( lo_repo->get_key( ) ). COMMIT WORK AND WAIT. ENDMETHOD. METHOD new_online. DATA: ls_popup TYPE zif_abapgit_popups=>ty_popup. ls_popup = zcl_abapgit_ui_factory=>get_popups( )->repo_popup( iv_url ). IF ls_popup-cancel = abap_true. RAISE EXCEPTION TYPE zcx_abapgit_cancel. ENDIF. ro_repo = zcl_abapgit_repo_srv=>get_instance( )->new_online( iv_url = ls_popup-url iv_branch_name = ls_popup-branch_name iv_package = ls_popup-package ). toggle_favorite( ro_repo->get_key( ) ). * Set default repo for user zcl_abapgit_persistence_user=>get_instance( )->set_repo_show( ro_repo->get_key( ) ). COMMIT WORK. ENDMETHOD. METHOD open_se80. CALL FUNCTION 'RS_TOOL_ACCESS' EXPORTING operation = 'SHOW' in_new_window = abap_true object_name = iv_package object_type = 'DEVC' with_objectlist = abap_true. ENDMETHOD. METHOD popup_overwrite. DATA: lt_columns TYPE stringtab, lt_selected LIKE ct_overwrite, lv_column LIKE LINE OF lt_columns, li_popups TYPE REF TO zif_abapgit_popups. FIELD-SYMBOLS: LIKE LINE OF ct_overwrite. IF lines( ct_overwrite ) = 0. RETURN. ENDIF. lv_column = 'OBJ_TYPE'. INSERT lv_column INTO TABLE lt_columns. lv_column = 'OBJ_NAME'. INSERT lv_column INTO TABLE lt_columns. li_popups = zcl_abapgit_ui_factory=>get_popups( ). li_popups->popup_to_select_from_list( EXPORTING it_list = ct_overwrite iv_header_text = |The following Objects have been modified locally.| && | Select the Objects which should be overwritten.| iv_select_column_text = 'Overwrite?' it_columns_to_display = lt_columns IMPORTING et_list = lt_selected ). LOOP AT ct_overwrite ASSIGNING . READ TABLE lt_selected WITH KEY obj_type = -obj_type obj_name = -obj_name TRANSPORTING NO FIELDS. IF sy-subrc = 0. -decision = 'Y'. ELSE. -decision = 'N'. ENDIF. ENDLOOP. ENDMETHOD. METHOD popup_package_overwrite. DATA: lv_question TYPE c LENGTH 200, lv_answer TYPE c. FIELD-SYMBOLS: LIKE LINE OF ct_overwrite. IF lines( ct_overwrite ) = 0. RETURN. ENDIF. LOOP AT ct_overwrite ASSIGNING . CONCATENATE 'Overwrite object' -obj_type -obj_name 'from package' -devclass INTO lv_question SEPARATED BY space. ""#EC NOTEXT lv_answer = zcl_abapgit_ui_factory=>get_popups( )->popup_to_confirm( iv_titlebar = 'Warning' iv_text_question = lv_question iv_text_button_1 = 'Ok' iv_icon_button_1 = 'ICON_DELETE' iv_text_button_2 = 'Cancel' iv_icon_button_2 = 'ICON_CANCEL' iv_default_button = '2' iv_display_cancel_button = abap_false ). ""#EC NOTEXT IF lv_answer = '2'. RAISE EXCEPTION TYPE zcx_abapgit_cancel. ENDIF. * todo, let the user decide yes/no/cancel -decision = 'Y'. ENDLOOP. ENDMETHOD. METHOD purge. DATA: lt_tadir TYPE zif_abapgit_definitions=>ty_tadir_tt, lv_answer TYPE c LENGTH 1, lo_repo TYPE REF TO zcl_abapgit_repo, lv_package TYPE devclass, lv_question TYPE c LENGTH 100, ls_checks TYPE zif_abapgit_definitions=>ty_delete_checks. lo_repo = zcl_abapgit_repo_srv=>get_instance( )->get( iv_key ). lv_package = lo_repo->get_package( ). lt_tadir = zcl_abapgit_factory=>get_tadir( )->read( lv_package ). IF lines( lt_tadir ) > 0. lv_question = |This will DELETE all objects in package { lv_package } ({ lines( lt_tadir ) } objects) from the system|. ""#EC NOTEXT lv_answer = zcl_abapgit_ui_factory=>get_popups( )->popup_to_confirm( iv_titlebar = 'Uninstall' iv_text_question = lv_question iv_text_button_1 = 'Delete' iv_icon_button_1 = 'ICON_DELETE' iv_text_button_2 = 'Cancel' iv_icon_button_2 = 'ICON_CANCEL' iv_default_button = '2' iv_display_cancel_button = abap_false ). ""#EC NOTEXT IF lv_answer = '2'. RAISE EXCEPTION TYPE zcx_abapgit_cancel. ENDIF. ENDIF. ls_checks = lo_repo->delete_checks( ). IF ls_checks-transport-required = abap_true. ls_checks-transport-transport = zcl_abapgit_ui_factory=>get_popups( )->popup_transport_request( ls_checks-transport-type ). ENDIF. zcl_abapgit_repo_srv=>get_instance( )->purge( io_repo = lo_repo is_checks = ls_checks ). COMMIT WORK. ENDMETHOD. METHOD refresh. zcl_abapgit_repo_srv=>get_instance( )->get( iv_key )->refresh( ). ENDMETHOD. METHOD refresh_local_checksums. DATA: lv_answer TYPE c, lv_question TYPE string, lo_repo TYPE REF TO zcl_abapgit_repo. IF zcl_abapgit_auth=>is_allowed( zif_abapgit_auth=>gc_authorization-update_local_checksum ) = abap_false. zcx_abapgit_exception=>raise( 'Not authorized' ). ENDIF. lo_repo = zcl_abapgit_repo_srv=>get_instance( )->get( iv_key ). lv_question = 'This will rebuild and overwrite local repo checksums.'. IF lo_repo->is_offline( ) = abap_false. lv_question = lv_question && ' The logic: if local and remote file differs then:' && ' if remote branch is ahead then assume changes are remote,' && ' else (branches are equal) assume changes are local.' && ' This will lead to incorrect state for files changed on both sides.' && ' Please make sure you don''t have ones like that.'. ENDIF. lv_answer = zcl_abapgit_ui_factory=>get_popups( )->popup_to_confirm( iv_titlebar = 'Warning' iv_text_question = lv_question iv_text_button_1 = 'OK' iv_icon_button_1 = 'ICON_DELETE' iv_text_button_2 = 'Cancel' iv_icon_button_2 = 'ICON_CANCEL' iv_default_button = '2' iv_display_cancel_button = abap_false ). ""#EC NOTEXT IF lv_answer = '2'. RAISE EXCEPTION TYPE zcx_abapgit_cancel. ENDIF. lo_repo->rebuild_local_checksums( ). COMMIT WORK AND WAIT. ENDMETHOD. METHOD remote_attach. DATA: ls_popup TYPE zif_abapgit_popups=>ty_popup, lo_repo TYPE REF TO zcl_abapgit_repo_online. ls_popup = zcl_abapgit_ui_factory=>get_popups( )->repo_popup( iv_title = 'Attach repo to remote ...' iv_url = '' iv_package = zcl_abapgit_repo_srv=>get_instance( )->get( iv_key )->get_package( ) iv_freeze_package = abap_true ). IF ls_popup-cancel = abap_true. RAISE EXCEPTION TYPE zcx_abapgit_cancel. ENDIF. zcl_abapgit_repo_srv=>get_instance( )->switch_repo_type( iv_key = iv_key iv_offline = abap_false ). lo_repo ?= zcl_abapgit_repo_srv=>get_instance( )->get( iv_key ). lo_repo->set_url( ls_popup-url ). lo_repo->set_branch_name( ls_popup-branch_name ). COMMIT WORK. ENDMETHOD. METHOD remote_change. DATA: ls_popup TYPE zif_abapgit_popups=>ty_popup, lo_repo TYPE REF TO zcl_abapgit_repo_online. lo_repo ?= zcl_abapgit_repo_srv=>get_instance( )->get( iv_key ). ls_popup = zcl_abapgit_ui_factory=>get_popups( )->repo_popup( iv_title = 'Change repo remote ...' iv_url = lo_repo->get_url( ) iv_package = lo_repo->get_package( ) iv_freeze_package = abap_true ). IF ls_popup-cancel = abap_true. RAISE EXCEPTION TYPE zcx_abapgit_cancel. ENDIF. lo_repo ?= zcl_abapgit_repo_srv=>get_instance( )->get( iv_key ). lo_repo->set_url( ls_popup-url ). lo_repo->set_branch_name( ls_popup-branch_name ). COMMIT WORK. ENDMETHOD. METHOD remote_detach. DATA: lv_answer TYPE c LENGTH 1. lv_answer = zcl_abapgit_ui_factory=>get_popups( )->popup_to_confirm( iv_titlebar = 'Make repository OFF-line' iv_text_question = 'This will detach the repo from remote and make it OFF-line' iv_text_button_1 = 'Make OFF-line' iv_icon_button_1 = 'ICON_WF_UNLINK' iv_text_button_2 = 'Cancel' iv_icon_button_2 = 'ICON_CANCEL' iv_default_button = '2' iv_display_cancel_button = abap_false ). ""#EC NOTEXT IF lv_answer = '2'. RAISE EXCEPTION TYPE zcx_abapgit_cancel. ENDIF. zcl_abapgit_repo_srv=>get_instance( )->switch_repo_type( iv_key = iv_key iv_offline = abap_true ). COMMIT WORK. ENDMETHOD. METHOD remove. DATA: lv_answer TYPE c LENGTH 1, lo_repo TYPE REF TO zcl_abapgit_repo, lv_package TYPE devclass, lv_question TYPE c LENGTH 200. lo_repo = zcl_abapgit_repo_srv=>get_instance( )->get( iv_key ). lv_package = lo_repo->get_package( ). lv_question = |This will remove the repository reference to the package { lv_package }. All objects will safely remain in the system.|. lv_answer = zcl_abapgit_ui_factory=>get_popups( )->popup_to_confirm( iv_titlebar = 'Remove' iv_text_question = lv_question iv_text_button_1 = 'Remove' iv_icon_button_1 = 'ICON_WF_UNLINK' iv_text_button_2 = 'Cancel' iv_icon_button_2 = 'ICON_CANCEL' iv_default_button = '2' iv_display_cancel_button = abap_false ). ""#EC NOTEXT IF lv_answer = '2'. RAISE EXCEPTION TYPE zcx_abapgit_cancel. ENDIF. zcl_abapgit_repo_srv=>get_instance( )->delete( lo_repo ). COMMIT WORK. ENDMETHOD. METHOD toggle_favorite. zcl_abapgit_persistence_user=>get_instance( )->toggle_favorite( iv_key ). ENDMETHOD. METHOD transport_to_branch. DATA: lo_repository TYPE REF TO zcl_abapgit_repo_online, lo_transport_to_branch TYPE REF TO zcl_abapgit_transport_2_branch, lt_transport_headers TYPE trwbo_request_headers, lt_transport_objects TYPE zif_abapgit_definitions=>ty_tadir_tt, ls_transport_to_branch TYPE zif_abapgit_definitions=>ty_transport_to_branch. IF zcl_abapgit_auth=>is_allowed( zif_abapgit_auth=>gc_authorization-transport_to_branch ) = abap_false. zcx_abapgit_exception=>raise( 'Not authorized' ). ENDIF. lo_repository ?= zcl_abapgit_repo_srv=>get_instance( )->get( iv_repository_key ). lt_transport_headers = zcl_abapgit_ui_factory=>get_popups( )->popup_to_select_transports( ). lt_transport_objects = zcl_abapgit_transport=>to_tadir( lt_transport_headers ). IF lt_transport_objects IS INITIAL. zcx_abapgit_exception=>raise( 'Canceled or List of objects is empty ' ). ENDIF. ls_transport_to_branch = zcl_abapgit_ui_factory=>get_popups( )->popup_to_create_transp_branch( lt_transport_headers ). CREATE OBJECT lo_transport_to_branch. lo_transport_to_branch->create( io_repository = lo_repository is_transport_to_branch = ls_transport_to_branch it_transport_objects = lt_transport_objects ). ENDMETHOD. ENDCLASS. ",4134,False,962.9886014554163,median "FUNCTION-POOL zgtt_sof. ""MESSAGE-ID .. TYPE-POOLS: trxas, abap. TYPES: BEGIN OF gtys_vtts_vtsp, tsrfo TYPE tsrfo. INCLUDE STRUCTURE vtspvb. TYPES: END OF gtys_vtts_vtsp. TYPES: gtyt_vtts_vtsp TYPE STANDARD TABLE OF gtys_vtts_vtsp. TYPES: gtyt_message_log TYPE STANDARD TABLE OF bapiret2. DATA: gv_evtcnt TYPE /saptrx/evtcnt. ""#EC NEEDED CONSTANTS: * General gc_true TYPE boole_d VALUE 'X', gc_false TYPE boole_d VALUE ' ', gc_true_condition TYPE char1 VALUE 'T', gc_false_condition TYPE char1 VALUE 'F', gc_insert TYPE updkz_d VALUE 'I', gc_update TYPE updkz_d VALUE 'U', gc_delete TYPE updkz_d VALUE 'D', gc_aot_yn_ote TYPE /saptrx/aotype VALUE 'YN_OTE', gc_complete TYPE char1 VALUE 'C', gc_partyp_cntl TYPE /saptrx/aspartyp VALUE 'C', gc_partyp_evt TYPE /saptrx/aspartyp VALUE ' ', gc_act_set TYPE /saptrx/action VALUE 'S', gc_act_change TYPE /saptrx/action VALUE 'C', gc_datacs_dlv TYPE /saptrx/data_code_set VALUE 'DLV', gc_datacs_bill TYPE /saptrx/data_code_set VALUE 'BILL', gc_msg_class TYPE symsgid VALUE '/SAPTRX/ASC', gc_msg_type_e TYPE bapi_mtype VALUE 'E', gc_msg_val_aot TYPE symsgv VALUE 'AOT', gc_msg_val_et TYPE symsgv VALUE 'ET', gc_msg_no_087 TYPE symsgno VALUE '087', gc_msg_no_088 TYPE symsgno VALUE '088', * Business Process Type gc_bpt_sales_order_header_new TYPE /saptrx/strucdataname VALUE 'SALES_ORDER_HEADER_NEW', gc_bpt_sales_order_header_old TYPE /saptrx/strucdataname VALUE 'SALES_ORDER_HEADER_OLD', gc_bpt_sales_order_items_new TYPE /saptrx/strucdataname VALUE 'SALES_ORDER_ITEMS_NEW', gc_bpt_sales_order_items_old TYPE /saptrx/strucdataname VALUE 'SALES_ORDER_ITEMS_OLD', gc_bpt_schedule_line_item_new TYPE /saptrx/strucdataname VALUE 'SCHEDULE_LINE_ITEMS_NEW', gc_bpt_schedule_line_item_old TYPE /saptrx/strucdataname VALUE 'SCHEDULE_LINE_ITEMS_OLD', gc_bpt_business_data_new TYPE /saptrx/strucdataname VALUE 'BUSINESS_DATA_NEW', gc_bpt_business_data_old TYPE /saptrx/strucdataname VALUE 'BUSINESS_DATA_OLD', gc_bpt_partners_new TYPE /saptrx/strucdataname VALUE 'PARTNERS_NEW', gc_bpt_partners_old TYPE /saptrx/strucdataname VALUE 'PARTNERS_OLD', gc_bpt_header_status_new TYPE /saptrx/strucdataname VALUE 'HEADER_STATUS_NEW', gc_bpt_header_status_old TYPE /saptrx/strucdataname VALUE 'HEADER_STATUS_OLD', gc_bpt_item_status_new TYPE /saptrx/strucdataname VALUE 'ITEM_STATUS_NEW', gc_bpt_item_status_old TYPE /saptrx/strucdataname VALUE 'ITEM_STATUS_OLD', gc_bpt_document_flow_new TYPE /saptrx/strucdataname VALUE 'DOCUMENT_FLOW_NEW', gc_bpt_document_flow_old TYPE /saptrx/strucdataname VALUE 'DOCUMENT_FLOW_OLD', gc_bpt_delivery_item_new TYPE /saptrx/strucdataname VALUE 'DELIVERY_ITEM_NEW', gc_bpt_delivery_item_old TYPE /saptrx/strucdataname VALUE 'DELIVERY_ITEM_OLD', gc_bpt_delivery_item_stat_new TYPE /saptrx/strucdataname VALUE 'DELIVERY_ITEM_STATUS_NEW', gc_bpt_delivery_item_stat_old TYPE /saptrx/strucdataname VALUE 'DELIVERY_ITEM_STATUS_OLD', gc_bpt_invoice_item_new TYPE /saptrx/strucdataname VALUE 'INVOICE_ITEM_NEW', gc_bpt_invoice_header_new TYPE /saptrx/strucdataname VALUE 'INVOICE_HEADER_NEW', gc_bpt_invoice_header_old TYPE /saptrx/strucdataname VALUE 'INVOICE_HEADER_OLD', gc_bpt_cleared_item TYPE /saptrx/strucdataname VALUE 'CLEARED_ITEM', gc_bpt_purchase_item_new TYPE /saptrx/strucdataname VALUE 'PURCHASE_ITEM_NEW', gc_bpt_purchase_header_new TYPE /saptrx/strucdataname VALUE 'PURCHASE_ORDER_HEADER_NEW', gc_bpt_purchase_header_old TYPE /saptrx/strucdataname VALUE 'PURCHASE_ORDER_HEADER_OLD', gc_bpt_po_account_assign_new TYPE /saptrx/strucdataname VALUE 'PO_ACCOUNT_ASSIGNMENT_NEW', gc_bpt_po_sched_line_item_new TYPE /saptrx/strucdataname VALUE 'PO_SCHED_LINE_ITEM_NEW', gc_bpt_po_sched_line_item_old TYPE /saptrx/strucdataname VALUE 'PO_SCHED_LINE_ITEM_OLD', gc_bpt_shipment_header_new TYPE /saptrx/strucdataname VALUE 'SHIPMENT_HEADER_NEW', gc_bpt_shipment_header_old TYPE /saptrx/strucdataname VALUE 'SHIPMENT_HEADER_OLD', gc_bpt_shipment_item_new TYPE /saptrx/strucdataname VALUE 'SHIPMENT_ITEM_NEW', gc_bpt_shipment_item_old TYPE /saptrx/strucdataname VALUE 'SHIPMENT_ITEM_OLD', gc_bpt_delivery_item TYPE /saptrx/strucdataname VALUE 'DELIVERY_ITEM', gc_bpt_shipment_leg_new TYPE /saptrx/strucdataname VALUE 'SHIPMENT_LEG_NEW', gc_bpt_shipment_leg_old TYPE /saptrx/strucdataname VALUE 'SHIPMENT_LEG_OLD', gc_bpt_shipment_item_leg_new TYPE /saptrx/strucdataname VALUE 'SHIPMENT_ITEM_LEG_NEW', gc_bpt_shipment_item_leg_old TYPE /saptrx/strucdataname VALUE 'SHIPMENT_ITEM_LEG_OLD', gc_bpt_material_segment TYPE /saptrx/strucdataname VALUE 'MATERIAL_SEGMENT', gc_bpt_material_header TYPE /saptrx/strucdataname VALUE 'MATERIAL_HEADER', gc_bpt_wo_header_new TYPE /saptrx/strucdataname VALUE 'WO_HEADER_NEW', gc_bpt_wo_header_old TYPE /saptrx/strucdataname VALUE 'WO_HEADER_OLD', gc_bpt_wo_status_new TYPE /saptrx/strucdataname VALUE 'WO_STATUS_NEW', gc_bpt_wo_status_old TYPE /saptrx/strucdataname VALUE 'WO_STATUS_OLD', gc_bpt_clearing_doc_header TYPE /saptrx/strucdataname VALUE 'CLEARING_DOC_HEADER', * Event ID gc_evtid_yn_so_bill_blk TYPE /saptrx/ev_evtid VALUE 'YN_SO_BILL_BLK', gc_evtid_yn_so_dlv_blk TYPE /saptrx/ev_evtid VALUE 'YN_SO_DLV_BLK', gc_evtid_yn_so_reject TYPE /saptrx/ev_evtid VALUE 'YN_SO_REJECT', gc_evtid_yn_dlv_gi TYPE /saptrx/ev_evtid VALUE 'YN_DLV_GI', gc_evtid_yn_shpmt_plan TYPE /saptrx/ev_evtid VALUE 'YN_SHPMT_PLAN', gc_evtid_yn_shpmt_start TYPE /saptrx/ev_evtid VALUE 'YN_SHPMT_START', gc_evtid_yn_shpmt_end TYPE /saptrx/ev_evtid VALUE 'YN_SHPMT_END', gc_evtid_yn_fi_payment TYPE /saptrx/ev_evtid VALUE 'YN_FI_PAYMENT', * Additional constants D2O gc_trxcod_yn_so_header TYPE /saptrx/trxcod VALUE 'YN_SO_HEADER', gc_evtid_yn_so_ready TYPE /saptrx/ev_evtid VALUE 'YN_SO_READY', gc_evtid_yn_so_create TYPE /saptrx/ev_evtid VALUE 'YN_SO_CREATE', gc_evtid_yn_so_bill_unblk TYPE /saptrx/ev_evtid VALUE 'YN_SO_BILL_UNBLK', gc_evtid_yn_so_dlv_unblk TYPE /saptrx/ev_evtid VALUE 'YN_SO_DLV_UNBLK', gc_evtid_yn_dlv_create TYPE /saptrx/ev_evtid VALUE 'YN_SO_DLV_CREATE', gc_bpt_delivery_header_new TYPE /saptrx/strucdataname VALUE 'DELIVERY_HEADER_NEW', gc_bpt_delivery_header_old TYPE /saptrx/strucdataname VALUE 'DELIVERY_HEADER_OLD', gc_bpt_delivery_hdrstatus_new TYPE /saptrx/strucdataname VALUE 'DELIVERY_HDR_STATUS_NEW', gc_bpt_delivery_hdrstatus_old TYPE /saptrx/strucdataname VALUE 'DELIVERY_HDR_STATUS_OLD', gc_aot_zn_ote TYPE /saptrx/aotype VALUE 'ZN_OTE', gc_partial_dlv TYPE char1 VALUE 'B', * Tracking Code set gc_trxcod_yn_so_item TYPE /saptrx/trxcod VALUE 'YN_SO_ITEM', gc_trxcod_yn_dlv_no TYPE /saptrx/trxcod VALUE 'YN_DLV_NO', gc_trxcod_yn_bill_no TYPE /saptrx/trxcod VALUE 'YN_BILL_NO', gc_trxcod_yn_shpmt_no TYPE /saptrx/trxcod VALUE 'YN_SHPMT_NO', * Control Parameter Name gc_cp_yn_so_bl_blk_ind TYPE /saptrx/paramname VALUE 'YN_SO_BL_BLK_IND', gc_cp_yn_so_dl_blk_ind TYPE /saptrx/paramname VALUE 'YN_SO_DL_BLK_IND', gc_cp_yn_so_dl_blk_full TYPE /saptrx/paramname VALUE 'YN_SO_FULL_DL_BLK_IND', gc_cp_yn_so_dl_compl TYPE /saptrx/paramname VALUE 'YN_SO_DL_COMPL', gc_cp_yn_so_incoterm1 TYPE /saptrx/paramname VALUE 'YN_SO_INCOTERM1', gc_cp_yn_so_incotermloc1 TYPE /saptrx/paramname VALUE 'YN_SO_INCOTERM_LOCATION', gc_cp_yn_so_incotermversion TYPE /saptrx/paramname VALUE 'YN_SO_INCOTERM_VERSION', gc_cp_yn_so_incoterm2 TYPE /saptrx/paramname VALUE 'YN_SO_INCOTERM2', gc_cp_yn_so_po_no TYPE /saptrx/paramname VALUE 'YN_SO_PO_NO', gc_cp_yn_so_po_date TYPE /saptrx/paramname VALUE 'YN_SO_PO_DATE', gc_cp_yn_so_bill_date TYPE /saptrx/paramname VALUE 'YN_SO_BILL_DATE', gc_cp_yn_so_cust_grp TYPE /saptrx/paramname VALUE 'YN_SO_CUST_GRP', gc_cp_yn_so_ship_to TYPE /saptrx/paramname VALUE 'YN_SO_SHIPTO', gc_cp_yn_so_ship_to_txt TYPE /saptrx/paramname VALUE 'YN_SO_SHIPTO_TXT', gc_cp_yn_so_sold_to TYPE /saptrx/paramname VALUE 'YN_SO_SOLDTO', gc_cp_yn_so_sold_to_txt TYPE /saptrx/paramname VALUE 'YN_SO_SOLDTO_TXT', gc_cp_yn_so_sold_to_mail TYPE /saptrx/paramname VALUE 'YN_SO_SOLDTO_MAIL', gc_cp_yn_so_bill_to TYPE /saptrx/paramname VALUE 'YN_SO_BILLTO', gc_cp_yn_so_bill_to_txt TYPE /saptrx/paramname VALUE 'YN_SO_BILLTO_TXT', gc_cp_yn_so_payer TYPE /saptrx/paramname VALUE 'YN_SO_PAYER', gc_cp_yn_so_payer_txt TYPE /saptrx/paramname VALUE 'YN_SO_PAYER_TXT', gc_cp_yn_so_fwd TYPE /saptrx/paramname VALUE 'YN_SO_FWD', gc_cp_yn_so_fwd_txt TYPE /saptrx/paramname VALUE 'YN_SO_FWD_TXT', gc_cp_yn_so_full_dlv TYPE /saptrx/paramname VALUE 'YN_SO_FULL_DLV_IND', gc_cp_yn_so_subseq_doc_ind TYPE /saptrx/paramname VALUE 'YN_SO_SUBSEQ_DOC_IND', gc_cp_yn_shpmt_no TYPE /saptrx/paramname VALUE 'YN_SHPMT_NO', gc_cp_yn_shpmt_cont_id TYPE /saptrx/paramname VALUE 'YN_SHPMT_CONT_ID', gc_cp_yn_account_no TYPE /saptrx/paramname VALUE 'YN_ACCOUNT_NO', gc_cp_yn_so_no TYPE /saptrx/paramname VALUE 'YN_SO_NO', gc_cp_yn_so_item_no TYPE /saptrx/paramname VALUE 'YN_SO_ITEM_NO', gc_cp_yn_material_no TYPE /saptrx/paramname VALUE 'YN_MATERIAL_NO', gc_cp_yn_material_txt TYPE /saptrx/paramname VALUE 'YN_MATERIAL_TXT', gc_cp_yn_plant TYPE /saptrx/paramname VALUE 'YN_PLANT', gc_cp_yn_quantity TYPE /saptrx/paramname VALUE 'YN_QUANTITY', gc_cp_yn_pick_quantity TYPE /saptrx/paramname VALUE 'YN_PICK_QUANTITY', gc_cp_yn_pack_quantity TYPE /saptrx/paramname VALUE 'YN_PACK_QUANTITY', gc_cp_yn_pod_quantity TYPE /saptrx/paramname VALUE 'YN_POD_QUANTITY', gc_cp_yn_qty_unit TYPE /saptrx/paramname VALUE 'YN_QTY_UNIT', gc_cp_yn_ean_upc TYPE /saptrx/paramname VALUE 'YN_EAN_UPC', gc_cp_yn_net_value TYPE /saptrx/paramname VALUE 'YN_NET_VALUE', gc_cp_yn_reject_status TYPE /saptrx/paramname VALUE 'YN_REJECTION_STATUS', gc_cp_yn_net_value_curr TYPE /saptrx/paramname VALUE 'YN_NET_VALUE_CURRENCY', gc_cp_yn_doc_date TYPE /saptrx/paramname VALUE 'YN_DOCUMENT_DATE', gc_cp_yn_act_datetime TYPE /saptrx/paramname VALUE 'ACTUAL_BUSINESS_DATETIME', gc_cp_yn_act_timezone TYPE /saptrx/paramname VALUE 'ACTUAL_BUSINESS_TIMEZONE', gc_cp_yn_acttec_datetime TYPE /saptrx/paramname VALUE 'ACTUAL_TECHNICAL_DATETIME', gc_cp_yn_acttec_timezone TYPE /saptrx/paramname VALUE 'ACTUAL_TECHNICAL_TIMEZONE', gc_cp_yn_de_no TYPE /saptrx/paramname VALUE 'YN_DLV_NO', gc_cp_yn_de_item_no TYPE /saptrx/paramname VALUE 'YN_DLV_ITEM_NO', gc_cp_yn_de_ship_to TYPE /saptrx/paramname VALUE 'YN_DLV_SHIPTO', gc_cp_yn_de_plndelivery_date TYPE /saptrx/paramname VALUE 'YN_DLV_PLAN_DELIVERY_DATE', gc_cp_yn_de_tot_weight TYPE /saptrx/paramname VALUE 'YN_DLV_TOTAL_WEIGHT', gc_cp_yn_de_gross_weight TYPE /saptrx/paramname VALUE 'YN_DLV_GROSS_WEIGHT', gc_cp_yn_de_net_weight TYPE /saptrx/paramname VALUE 'YN_DLV_NET_WEIGHT', gc_cp_yn_de_tot_weight_uom TYPE /saptrx/paramname VALUE 'YN_DLV_TOTAL_WEIGHT_UOM', gc_cp_yn_de_gross_weight_uom TYPE /saptrx/paramname VALUE 'YN_DLV_GROSS_WEIGHT_UOM', gc_cp_yn_de_vol TYPE /saptrx/paramname VALUE 'YN_DLV_VOLUME', gc_cp_yn_de_vol_uom TYPE /saptrx/paramname VALUE 'YN_DLV_VOLUME_UOM', gc_cp_yn_dgoods TYPE /saptrx/paramname VALUE 'YN_DLV_DANGEROUS_GOODS', gc_cp_yn_de_pick_status TYPE /saptrx/paramname VALUE 'YN_DLV_PICK_STATUS', gc_cp_yn_de_pack_status TYPE /saptrx/paramname VALUE 'YN_DLV_PACK_STATUS', gc_cp_yn_de_trans_status TYPE /saptrx/paramname VALUE 'YN_DLV_TRANSPORTATION_STATUS', gc_cp_yn_de_gi_status TYPE /saptrx/paramname VALUE 'YN_DLV_GOODS_ISSUE_STATUS', gc_cp_yn_de_pod_status TYPE /saptrx/paramname VALUE 'YN_DLV_POD_STATUS', gc_cp_yn_de_asso_soitem_no TYPE /saptrx/paramname VALUE 'YN_DLV_ASSO_SOITEM_NO', gc_cp_yn_de_warehouse_no TYPE /saptrx/paramname VALUE 'YN_DLV_WAREHOUSE_NO', gc_cp_yn_de_door_no TYPE /saptrx/paramname VALUE 'YN_DLV_DOOR_NO', gc_cp_yn_de_door_txt TYPE /saptrx/paramname VALUE 'YN_DLV_DOOR_TEXT', gc_cp_yn_de_shp_pnt TYPE /saptrx/paramname VALUE 'YN_DLV_SHIPPING_POINT', gc_cp_yn_de_shp_pnt_loctype TYPE /saptrx/paramname VALUE 'YN_DLV_DEPARTURE_LOCATION_TYPE', gc_cp_yn_de_shp_addr TYPE /saptrx/paramname VALUE 'YN_DLV_DEPARTURE_ADDRESS', gc_cp_yn_de_shp_countryiso TYPE /saptrx/paramname VALUE 'YN_DLV_DEPARTURE_COUNTRY', gc_cp_yn_de_dest TYPE /saptrx/paramname VALUE 'YN_DLV_DESTINATION', gc_cp_yn_de_dest_loctype TYPE /saptrx/paramname VALUE 'YN_DLV_DESTINATION_LOCATION_TYPE', gc_cp_yn_de_dest_addr TYPE /saptrx/paramname VALUE 'YN_DLV_DESTINATION_ADDRESS', gc_cp_yn_de_dest_countryiso TYPE /saptrx/paramname VALUE 'YN_DLV_DESTINATION_COUNTRY', gc_cp_yn_de_dest_email TYPE /saptrx/paramname VALUE 'YN_DLV_DESTINATION_EMAIL', gc_cp_yn_de_dest_tele TYPE /saptrx/paramname VALUE 'YN_DLV_DESTINATION_TELEPHONE', gc_cp_yn_de_bol_no TYPE /saptrx/paramname VALUE 'YN_DLV_BILL_OF_LADING', gc_cp_yn_de_inco1 TYPE /saptrx/paramname VALUE 'YN_DLV_INCOTERMS', gc_cp_yn_de_inco2_l TYPE /saptrx/paramname VALUE 'YN_DLV_INCO_LOCATION', gc_cp_yn_de_incov TYPE /saptrx/paramname VALUE 'YN_DLV_INCO_VERSION', gc_cp_yn_shp_no TYPE /saptrx/paramname VALUE 'YN_SHP_NO', gc_cp_yn_shp_sa_erp_id TYPE /saptrx/paramname VALUE 'YN_SHP_SA_ERP_ID', gc_cp_yn_shp_sa_lbn_id TYPE /saptrx/paramname VALUE 'YN_SHP_SA_LBN_ID', gc_cp_yn_shp_contain_dg TYPE /saptrx/paramname VALUE 'YN_SHP_CONTAIN_DGOODS', gc_cp_yn_shp_inco1 TYPE /saptrx/paramname VALUE 'YN_SHP_INCOTERMS', gc_cp_yn_shp_fa_track_id TYPE /saptrx/paramname VALUE 'YN_SHP_FA_TRACKING_ID', gc_cp_yn_shp_shipping_type TYPE /saptrx/paramname VALUE 'YN_SHP_SHIPPING_TYPE', gc_cp_yn_shp_trans_mode TYPE /saptrx/paramname VALUE 'YN_SHP_TRANSPORTATION_MODE', gc_cp_yn_shp_container_id TYPE /saptrx/paramname VALUE 'YN_SHP_CONTAINER_ID', gc_cp_yn_shp_truck_id TYPE /saptrx/paramname VALUE 'YN_SHP_TRUCK_ID', gc_cp_yn_shp_res_value TYPE /saptrx/paramname VALUE 'YN_SHP_TRACKED_RESOURCE_VALUE', gc_cp_yn_shp_res_id TYPE /saptrx/paramname VALUE 'YN_SHP_TRACKED_RESOURCE_ID', gc_cp_yn_shp_res_tp_id TYPE /saptrx/paramname VALUE 'YN_SHP_RESOURCE_TP_ID', gc_cp_yn_shp_res_tp_cnt TYPE /saptrx/paramname VALUE 'YN_SHP_RESOURCE_TP_LINE_COUNT', gc_cp_yn_shp_stops_line_cnt TYPE /saptrx/paramname VALUE 'YN_SHP_LINE_COUNT', gc_cp_yn_shp_stops_stop_id TYPE /saptrx/paramname VALUE 'YN_SHP_STOP_ID', gc_cp_yn_shp_stops_ordinal_no TYPE /saptrx/paramname VALUE 'YN_SHP_ORDINAL_NO', gc_cp_yn_shp_stops_loc_cat TYPE /saptrx/paramname VALUE 'YN_SHP_LOC_CATEGORY', gc_cp_yn_shp_stops_loc_id TYPE /saptrx/paramname VALUE 'YN_SHP_LOC_ID', gc_cp_yn_shp_stops_loc_type TYPE /saptrx/paramname VALUE 'YN_SHP_LOC_TYPE', gc_cp_yn_shp_stops_load_pnt TYPE /saptrx/paramname VALUE 'YN_SHP_LOADING_POINT', gc_cp_yn_shp_stops_unload_pnt TYPE /saptrx/paramname VALUE 'YN_SHP_UNLOADING_POINT', gc_cp_yn_shp_stops_lgort TYPE /saptrx/paramname VALUE 'YN_SHP_STORAGE_LOCATION', gc_cp_yn_shp_warehouse_no TYPE /saptrx/paramname VALUE 'YN_SHP_WAREHOUSE_NO', gc_cp_yn_shp_gate_no TYPE /saptrx/paramname VALUE 'YN_SHP_GATE_NO', gc_cp_yn_shp_gate_txt TYPE /saptrx/paramname VALUE 'YN_SHP_GATE_TEXT', gc_cp_yn_shp_stage_seq TYPE /saptrx/paramname VALUE 'YN_SHP_STAGE_SEQUENCE', gc_cp_yn_shp_stops_pln_evt_dt TYPE /saptrx/paramname VALUE 'YN_SHP_STOP_PLAN_DATETIME', gc_cp_yn_shp_stops_pln_evt_tz TYPE /saptrx/paramname VALUE 'YN_SHP_STOP_PLAN_TIMEZONE', gc_cp_yn_shp_stop_id TYPE /saptrx/paramname VALUE 'YN_SHP_VP_STOP_ID', gc_cp_yn_shp_stop_id_ord_no TYPE /saptrx/paramname VALUE 'YN_SHP_VP_STOP_ORD_NO', gc_cp_yn_shp_stop_id_loc_id TYPE /saptrx/paramname VALUE 'YN_SHP_VP_STOP_LOC_ID', gc_cp_yn_shp_stop_id_loc_type TYPE /saptrx/paramname VALUE 'YN_SHP_VP_STOP_LOC_TYPE', gc_cp_yn_shp_departure_dt TYPE /saptrx/paramname VALUE 'YN_SHP_PLN_DEP_BUS_DATETIME', gc_cp_yn_shp_departure_tz TYPE /saptrx/paramname VALUE 'YN_SHP_PLN_DEP_BUS_TIMEZONE', gc_cp_yn_shp_departure_locid TYPE /saptrx/paramname VALUE 'YN_SHP_PLN_DEP_LOC_ID', gc_cp_yn_shp_departure_loctype TYPE /saptrx/paramname VALUE 'YN_SHP_PLN_DEP_LOC_TYPE', gc_cp_yn_shp_arrival_dt TYPE /saptrx/paramname VALUE 'YN_SHP_PLN_AR_BUS_DATETIME', gc_cp_yn_shp_arrival_tz TYPE /saptrx/paramname VALUE 'YN_SHP_PLN_AR_BUS_TIMEZONE', gc_cp_yn_shp_arrival_locid TYPE /saptrx/paramname VALUE 'YN_SHP_PLN_AR_LOC_ID', gc_cp_yn_shp_arrival_loctype TYPE /saptrx/paramname VALUE 'YN_SHP_PLN_AR_LOC_TYPE', gc_cp_yn_so_header_item_no TYPE /saptrx/paramname VALUE 'YN_SO_HDR_ITM_NO', gc_cp_yn_so_header_item_cnt TYPE /saptrx/paramname VALUE 'YN_SO_HDR_ITM_LINE_COUNT', gc_cp_yn_so_schedule_item_cnt TYPE /saptrx/paramname VALUE 'YN_SO_SCH_ITM_LINE_COUNT', gc_cp_yn_so_schedule_dlv_date TYPE /saptrx/paramname VALUE 'YN_SO_SCH_ITM_DLV_DATE', gc_cp_yn_so_schedule_conf_qty TYPE /saptrx/paramname VALUE 'YN_SO_SCH_ITM_CONF_QTY', gc_cp_yn_so_schedule_ordr_uom TYPE /saptrx/paramname VALUE 'YN_SO_SCH_ITM_ORDER_UOM', gc_cp_yn_de_header_item_no TYPE /saptrx/paramname VALUE 'YN_DLV_HDR_ITM_NO', gc_cp_yn_de_header_item_cnt TYPE /saptrx/paramname VALUE 'YN_DLV_HDR_ITM_LINE_COUNT', gc_cp_yn_shp_dlv_no TYPE /saptrx/paramname VALUE 'YN_SHP_HDR_DLV_NO', gc_cp_yn_shp_dlv_cnt TYPE /saptrx/paramname VALUE 'YN_SHP_HDR_DLV_LINE_COUNT', gc_cp_yn_shp_carrier_ref_type TYPE /saptrx/paramname VALUE 'YN_SHP_CARRIER_REF_TYPE', gc_cp_yn_shp_carrier_ref_value TYPE /saptrx/paramname VALUE 'YN_SHP_CARRIER_REF_VALUE', * Event Message Parameters gc_ev_yn_document TYPE /saptrx/paramname VALUE 'YN_DOCUMENT', * Sales Order gc_parvw_ag TYPE parvw VALUE 'AG', "" Sold-to Party gc_parvw_we TYPE parvw VALUE 'WE', "" Ship-to Party gc_parvw_re TYPE parvw VALUE 'RE', "" Bill-to Party gc_parvw_rg TYPE parvw VALUE 'RG', "" Payer gc_parvw_sp TYPE parvw VALUE 'SP', "" Forwarding Agent gc_cmgst_a TYPE cmgst VALUE 'A', gc_cmgst_b TYPE cmgst VALUE 'B', gc_cmgst_c TYPE cmgst VALUE 'C', gc_cmgst_d TYPE cmgst VALUE 'D', * Shipment gc_leg_ind_1 TYPE laufk VALUE '1', "" Preliminary Leg gc_leg_ind_2 TYPE laufk VALUE '2', "" Main leg gc_leg_ind_3 TYPE laufk VALUE '3', "" Subsequent leg gc_leg_ind_4 TYPE laufk VALUE '4', "" Direct Leg gc_tstyp_3 TYPE tstyp VALUE '3', "" Stage Category: Border * Production Order gc_aufty_pp TYPE auftyp VALUE '10', gc_stat_rel TYPE j_status VALUE 'I0002', * Purchase Order gc_vgart_we TYPE vgart VALUE 'WE', gc_del_loekz TYPE eloek VALUE 'L', gc_shkzg_s TYPE shkzg VALUE 'S', * Billing gc_rfbsk_c TYPE rfbsk VALUE 'C', gc_vbtyp_cancel TYPE vbtyp VALUE 'N', * Payment gc_koart_d TYPE koart VALUE 'D', gc_awtyp_vbrk TYPE awtyp VALUE 'VBRK'. ",6382,False,1619.2800370545376,median "// FB Alpha Vendetta / Crime Fighters 2 / Escape Kids driver module // Based on MAME driver by Ernesto Corvi #include ""tiles_generic.h"" #include ""z80_intf.h"" #include ""burn_ym2151.h"" #include ""konami_intf.h"" #include ""konamiic.h"" #include ""k053260.h"" #include ""eeprom.h"" static UINT8 *AllMem; static UINT8 *MemEnd; static UINT8 *AllRam; static UINT8 *RamEnd; static UINT8 *DrvKonROM; static UINT8 *DrvZ80ROM; static UINT8 *DrvGfxROM0; static UINT8 *DrvGfxROMExp0; static UINT8 *DrvGfxROM1; static UINT8 *DrvGfxROMExp1; static UINT8 *DrvSndROM; static UINT8 *DrvKonRAM; static UINT8 *DrvPalRAM; static UINT8 *DrvZ80RAM; static UINT32 *Palette; static UINT32 *DrvPalette; static UINT8 DrvRecalc; static UINT8 *nDrvBank; static INT32 videobank; static INT32 init_eeprom_count; static INT32 irq_enabled; static INT32 vblank = 0; static INT32 bankoffset; static INT32 bg_colorbase; static INT32 sprite_colorbase; static INT32 layer_colorbase[3]; static INT32 layerpri[3]; static UINT8 DrvJoy1[8]; static UINT8 DrvJoy2[8]; static UINT8 DrvJoy3[8]; static UINT8 DrvJoy4[8]; static UINT8 DrvJoy5[8]; static UINT8 DrvJoy6; static UINT8 DrvReset; static UINT8 DrvInputs[5]; static INT32 nCyclesDone[2]; static struct BurnInputInfo Vendet4pInputList[] = { {""P1 Coin"", BIT_DIGITAL, DrvJoy1 + 7, ""p1 coin"" }, {""P1 Up"", BIT_DIGITAL, DrvJoy1 + 2, ""p1 up"" }, {""P1 Down"", BIT_DIGITAL, DrvJoy1 + 3, ""p1 down"" }, {""P1 Left"", BIT_DIGITAL, DrvJoy1 + 1, ""p1 left"" }, {""P1 Right"", BIT_DIGITAL, DrvJoy1 + 0, ""p1 right"" }, {""P1 Button 1"", BIT_DIGITAL, DrvJoy1 + 4, ""p1 fire 1"" }, {""P1 Button 2"", BIT_DIGITAL, DrvJoy1 + 5, ""p1 fire 2"" }, {""P2 Coin"", BIT_DIGITAL, DrvJoy2 + 7, ""p2 coin"" }, {""P2 Up"", BIT_DIGITAL, DrvJoy2 + 2, ""p2 up"" }, {""P2 Down"", BIT_DIGITAL, DrvJoy2 + 3, ""p2 down"" }, {""P2 Left"", BIT_DIGITAL, DrvJoy2 + 1, ""p2 left"" }, {""P2 Right"", BIT_DIGITAL, DrvJoy2 + 0, ""p2 right"" }, {""P2 Button 1"", BIT_DIGITAL, DrvJoy2 + 4, ""p2 fire 1"" }, {""P2 Button 2"", BIT_DIGITAL, DrvJoy2 + 5, ""p2 fire 2"" }, {""P3 Coin"", BIT_DIGITAL, DrvJoy3 + 7, ""p3 coin"" }, {""P3 Up"", BIT_DIGITAL, DrvJoy3 + 2, ""p3 up"" }, {""P3 Down"", BIT_DIGITAL, DrvJoy3 + 3, ""p3 down"" }, {""P3 Left"", BIT_DIGITAL, DrvJoy3 + 1, ""p3 left"" }, {""P3 Right"", BIT_DIGITAL, DrvJoy3 + 0, ""p3 right"" }, {""P3 Button 1"", BIT_DIGITAL, DrvJoy3 + 4, ""p3 fire 1"" }, {""P3 Button 2"", BIT_DIGITAL, DrvJoy3 + 5, ""p3 fire 2"" }, {""P4 Coin"", BIT_DIGITAL, DrvJoy4 + 7, ""p4 coin"" }, {""P4 Up"", BIT_DIGITAL, DrvJoy4 + 2, ""p4 up"" }, {""P4 Down"", BIT_DIGITAL, DrvJoy4 + 3, ""p4 down"" }, {""P4 Left"", BIT_DIGITAL, DrvJoy4 + 1, ""p4 left"" }, {""P4 Right"", BIT_DIGITAL, DrvJoy4 + 0, ""p4 right"" }, {""P4 Button 1"", BIT_DIGITAL, DrvJoy4 + 4, ""p4 fire 1"" }, {""P4 Button 2"", BIT_DIGITAL, DrvJoy4 + 5, ""p4 fire 2"" }, {""Reset"", BIT_DIGITAL, &DrvReset, ""reset"" }, {""Diagnostics"", BIT_DIGITAL, &DrvJoy6, ""diag"" }, }; STDINPUTINFO(Vendet4p) static struct BurnInputInfo VendettaInputList[] = { {""P1 Coin"", BIT_DIGITAL, DrvJoy1 + 7, ""p1 coin"" }, {""P1 Start"", BIT_DIGITAL, DrvJoy5 + 0, ""p1 start"" }, {""P1 Up"", BIT_DIGITAL, DrvJoy1 + 2, ""p1 up"" }, {""P1 Down"", BIT_DIGITAL, DrvJoy1 + 3, ""p1 down"" }, {""P1 Left"", BIT_DIGITAL, DrvJoy1 + 1, ""p1 left"" }, {""P1 Right"", BIT_DIGITAL, DrvJoy1 + 0, ""p1 right"" }, {""P1 Button 1"", BIT_DIGITAL, DrvJoy1 + 4, ""p1 fire 1"" }, {""P1 Button 2"", BIT_DIGITAL, DrvJoy1 + 5, ""p1 fire 2"" }, {""P2 Coin"", BIT_DIGITAL, DrvJoy2 + 7, ""p2 coin"" }, {""P2 Start"", BIT_DIGITAL, DrvJoy5 + 1, ""p2 start"" }, {""P2 Up"", BIT_DIGITAL, DrvJoy2 + 2, ""p2 up"" }, {""P2 Down"", BIT_DIGITAL, DrvJoy2 + 3, ""p2 down"" }, {""P2 Left"", BIT_DIGITAL, DrvJoy2 + 1, ""p2 left"" }, {""P2 Right"", BIT_DIGITAL, DrvJoy2 + 0, ""p2 right"" }, {""P2 Button 1"", BIT_DIGITAL, DrvJoy2 + 4, ""p2 fire 1"" }, {""P2 Button 2"", BIT_DIGITAL, DrvJoy2 + 5, ""p2 fire 2"" }, {""Reset"", BIT_DIGITAL, &DrvReset, ""reset"" }, {""Diagnostics"", BIT_DIGITAL, &DrvJoy6, ""diag"" }, {""Service"", BIT_DIGITAL, DrvJoy5 + 4, ""service"" }, }; STDINPUTINFO(Vendetta) static struct BurnInputInfo EsckidsInputList[] = { {""P1 Coin"", BIT_DIGITAL, DrvJoy1 + 7, ""p1 coin"" }, {""P1 Start"", BIT_DIGITAL, DrvJoy5 + 0, ""p1 start"" }, {""P1 Up"", BIT_DIGITAL, DrvJoy1 + 2, ""p1 up"" }, {""P1 Down"", BIT_DIGITAL, DrvJoy1 + 3, ""p1 down"" }, {""P1 Left"", BIT_DIGITAL, DrvJoy1 + 1, ""p1 left"" }, {""P1 Right"", BIT_DIGITAL, DrvJoy1 + 0, ""p1 right"" }, {""P1 Button 1"", BIT_DIGITAL, DrvJoy1 + 4, ""p1 fire 1"" }, {""P1 Button 2"", BIT_DIGITAL, DrvJoy1 + 5, ""p1 fire 2"" }, {""P2 Coin"", BIT_DIGITAL, DrvJoy2 + 7, ""p2 coin"" }, {""P2 Start"", BIT_DIGITAL, DrvJoy5 + 1, ""p2 start"" }, {""P2 Up"", BIT_DIGITAL, DrvJoy2 + 2, ""p2 up"" }, {""P2 Down"", BIT_DIGITAL, DrvJoy2 + 3, ""p2 down"" }, {""P2 Left"", BIT_DIGITAL, DrvJoy2 + 1, ""p2 left"" }, {""P2 Right"", BIT_DIGITAL, DrvJoy2 + 0, ""p2 right"" }, {""P2 Button 1"", BIT_DIGITAL, DrvJoy2 + 4, ""p2 fire 1"" }, {""P2 Button 2"", BIT_DIGITAL, DrvJoy2 + 5, ""p2 fire 2"" }, {""P3 Coin"", BIT_DIGITAL, DrvJoy3 + 7, ""p3 coin"" }, {""P3 Start"", BIT_DIGITAL, DrvJoy5 + 2, ""p3 start"" }, {""P3 Up"", BIT_DIGITAL, DrvJoy3 + 2, ""p3 up"" }, {""P3 Down"", BIT_DIGITAL, DrvJoy3 + 3, ""p3 down"" }, {""P3 Left"", BIT_DIGITAL, DrvJoy3 + 1, ""p3 left"" }, {""P3 Right"", BIT_DIGITAL, DrvJoy3 + 0, ""p3 right"" }, {""P3 Button 1"", BIT_DIGITAL, DrvJoy3 + 4, ""p3 fire 1"" }, {""P3 Button 2"", BIT_DIGITAL, DrvJoy3 + 5, ""p3 fire 2"" }, {""P4 Coin"", BIT_DIGITAL, DrvJoy4 + 7, ""p4 coin"" }, {""P4 Start"", BIT_DIGITAL, DrvJoy5 + 3, ""p4 start"" }, {""P4 Up"", BIT_DIGITAL, DrvJoy4 + 2, ""p4 up"" }, {""P4 Down"", BIT_DIGITAL, DrvJoy4 + 3, ""p4 down"" }, {""P4 Left"", BIT_DIGITAL, DrvJoy4 + 1, ""p4 left"" }, {""P4 Right"", BIT_DIGITAL, DrvJoy4 + 0, ""p4 right"" }, {""P4 Button 1"", BIT_DIGITAL, DrvJoy4 + 4, ""p4 fire 1"" }, {""P4 Button 2"", BIT_DIGITAL, DrvJoy4 + 5, ""p4 fire 2"" }, {""Reset"", BIT_DIGITAL, &DrvReset, ""reset"" }, {""Diagnostics"", BIT_DIGITAL, &DrvJoy6, ""diag"" }, {""Service 1"", BIT_DIGITAL, DrvJoy5 + 4, ""service"" }, {""Service 2"", BIT_DIGITAL, DrvJoy5 + 5, ""service2"" }, {""Service 3"", BIT_DIGITAL, DrvJoy5 + 6, ""service3"" }, {""Service 4"", BIT_DIGITAL, DrvJoy5 + 7, ""service4"" }, }; STDINPUTINFO(Esckids) static struct BurnInputInfo EsckidsjInputList[] = { {""P1 Coin"", BIT_DIGITAL, DrvJoy1 + 7, ""p1 coin"" }, {""P1 Start"", BIT_DIGITAL, DrvJoy5 + 0, ""p1 start"" }, {""P1 Up"", BIT_DIGITAL, DrvJoy1 + 2, ""p1 up"" }, {""P1 Down"", BIT_DIGITAL, DrvJoy1 + 3, ""p1 down"" }, {""P1 Left"", BIT_DIGITAL, DrvJoy1 + 1, ""p1 left"" }, {""P1 Right"", BIT_DIGITAL, DrvJoy1 + 0, ""p1 right"" }, {""P1 Button 1"", BIT_DIGITAL, DrvJoy1 + 4, ""p1 fire 1"" }, {""P1 Button 2"", BIT_DIGITAL, DrvJoy1 + 5, ""p1 fire 2"" }, {""P2 Coin"", BIT_DIGITAL, DrvJoy2 + 7, ""p2 coin"" }, {""P2 Start"", BIT_DIGITAL, DrvJoy5 + 1, ""p2 start"" }, {""P2 Up"", BIT_DIGITAL, DrvJoy2 + 2, ""p2 up"" }, {""P2 Down"", BIT_DIGITAL, DrvJoy2 + 3, ""p2 down"" }, {""P2 Left"", BIT_DIGITAL, DrvJoy2 + 1, ""p2 left"" }, {""P2 Right"", BIT_DIGITAL, DrvJoy2 + 0, ""p2 right"" }, {""P2 Button 1"", BIT_DIGITAL, DrvJoy2 + 4, ""p2 fire 1"" }, {""P2 Button 2"", BIT_DIGITAL, DrvJoy2 + 5, ""p2 fire 2"" }, {""Reset"", BIT_DIGITAL, &DrvReset, ""reset"" }, {""Diagnostics"", BIT_DIGITAL, &DrvJoy6, ""diag"" }, {""Service 1"", BIT_DIGITAL, DrvJoy5 + 4, ""service"" }, {""Service 2"", BIT_DIGITAL, DrvJoy5 + 5, ""service2"" }, }; STDINPUTINFO(Esckidsj) void vendetta_main_write(UINT16 address, UINT8 data) { switch (address) { case 0x5fe0: K052109RMRDLine = data & 0x08; K053246_set_OBJCHA_line(data & 0x20); return; case 0x5fe2: { if (data == 0xff) return; EEPROMWrite(data & 0x10, data & 0x08, data & 0x20); irq_enabled = (data >> 6) & 1; videobank = data & 1; } return; case 0x5fe4: ZetSetVector(0xff); ZetSetIRQLine(0, ZET_IRQSTATUS_ACK); return; case 0x5fe6: case 0x5fe7: K053260Write(0, address & 1, data); return; } if ((address & 0xffe0) == 0x5f80) { K054000Write(address, data); return; } if ((address & 0xfff0) == 0x5fa0) { K053251Write(address & 0x0f, data); return; } if ((address & 0xfff8) == 0x5fb0) { K053246Write(address & 7, data); return; } if (videobank) { if ((address & 0xf000) == 0x4000) { address ^= 1; K053247Write(address & 0x0fff, data); return; } if ((address & 0xf000) == 0x6000) { DrvPalRAM[address & 0xfff] = data; return; } } if ((address & 0xc000) == 0x4000) { K052109Write(address & 0x3fff, data); return; } } UINT8 vendetta_main_read(UINT16 address) { switch (address) { case 0x5fc0: return DrvInputs[0]; case 0x5fc1: return DrvInputs[1]; case 0x5fc2: return DrvInputs[2]; case 0x5fc3: return DrvInputs[3]; case 0x5fd0: { INT32 res = (EEPROMRead() & 1) | vblank | ((DrvJoy6 << 2) ^ 0xf6); if (init_eeprom_count > 0) { init_eeprom_count--; res &= 0xfb; } return res; } case 0x5fd1: return DrvInputs[4]; case 0x5fe4: ZetSetVector(0xff); ZetSetIRQLine(0, ZET_IRQSTATUS_ACK); return 0; case 0x5fe6: case 0x5fe7: return K053260Read(0, (address & 1)+2); case 0x5fe8: case 0x5fe9: return K053246Read(address & 1); case 0x5fea: return 0; // watchdog } if ((address & 0xffe0) == 0x5f80) { return K054000Read(address); } if (videobank) { if ((address & 0xf000) == 0x4000) { address ^= 1; return K053247Read(address & 0x0fff); } if ((address & 0xf000) == 0x6000) { return DrvPalRAM[address & 0x0fff]; } } if ((address & 0xc000) == 0x4000) { return K052109Read(address & 0x3fff); } return 0; } void esckids_main_write(UINT16 address, UINT8 data) { switch (address) { case 0x3fd0: K052109RMRDLine = data & 0x08; K053246_set_OBJCHA_line(data & 0x20); return; case 0x3fd2: { if (data == 0xff) return; EEPROMWrite(data & 0x10, data & 0x08, data & 0x20); irq_enabled = (data >> 6) & 1; videobank = data & 1; } return; case 0x3fd4: ZetSetVector(0xff); ZetSetIRQLine(0, ZET_IRQSTATUS_ACK); return; case 0x3fd6: case 0x3fd7: K053260Write(0, address & 1, data); return; } if ((address & 0xfff0) == 0x3fb0) { K053251Write(address & 0x0f, data); return; } if ((address & 0xfff8) == 0x3fa0) { K053246Write(address & 7, data); return; } if (videobank) { if ((address & 0xf000) == 0x2000) { address ^= 1; K053247Write(address & 0x0fff, data); return; } if ((address & 0xf000) == 0x4000) { DrvPalRAM[address & 0xfff] = data; return; } } if (address >= 0x2000 && address <= 0x5fff) { K052109Write(address - 0x2000, data); return; } } UINT8 esckids_main_read(UINT16 address) { switch (address) { case 0x3f80: return DrvInputs[0]; case 0x3f81: return DrvInputs[1]; case 0x3f82: return DrvInputs[2]; case 0x3f83: return DrvInputs[3]; case 0x3f92: { INT32 res = (EEPROMRead() & 1) | vblank | ((DrvJoy6 << 2) ^ 0xf6); if (init_eeprom_count > 0) { init_eeprom_count--; res &= 0xfb; } return res; } case 0x3f93: return DrvInputs[4]; case 0x3fd4: ZetSetVector(0xff); ZetSetIRQLine(0, ZET_IRQSTATUS_ACK); return 0; case 0x3fd6: case 0x3fd7: return K053260Read(0, (address & 1)+2); case 0x3fd8: case 0x3fd9: return K053246Read(address & 1); } if (videobank) { if ((address & 0xf000) == 0x2000) { address ^= 1; return K053247Read(address & 0x0fff); } if ((address & 0xf000) == 0x4000) { return DrvPalRAM[address & 0x0fff]; } } if (address >= 0x2000 && address <= 0x5fff) { return K052109Read(address - 0x2000); } return 0; } void __fastcall vendetta_sound_write(UINT16 address, UINT8 data) { switch (address) { case 0xf800: BurnYM2151SelectRegister(data); return; case 0xf801: BurnYM2151WriteRegister(data); return; case 0xfa00: nCyclesDone[1] += ZetRun(100); ZetNmi(); return; } if (address >= 0xfc00 && address < 0xfc30) { K053260Write(0, address & 0xff, data); return; } } UINT8 __fastcall vendetta_sound_read(UINT16 address) { switch (address) { case 0xf800: return 0xff; case 0xf801: return BurnYM2151ReadStatus(); } if (address >= 0xfc00 && address < 0xfc30) { if ((address & 0x3f) == 0x01) ZetSetIRQLine(0, ZET_IRQSTATUS_NONE); return K053260Read(0, address & 0xff); } return 0; } static void vendetta_set_lines(INT32 lines) { nDrvBank[0] = lines; if (lines < 0x1c) { konamiMapMemory(DrvKonROM + 0x10000 + (lines * 0x2000), 0x0000 | bankoffset, 0x1fff | bankoffset, KON_ROM); } } static void K052109Callback(INT32 layer, INT32 bank, INT32 *code, INT32 *color, INT32 *, INT32 *) { *code |= ((*color & 0x03) << 8) | ((*color & 0x30) << 6) | ((*color & 0x0c) << 10) | (bank << 14); *color = layer_colorbase[layer] + ((*color & 0xc0) >> 6); } static void EsckidsK052109Callback(INT32 layer, INT32 bank, INT32 *code, INT32 *color, INT32 *, INT32 *) { *code |= ((*color & 0x03) << 8) | ((*color & 0x10) << 6) | ((*color & 0x0c) << 9) | (bank << 13); *color = layer_colorbase[layer] + ((*color & 0xe0) >> 5); } static void K053247Callback(INT32 *code, INT32 *color, INT32 *priority) { INT32 pri = (*color & 0x03e0) >> 4; if (pri <= layerpri[2]) *priority = 0; else if (pri > layerpri[2] && pri <= layerpri[1]) *priority = 1; else if (pri > layerpri[1] && pri <= layerpri[0]) *priority = 2; else *priority = 3; *code &= 0x7fff; *color = sprite_colorbase + (*color & 0x001f); } static INT32 DrvDoReset() { DrvReset = 0; memset (AllRam, 0, RamEnd - AllRam); konamiOpen(0); konamiReset(); konamiClose(); ZetOpen(0); ZetReset(); ZetClose(); BurnYM2151Reset(); KonamiICReset(); K053260Reset(0); EEPROMReset(); videobank = 0; if (EEPROMAvailable()) { init_eeprom_count = 0; } else { init_eeprom_count = 1000; } irq_enabled = 0; videobank = 0; return 0; } static INT32 MemIndex() { UINT8 *Next; Next = AllMem; DrvKonROM = Next; Next += 0x050000; DrvZ80ROM = Next; Next += 0x010000; DrvGfxROM0 = Next; Next += 0x100000; DrvGfxROMExp0 = Next; Next += 0x200000; DrvGfxROM1 = Next; Next += 0x400000; DrvGfxROMExp1 = Next; Next += 0x800000; DrvSndROM = Next; Next += 0x100000; Palette = (UINT32*)Next; Next += 0x800 * sizeof(UINT32); DrvPalette = (UINT32*)Next; Next += 0x800 * sizeof(UINT32); AllRam = Next; DrvZ80RAM = Next; Next += 0x000800; DrvKonRAM = Next; Next += 0x002000; DrvPalRAM = Next; Next += 0x001000; nDrvBank = Next; Next += 0x000001; RamEnd = Next; MemEnd = Next; return 0; } static INT32 DrvGfxDecode() { INT32 Plane[4] = { 0x018, 0x010, 0x008, 0x000 }; INT32 XOffs[8] = { 0x000, 0x001, 0x002, 0x003, 0x004, 0x005, 0x006, 0x007 }; INT32 YOffs[8] = { 0x000, 0x020, 0x040, 0x060, 0x080, 0x0a0, 0x0c0, 0x0e0 }; konami_rom_deinterleave_2(DrvGfxROM0, 0x100000); konami_rom_deinterleave_4(DrvGfxROM1, 0x400000); GfxDecode(0x8000, 4, 8, 8, Plane, XOffs, YOffs, 0x100, DrvGfxROM0, DrvGfxROMExp0); K053247GfxDecode(DrvGfxROM1, DrvGfxROMExp1, 0x400000); return 0; } static const eeprom_interface vendetta_eeprom_intf = { 7, // address bits 8, // data bits ""011000"", // read command ""011100"", // write command 0, // erase command ""0100000000000"", // lock command ""0100110000000"", // unlock command 0, 0 }; static INT32 DrvInit(INT32 nGame) { AllMem = NULL; MemIndex(); INT32 nLen = MemEnd - (UINT8 *)0; if ((AllMem = (UINT8 *)BurnMalloc(nLen)) == NULL) return 1; memset(AllMem, 0, nLen); MemIndex(); { if (BurnLoadRom(DrvKonROM + 0x010000, 0, 1)) return 1; if (BurnLoadRom(DrvZ80ROM + 0x000000, 1, 1)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x000000, 2, 1)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x080000, 3, 1)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x000000, 4, 1)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x100000, 5, 1)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x200000, 6, 1)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x300000, 7, 1)) return 1; if (BurnLoadRom(DrvSndROM + 0x000000, 8, 1)) return 1; DrvGfxDecode(); } if (nGame) // escape kids { memcpy (DrvKonROM + 0x08000, DrvKonROM + 0x28000, 0x8000); konamiInit(1); konamiOpen(0); konamiMapMemory(DrvKonRAM, 0x0000, 0x1fff, KON_RAM); konamiMapMemory(DrvKonROM + 0x10000, 0x6000, 0x7fff, KON_ROM); konamiMapMemory(DrvKonROM + 0x08000, 0x8000, 0xffff, KON_ROM); konamiSetWriteHandler(esckids_main_write); konamiSetReadHandler(esckids_main_read); konamiSetlinesCallback(vendetta_set_lines); konamiClose(); K052109Init(DrvGfxROM0, 0x0fffff); K052109SetCallback(EsckidsK052109Callback); K052109AdjustScroll(8, -8); K053247Init(DrvGfxROM1, 0x3fffff, K053247Callback, 1); K053247SetSpriteOffset(-11, 14); bankoffset = 0x6000; } else { memcpy (DrvKonROM + 0x08000, DrvKonROM + 0x48000, 0x8000); konamiInit(1); konamiOpen(0); konamiMapMemory(DrvKonROM + 0x10000, 0x0000, 0x1fff, KON_ROM); konamiMapMemory(DrvKonRAM, 0x2000, 0x3fff, KON_RAM); konamiMapMemory(DrvKonROM + 0x08000, 0x8000, 0xffff, KON_ROM); konamiSetWriteHandler(vendetta_main_write); konamiSetReadHandler(vendetta_main_read); konamiSetlinesCallback(vendetta_set_lines); konamiClose(); K052109Init(DrvGfxROM0, 0x0fffff); K052109SetCallback(K052109Callback); K052109AdjustScroll(0, 0); K053247Init(DrvGfxROM1, 0x3fffff, K053247Callback, 1); K053247SetSpriteOffset(-53, 22); bankoffset = 0; } ZetInit(0); ZetOpen(0); ZetMapArea(0x0000, 0xefff, 0, DrvZ80ROM); ZetMapArea(0x0000, 0xefff, 2, DrvZ80ROM); ZetMapArea(0xf000, 0xf7ff, 0, DrvZ80RAM); ZetMapArea(0xf000, 0xf7ff, 1, DrvZ80RAM); ZetMapArea(0xf000, 0xf7ff, 2, DrvZ80RAM); ZetSetWriteHandler(vendetta_sound_write); ZetSetReadHandler(vendetta_sound_read); ZetClose(); EEPROMInit(&vendetta_eeprom_intf); BurnYM2151Init(3579545); BurnYM2151SetRoute(BURN_SND_YM2151_YM2151_ROUTE_1, 1.00, BURN_SND_ROUTE_LEFT); BurnYM2151SetRoute(BURN_SND_YM2151_YM2151_ROUTE_2, 1.00, BURN_SND_ROUTE_RIGHT); K053260Init(0, 3579545, DrvSndROM, 0x100000 >> nGame); K053260SetRoute(0, BURN_SND_K053260_ROUTE_1, 0.75, BURN_SND_ROUTE_LEFT); K053260SetRoute(0, BURN_SND_K053260_ROUTE_2, 0.75, BURN_SND_ROUTE_RIGHT); GenericTilesInit(); DrvDoReset(); return 0; } static INT32 DrvExit() { GenericTilesExit(); KonamiICExit(); konamiExit(); ZetExit(); EEPROMExit(); BurnYM2151Exit(); K053260Exit(); BurnFree (AllMem); return 0; } static void DrvRecalcPal() { UINT8 r,g,b; UINT16 *p = (UINT16*)DrvPalRAM; for (INT32 i = 0; i < 0x1000 / 2; i++) { UINT16 d = BURN_ENDIAN_SWAP_INT16((p[i] << 8) | (p[i] >> 8)); b = (d >> 10) & 0x1f; g = (d >> 5) & 0x1f; r = (d >> 0) & 0x1f; r = (r << 3) | (r >> 2); g = (g << 3) | (g >> 2); b = (b << 3) | (b >> 2); Palette[i] = (r << 16) | (g << 8) | b; DrvPalette[i] = BurnHighCol(r, g, b, 0); } } static void sortlayers(INT32 *layer,INT32 *pri) { #define SWAP(a,b) \\ if (pri[a] < pri[b]) \\ { \\ INT32 t; \\ t = pri[a]; pri[a] = pri[b]; pri[b] = t; \\ t = layer[a]; layer[a] = layer[b]; layer[b] = t; \\ } SWAP(0,1) SWAP(0,2) SWAP(1,2) } static INT32 DrvDraw() { if (DrvRecalc) { DrvRecalcPal(); } K052109UpdateScroll(); INT32 layer[3]; bg_colorbase = K053251GetPaletteIndex(0); sprite_colorbase = K053251GetPaletteIndex(1); layer_colorbase[0] = K053251GetPaletteIndex(2); layer_colorbase[1] = K053251GetPaletteIndex(3); layer_colorbase[2] = K053251GetPaletteIndex(4); layerpri[0] = K053251GetPriority(2); layerpri[1] = K053251GetPriority(3); layerpri[2] = K053251GetPriority(4); layer[0] = 0; layer[1] = 1; layer[2] = 2; sortlayers(layer,layerpri); BurnTransferClear(); // this order makes sense... if (nSpriteEnable & 8) K053247SpritesRender(DrvGfxROMExp1, 0); if (nBurnLayer & 1) K052109RenderLayer(layer[0], 1, DrvGfxROMExp0); if (nBurnLayer & 2) K052109RenderLayer(layer[1], 0, DrvGfxROMExp0); if (nSpriteEnable & 4) K053247SpritesRender(DrvGfxROMExp1, 1); if (nSpriteEnable & 2) K053247SpritesRender(DrvGfxROMExp1, 2); if (nBurnLayer & 4) K052109RenderLayer(layer[2], 0, DrvGfxROMExp0); if (nSpriteEnable & 1) K053247SpritesRender(DrvGfxROMExp1, 3); KonamiBlendCopy(Palette, DrvPalette); return 0; } static INT32 DrvFrame() { if (DrvReset) { DrvDoReset(); } ZetNewFrame(); konamiNewFrame(); { memset (DrvInputs, 0xff, 5); for (INT32 i = 0; i < 8; i++) { DrvInputs[0] ^= (DrvJoy1[i] & 1) << i; DrvInputs[1] ^= (DrvJoy2[i] & 1) << i; DrvInputs[2] ^= (DrvJoy3[i] & 1) << i; DrvInputs[3] ^= (DrvJoy4[i] & 1) << i; DrvInputs[4] ^= (DrvJoy5[i] & 1) << i; } // Clear Opposites if ((DrvInputs[0] & 0x0c) == 0) DrvInputs[0] |= 0x0c; if ((DrvInputs[0] & 0x03) == 0) DrvInputs[0] |= 0x03; if ((DrvInputs[1] & 0x0c) == 0) DrvInputs[1] |= 0x0c; if ((DrvInputs[1] & 0x03) == 0) DrvInputs[1] |= 0x03; if ((DrvInputs[2] & 0x0c) == 0) DrvInputs[2] |= 0x0c; if ((DrvInputs[2] & 0x03) == 0) DrvInputs[2] |= 0x03; if ((DrvInputs[3] & 0x0c) == 0) DrvInputs[3] |= 0x0c; if ((DrvInputs[3] & 0x03) == 0) DrvInputs[3] |= 0x03; } INT32 nInterleave = 100; INT32 nSoundBufferPos = 0; INT32 nCyclesTotal[2] = { 6000000 / 60, 3579545 / 60 }; nCyclesDone[0] = nCyclesDone[1] = 0; ZetOpen(0); konamiOpen(0); vblank = 8; INT32 trigger_vblank = (nInterleave / 256) * 240; for (INT32 i = 0; i < nInterleave; i++) { INT32 nNext, nCyclesSegment; nNext = (i + 1) * nCyclesTotal[0] / nInterleave; nCyclesSegment = nNext - nCyclesDone[0]; nCyclesSegment = konamiRun(nCyclesSegment); nCyclesDone[0] += nCyclesSegment; nNext = (i + 1) * nCyclesTotal[1] / nInterleave; nCyclesSegment = nNext - nCyclesDone[1]; nCyclesSegment = ZetRun(nCyclesSegment); nCyclesDone[1] += nCyclesSegment; if (i == trigger_vblank) vblank = 0; // or 8? if (pBurnSoundOut) { INT32 nSegmentLength = nBurnSoundLen / nInterleave; INT16* pSoundBuf = pBurnSoundOut + (nSoundBufferPos << 1); BurnYM2151Render(pSoundBuf, nSegmentLength); K053260Update(0, pSoundBuf, nSegmentLength); nSoundBufferPos += nSegmentLength; } } if (irq_enabled) konamiSetIrqLine(KONAMI_IRQ_LINE, KONAMI_HOLD_LINE); if (pBurnSoundOut) { INT32 nSegmentLength = nBurnSoundLen - nSoundBufferPos; INT16* pSoundBuf = pBurnSoundOut + (nSoundBufferPos << 1); if (nSegmentLength) { BurnYM2151Render(pSoundBuf, nSegmentLength); K053260Update(0, pSoundBuf, nSegmentLength); } } konamiClose(); ZetClose(); if (pBurnDraw) { DrvDraw(); } return 0; } static INT32 DrvScan(INT32 nAction,INT32 *pnMin) { struct BurnArea ba; if (pnMin) { *pnMin = 0x029705; } if (nAction & ACB_VOLATILE) { memset(&ba, 0, sizeof(ba)); ba.Data = AllRam; ba.nLen = RamEnd - AllRam; ba.szName = ""All Ram""; BurnAcb(&ba); konamiCpuScan(nAction, pnMin); ZetScan(nAction); BurnYM2151Scan(nAction); K053260Scan(nAction); KonamiICScan(nAction); EEPROMScan(nAction, pnMin); SCAN_VAR(irq_enabled); SCAN_VAR(videobank); SCAN_VAR(nCyclesDone[1]); } if (nAction & ACB_WRITE) { konamiOpen(0); vendetta_set_lines(nDrvBank[0]); konamiClose(); } return 0; } // Vendetta (World 4 Players ver. T) static struct BurnRomInfo vendettaRomDesc[] = { { ""081t01"", 0x040000, 0xe76267f5, 1 | BRF_PRG | BRF_ESS }, // 0 Konami Custom Code { ""081b02"", 0x010000, 0x4c604d9b, 2 | BRF_PRG | BRF_ESS }, // 1 Z80 Code { ""081a09"", 0x080000, 0xb4c777a9, 3 | BRF_GRA }, // 2 K052109 Tiles { ""081a08"", 0x080000, 0x272ac8d9, 3 | BRF_GRA }, // 3 { ""081a04"", 0x100000, 0x464b9aa4, 4 | BRF_GRA }, // 4 K053247 Tiles { ""081a05"", 0x100000, 0x4e173759, 4 | BRF_GRA }, // 5 { ""081a06"", 0x100000, 0xe9fe6d80, 4 | BRF_GRA }, // 6 { ""081a07"", 0x100000, 0x8a22b29a, 4 | BRF_GRA }, // 7 { ""081a03"", 0x100000, 0x14b6baea, 5 | BRF_SND }, // 8 K053260 Samples { ""vendetta.nv"", 0x000080, 0xfbac4e30, BRF_OPT }, }; STD_ROM_PICK(vendetta) STD_ROM_FN(vendetta) static INT32 VendettaInit() { return DrvInit(0); } struct BurnDriver BurnDrvVendetta = { ""vendetta"", NULL, NULL, NULL, ""1991"", ""Vendetta (World 4 Players ver. T)\\0"", NULL, ""Konami"", ""GX081"", NULL, NULL, NULL, NULL, BDF_GAME_WORKING, 4, HARDWARE_PREFIX_KONAMI, GBF_SCRFIGHT, 0, NULL, vendettaRomInfo, vendettaRomName, NULL, NULL, Vendet4pInputInfo, NULL, VendettaInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &DrvRecalc, 0x800, 304, 224, 4, 3 }; // Vendetta (World 4 Players ver. R) static struct BurnRomInfo vendettarRomDesc[] = { { ""081r01"", 0x040000, 0x84796281, 1 | BRF_PRG | BRF_ESS }, // 0 Konami Custom Code { ""081b02"", 0x010000, 0x4c604d9b, 2 | BRF_PRG | BRF_ESS }, // 1 Z80 Code { ""081a09"", 0x080000, 0xb4c777a9, 3 | BRF_GRA }, // 2 K052109 Tiles { ""081a08"", 0x080000, 0x272ac8d9, 3 | BRF_GRA }, // 3 { ""081a04"", 0x100000, 0x464b9aa4, 4 | BRF_GRA }, // 4 K053247 Tiles { ""081a05"", 0x100000, 0x4e173759, 4 | BRF_GRA }, // 5 { ""081a06"", 0x100000, 0xe9fe6d80, 4 | BRF_GRA }, // 6 { ""081a07"", 0x100000, 0x8a22b29a, 4 | BRF_GRA }, // 7 { ""081a03"", 0x100000, 0x14b6baea, 5 | BRF_SND }, // 8 K053260 Samples { ""vendettar.nv"", 0x000080, 0xec3f0449, BRF_OPT }, }; STD_ROM_PICK(vendettar) STD_ROM_FN(vendettar) struct BurnDriver BurnDrvVendettar = { ""vendettar"", ""vendetta"", NULL, NULL, ""1991"", ""Vendetta (World 4 Players ver. R)\\0"", NULL, ""Konami"", ""GX081"", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE, 4, HARDWARE_PREFIX_KONAMI, GBF_SCRFIGHT, 0, NULL, vendettarRomInfo, vendettarRomName, NULL, NULL, Vendet4pInputInfo, NULL, VendettaInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &DrvRecalc, 0x800, 304, 224, 4, 3 }; // Vendetta (World 2 Players ver. W) static struct BurnRomInfo vendetta2pRomDesc[] = { { ""081w01"", 0x040000, 0xcee57132, 1 | BRF_PRG | BRF_ESS }, // 0 Konami Custom Code { ""081b02"", 0x010000, 0x4c604d9b, 2 | BRF_PRG | BRF_ESS }, // 1 Z80 Code { ""081a09"", 0x080000, 0xb4c777a9, 3 | BRF_GRA }, // 2 K052109 Tiles { ""081a08"", 0x080000, 0x272ac8d9, 3 | BRF_GRA }, // 3 { ""081a04"", 0x100000, 0x464b9aa4, 4 | BRF_GRA }, // 4 K053247 Tiles { ""081a05"", 0x100000, 0x4e173759, 4 | BRF_GRA }, // 5 { ""081a06"", 0x100000, 0xe9fe6d80, 4 | BRF_GRA }, // 6 { ""081a07"", 0x100000, 0x8a22b29a, 4 | BRF_GRA }, // 7 { ""081a03"", 0x100000, 0x14b6baea, 5 | BRF_SND }, // 8 K053260 Samples { ""vendetta.nv"", 0x000080, 0xfbac4e30, BRF_OPT }, }; STD_ROM_PICK(vendetta2p) STD_ROM_FN(vendetta2p) struct BurnDriver BurnDrvVendetta2p = { ""vendetta2p"", ""vendetta"", NULL, NULL, ""1991"", ""Vendetta (World 2 Players ver. W)\\0"", NULL, ""Konami"", ""GX081"", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_PREFIX_KONAMI, GBF_SCRFIGHT, 0, NULL, vendetta2pRomInfo, vendetta2pRomName, NULL, NULL, VendettaInputInfo, NULL, VendettaInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &DrvRecalc, 0x800, 304, 224, 4, 3 }; // Vendetta (Asia 2 Players ver. U) static struct BurnRomInfo vendetta2puRomDesc[] = { { ""081u01"", 0x040000, 0xb4d9ade5, 1 | BRF_PRG | BRF_ESS }, // 0 Konami Custom Code { ""081b02"", 0x010000, 0x4c604d9b, 2 | BRF_PRG | BRF_ESS }, // 1 Z80 Code { ""081a09"", 0x080000, 0xb4c777a9, 3 | BRF_GRA }, // 2 K052109 Tiles { ""081a08"", 0x080000, 0x272ac8d9, 3 | BRF_GRA }, // 3 { ""081a04"", 0x100000, 0x464b9aa4, 4 | BRF_GRA }, // 4 K053247 Tiles { ""081a05"", 0x100000, 0x4e173759, 4 | BRF_GRA }, // 5 { ""081a06"", 0x100000, 0xe9fe6d80, 4 | BRF_GRA }, // 6 { ""081a07"", 0x100000, 0x8a22b29a, 4 | BRF_GRA }, // 7 { ""081a03"", 0x100000, 0x14b6baea, 5 | BRF_SND }, // 8 K053260 Samples { ""vendetta.nv"", 0x000080, 0xfbac4e30, BRF_OPT }, }; STD_ROM_PICK(vendetta2pu) STD_ROM_FN(vendetta2pu) struct BurnDriver BurnDrvVendetta2pu = { ""vendetta2pu"", ""vendetta"", NULL, NULL, ""1991"", ""Vendetta (Asia 2 Players ver. U)\\0"", NULL, ""Konami"", ""GX081"", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_PREFIX_KONAMI, GBF_SCRFIGHT, 0, NULL, vendetta2puRomInfo, vendetta2puRomName, NULL, NULL, VendettaInputInfo, NULL, VendettaInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &DrvRecalc, 0x800, 304, 224, 4, 3 }; // Vendetta (Asia 2 Players ver. D) static struct BurnRomInfo vendetta2pdRomDesc[] = { { ""081d01"", 0x040000, 0x335da495, 1 | BRF_PRG | BRF_ESS }, // 0 Konami Custom Code { ""081b02"", 0x010000, 0x4c604d9b, 2 | BRF_PRG | BRF_ESS }, // 1 Z80 Code { ""081a09"", 0x080000, 0xb4c777a9, 3 | BRF_GRA }, // 2 K052109 Tiles { ""081a08"", 0x080000, 0x272ac8d9, 3 | BRF_GRA }, // 3 { ""081a04"", 0x100000, 0x464b9aa4, 4 | BRF_GRA }, // 4 K053247 Tiles { ""081a05"", 0x100000, 0x4e173759, 4 | BRF_GRA }, // 5 { ""081a06"", 0x100000, 0xe9fe6d80, 4 | BRF_GRA }, // 6 { ""081a07"", 0x100000, 0x8a22b29a, 4 | BRF_GRA }, // 7 { ""081a03"", 0x100000, 0x14b6baea, 5 | BRF_SND }, // 8 K053260 Samples { ""vendetta.nv"", 0x000080, 0xfbac4e30, BRF_OPT }, }; STD_ROM_PICK(vendetta2pd) STD_ROM_FN(vendetta2pd) struct BurnDriver BurnDrvVendetta2pd = { ""vendetta2pd"", ""vendetta"", NULL, NULL, ""1991"", ""Vendetta (Asia 2 Players ver. D)\\0"", NULL, ""Konami"", ""GX081"", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_PREFIX_KONAMI, GBF_SCRFIGHT, 0, NULL, vendetta2pdRomInfo, vendetta2pdRomName, NULL, NULL, VendettaInputInfo, NULL, VendettaInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &DrvRecalc, 0x800, 304, 224, 4, 3 }; // Crime Fighters 2 (Japan 2 Players ver. P) static struct BurnRomInfo vendettajRomDesc[] = { { ""081p01"", 0x040000, 0x5fe30242, 1 | BRF_PRG | BRF_ESS }, // 0 Konami Custom Code { ""081b02"", 0x010000, 0x4c604d9b, 2 | BRF_PRG | BRF_ESS }, // 1 Z80 Code { ""081a09"", 0x080000, 0xb4c777a9, 3 | BRF_GRA }, // 2 K052109 Tiles { ""081a08"", 0x080000, 0x272ac8d9, 3 | BRF_GRA }, // 3 { ""081a04"", 0x100000, 0x464b9aa4, 4 | BRF_GRA }, // 4 K053247 Tiles { ""081a05"", 0x100000, 0x4e173759, 4 | BRF_GRA }, // 5 { ""081a06"", 0x100000, 0xe9fe6d80, 4 | BRF_GRA }, // 6 { ""081a07"", 0x100000, 0x8a22b29a, 4 | BRF_GRA }, // 7 { ""081a03"", 0x100000, 0x14b6baea, 5 | BRF_SND }, // 8 K053260 Samples { ""vendettaj.nv"", 0x000080, 0x3550a54e, BRF_OPT }, }; STD_ROM_PICK(vendettaj) STD_ROM_FN(vendettaj) struct BurnDriver BurnDrvVendettaj = { ""vendettaj"", ""vendetta"", NULL, NULL, ""1991"", ""Crime Fighters 2 (Japan 2 Players ver. P)\\0"", NULL, ""Konami"", ""GX081"", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_PREFIX_KONAMI, GBF_SCRFIGHT, 0, NULL, vendettajRomInfo, vendettajRomName, NULL, NULL, VendettaInputInfo, NULL, VendettaInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &DrvRecalc, 0x800, 304, 224, 4, 3 }; // Escape Kids (Asia, 4 Players) static struct BurnRomInfo esckidsRomDesc[] = { { ""17c.bin"", 0x020000, 0x9dfba99c, 1 | BRF_PRG | BRF_ESS }, // 0 Konami Custom Code { ""975f02"", 0x010000, 0x994fb229, 2 | BRF_PRG | BRF_ESS }, // 1 Z80 Code { ""975c09"", 0x080000, 0xbc52210e, 3 | BRF_GRA }, // 2 K052109 Tiles { ""975c08"", 0x080000, 0xfcff9256, 3 | BRF_GRA }, // 3 { ""975c04"", 0x100000, 0x15688a6f, 4 | BRF_GRA }, // 4 K053247 Tiles { ""975c05"", 0x100000, 0x1ff33bb7, 4 | BRF_GRA }, // 5 { ""975c06"", 0x100000, 0x36d410f9, 4 | BRF_GRA }, // 6 { ""975c07"", 0x100000, 0x97ec541e, 4 | BRF_GRA }, // 7 { ""975c03"", 0x080000, 0xdc4a1707, 5 | BRF_SND }, // 8 K053260 Samples { ""esckids.nv"", 0x000080, 0xa8522e1f, BRF_OPT }, }; STD_ROM_PICK(esckids) STD_ROM_FN(esckids) static INT32 EsckidsInit() { return DrvInit(1); } struct BurnDriver BurnDrvEsckids = { ""esckids"", NULL, NULL, NULL, ""1991"", ""Escape Kids (Asia, 4 Players)\\0"", NULL, ""Konami"", ""GX975"", NULL, NULL, NULL, NULL, BDF_GAME_WORKING, 4, HARDWARE_PREFIX_KONAMI, GBF_MISC, 0, NULL, esckidsRomInfo, esckidsRomName, NULL, NULL, EsckidsInputInfo, NULL, EsckidsInit, DrvExit, DrvFrame, DrvDraw, NULL, &DrvRecalc, 0x800, 288, 240, 4, 3 }; // Escape Kids (Japan, 2 Players) static struct BurnRomInfo esckidsjRomDesc[] = { { ""975r01"", 0x020000, 0x7b5c5572, 1 | BRF_PRG | BRF_ESS }, // 0 Konami Custom Code { ""975f02"", 0x010000, 0x994fb229, 2 | BRF_PRG | BRF_ESS }, // 1 Z80 Code { ""975c09"", 0x080000, 0xbc52210e, 3 | BRF_GRA }, // 2 K052109 Tiles { ""975c08"", 0x080000, 0xfcff9256, 3 | BRF_GRA }, // 3 { ""975c04"", 0x100000, 0x15688a6f, 4 | BRF_GRA }, // 4 K053247 Tiles { ""975c05"", 0x100000, 0x1ff33bb7, 4 | BRF_GRA }, // 5 { ""975c06"", 0x100000, 0x36d410f9, 4 | BRF_GRA }, // 6 { ""975c07"", 0x100000, 0x97ec541e, 4 | BRF_GRA }, // 7 { ""975c03"", 0x080000, 0xdc4a1707, 5 | BRF_SND }, // 8 K053260 Samples { ""esckidsj.nv"", 0x000080, 0x985e2a2d, BRF_OPT }, }; STD_ROM_PICK(esckidsj) STD_ROM_FN(esckidsj) struct BurnDriver BurnDrvEsckidsj = { ""esckidsj"", ""esckids"", NULL, NULL, ""1991"", ""Escape Kids (Japan, 2 Players)\\0"", NULL, ""Konami"", ""GX975"", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_PREFIX_KONAMI, GBF_MISC, 0, NULL, esckidsjRomInfo, esckidsjRomName, NULL, NULL, EsckidsjInputInfo, NULL, EsckidsInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &DrvRecalc, 0x800, 288, 240, 4, 3 }; ",16221,False,2483.203118086199,median "[MusicConfig] Location=14458 Shoji Meguro - Reach Out to the Truth (Instrumental)/01 Reach Out To The Truth -Inst Version-.mp3 Extension=mp3 MD5=6e‌​35‌​2f‌​4f‌​d6‌​30‌​57‌​c2‌​97‌​db‌​a5‌​08‌​86‌​fa‌​55‌​88 Source=OSU MetreNumber=4 Title=Reach Out to the Truth (Instrumental) [TagConfig] Tagger=Carra Time=2016/10/7 12:17:45 Confidence=4 [MiscConfig] LinkedFile=14458 Shoji Meguro - Reach Out to the Truth (Instrumental)/Shoji Meguro - Reach Out to the Truth (Instrumental) (Astom) [Insane].osu osuMapID=14458 [BeatInfo] Count=259 Beat_0={1.248,1,D Maj,D} Beat_1={1.6009411764705881,0,D Maj,D} Beat_2={1.953882352941176,0,D Maj,D} Beat_3={2.3068235294117638,0,D Maj,D} Beat_4={2.6597647058823517,1,D Maj,A} Beat_5={3.0127058823529396,0,D Maj,A} Beat_6={3.3656470588235274,0,D Maj,A} Beat_7={3.7185882352941153,0,D Maj,A} Beat_8={4.0715294117647032,1,D Maj,G} Beat_9={4.424470588235291,0,D Maj,G} Beat_10={4.7774117647058789,0,D Maj,G} Beat_11={5.1303529411764668,0,D Maj,G} Beat_12={5.4832941176470547,1,D Maj,C} Beat_13={5.8362352941176425,0,D Maj,C} Beat_14={6.18917647058823,0,D Maj,C} Beat_15={6.5421176470588183,0,D Maj,C} Beat_16={6.8950588235294061,1,D Maj,Em} Beat_17={7.247999999999994,0,D Maj,Em} Beat_18={7.6009411764705819,0,D Maj,Em} Beat_19={7.95388235294117,0,D Maj,Em} Beat_20={8.3068235294117585,1,D Maj,G} Beat_21={8.6597647058823473,0,D Maj,G} Beat_22={9.012705882352936,0,D Maj,A} Beat_23={9.3656470588235248,0,D Maj,A} Beat_24={9.7185882352941135,1,D Maj,Bm} Beat_25={10.071529411764702,0,D Maj,Bm} Beat_26={10.424470588235291,0,D Maj,Bm} Beat_27={10.77741176470588,0,D Maj,Bm} Beat_28={11.130352941176469,1,D Maj,Bm} Beat_29={11.483294117647057,0,D Maj,Bm} Beat_30={11.836235294117646,0,D Maj,Bm} Beat_31={12.189176470588235,0,D Maj,Bm} Beat_32={12.542117647058824,1,D Maj,Bm} Beat_33={12.895058823529412,0,D Maj,Bm} Beat_34={13.248000000000001,0,D Maj,Bm} Beat_35={13.60094117647059,0,D Maj,Bm} Beat_36={13.953882352941179,1,D Maj,Bm} Beat_37={14.306823529411767,0,D Maj,Bm} Beat_38={14.659764705882356,0,D Maj,C} Beat_39={15.012705882352945,0,D Maj,C} Beat_40={15.365647058823534,1,D Maj,Bm} Beat_41={15.718588235294122,0,D Maj,Bm} Beat_42={16.071529411764711,0,D Maj,Bm} Beat_43={16.424470588235298,0,D Maj,Bm} Beat_44={16.777411764705885,1,D Maj,Bm} Beat_45={17.130352941176472,0,D Maj,Bm} Beat_46={17.483294117647059,0,D Maj,Bm} Beat_47={17.836235294117646,0,D Maj,Bm} Beat_48={18.189176470588233,1,D Maj,Bm} Beat_49={18.54211764705882,0,D Maj,Bm} Beat_50={18.895058823529407,0,D Maj,Bm} Beat_51={19.247999999999994,0,D Maj,Bm} Beat_52={19.600941176470581,1,D Maj,Bm} Beat_53={19.953882352941168,0,D Maj,Bm} Beat_54={20.306823529411755,0,D Maj,C} Beat_55={20.659764705882342,0,D Maj,C} Beat_56={21.012705882352929,1,D Maj,Bm} Beat_57={21.365647058823516,0,D Maj,Bm} Beat_58={21.718588235294103,0,D Maj,Bm} Beat_59={22.07152941176469,0,D Maj,Bm} Beat_60={22.424470588235277,1,D Maj,Bm} Beat_61={22.777411764705864,0,D Maj,Bm} Beat_62={23.130352941176451,0,D Maj,Bm} Beat_63={23.483294117647038,0,D Maj,Bm} Beat_64={23.836235294117625,1,D Maj,Bm} Beat_65={24.189176470588212,0,D Maj,Bm} Beat_66={24.5421176470588,0,D Maj,Bm} Beat_67={24.895058823529386,0,D Maj,Bm} Beat_68={25.247999999999973,1,D Maj,Bm} Beat_69={25.60094117647056,0,D Maj,Bm} Beat_70={25.953882352941147,0,D Maj,C} Beat_71={26.306823529411734,0,D Maj,C} Beat_72={26.659764705882321,1,D Maj,Bm} Beat_73={27.012705882352908,0,D Maj,Bm} Beat_74={27.365647058823495,0,D Maj,Bm} Beat_75={27.718588235294082,0,D Maj,Bm} Beat_76={28.071529411764669,1,D Maj,Bm} Beat_77={28.424470588235256,0,D Maj,Bm} Beat_78={28.777411764705842,0,D Maj,Bm} Beat_79={29.130352941176429,0,D Maj,Bm} Beat_80={29.483294117647016,1,D Maj,Bm} Beat_81={29.836235294117603,0,D Maj,Bm} Beat_82={30.18917647058819,0,D Maj,Bm} Beat_83={30.542117647058777,0,D Maj,Bm} Beat_84={30.895058823529364,1,D Maj,Bm} Beat_85={31.247999999999951,0,D Maj,Bm} Beat_86={31.600941176470538,0,D Maj,C} Beat_87={31.953882352941125,0,D Maj,C} Beat_88={32.306823529411716,1,D Maj,Bm} Beat_89={32.6597647058823,0,D Maj,Bm} Beat_90={33.01270588235289,0,D Maj,Bm} Beat_91={33.365647058823477,0,D Maj,Bm} Beat_92={33.718588235294064,1,D Maj,Bm} Beat_93={34.071529411764651,0,D Maj,Bm} Beat_94={34.424470588235238,0,D Maj,Bm} Beat_95={34.777411764705825,0,D Maj,Bm} Beat_96={35.130352941176412,1,D Maj,Bm} Beat_97={35.483294117647,0,D Maj,Bm} Beat_98={35.836235294117586,0,D Maj,Bm} Beat_99={36.189176470588173,0,D Maj,Bm} Beat_100={36.54211764705876,1,D Maj,Bm} Beat_101={36.895058823529347,0,D Maj,Bm} Beat_102={37.247999999999934,0,D Maj,C} Beat_103={37.600941176470521,0,D Maj,C} Beat_104={37.953882352941108,1,D Maj,Bm} Beat_105={38.306823529411695,0,D Maj,Bm} Beat_106={38.659764705882282,0,D Maj,Bm} Beat_107={39.012705882352869,0,D Maj,Bm} Beat_108={39.365647058823455,1,D Maj,Bm} Beat_109={39.718588235294042,0,D Maj,Bm} Beat_110={40.071529411764629,0,D Maj,Bm} Beat_111={40.424470588235216,0,D Maj,Bm} Beat_112={40.7774117647058,1,D Maj,Bm} Beat_113={41.13035294117639,0,D Maj,Bm} Beat_114={41.483294117646977,0,D Maj,Bm} Beat_115={41.836235294117564,0,D Maj,Bm} Beat_116={42.189176470588151,1,D Maj,Bm} Beat_117={42.542117647058738,0,D Maj,Bm} Beat_118={42.895058823529325,0,D Maj,Bm} Beat_119={43.247999999999912,0,D Maj,Bm} Beat_120={43.6009411764705,1,D Maj,D} Beat_121={43.953882352941086,0,D Maj,D} Beat_122={44.306823529411673,0,D Maj,D} Beat_123={44.65976470588226,0,D Maj,D} Beat_124={45.012705882352847,1,D Maj,A} Beat_125={45.365647058823434,0,D Maj,A} Beat_126={45.718588235294021,0,D Maj,A} Beat_127={46.071529411764608,0,D Maj,A} Beat_128={46.424470588235195,1,D Maj,G} Beat_129={46.777411764705782,0,D Maj,G} Beat_130={47.130352941176369,0,D Maj,G} Beat_131={47.483294117646956,0,D Maj,G} Beat_132={47.836235294117543,1,D Maj,C} Beat_133={48.18917647058813,0,D Maj,C} Beat_134={48.542117647058717,0,D Maj,C} Beat_135={48.895058823529304,0,D Maj,C} Beat_136={49.247999999999891,1,D Maj,Em} Beat_137={49.600941176470478,0,D Maj,Em} Beat_138={49.953882352941065,0,D Maj,Em} Beat_139={50.306823529411652,0,D Maj,Em} Beat_140={50.659764705882239,1,D Maj,C#dim} Beat_141={51.012705882352826,0,D Maj,C#dim} Beat_142={51.365647058823413,0,D Maj,F#} Beat_143={51.718588235294,0,D Maj,F#} Beat_144={52.071529411764587,1,D Maj,Bm} Beat_145={52.424470588235174,0,D Maj,Bm} Beat_146={52.777411764705761,0,D Maj,Bm} Beat_147={53.130352941176348,0,D Maj,Bm} Beat_148={53.483294117646935,1,D Maj,Am} Beat_149={53.836235294117522,0,D Maj,Am} Beat_150={54.189176470588109,0,D Maj,Am} Beat_151={54.542117647058696,0,D Maj,Am} Beat_152={54.895058823529283,1,D Maj,G} Beat_153={55.24799999999987,0,D Maj,G} Beat_154={55.600941176470457,0,D Maj,G} Beat_155={55.953882352941044,0,D Maj,G} Beat_156={56.306823529411631,1,D Maj,A} Beat_157={56.659764705882218,0,D Maj,A} Beat_158={57.012705882352805,0,D Maj,A} Beat_159={57.365647058823392,0,D Maj,A} Beat_160={57.718588235293979,1,D Maj,F#m} Beat_161={58.071529411764566,0,D Maj,F#m} Beat_162={58.424470588235152,0,D Maj,F#m} Beat_163={58.777411764705739,0,D Maj,F#m} Beat_164={59.130352941176326,1,D Maj,Bm} Beat_165={59.483294117646913,0,D Maj,Bm} Beat_166={59.8362352941175,0,D Maj,Bm} Beat_167={60.189176470588087,0,D Maj,Bm} Beat_168={60.542117647058674,1,D Maj,Em} Beat_169={60.895058823529261,0,D Maj,Em} Beat_170={61.247999999999848,0,D Maj,Em} Beat_171={61.600941176470435,0,D Maj,Em} Beat_172={61.953882352941022,1,D Maj,A} Beat_173={62.306823529411609,0,D Maj,A} Beat_174={62.659764705882196,0,D Maj,A} Beat_175={63.012705882352783,0,D Maj,A} Beat_176={63.36564705882337,1,D Maj,D} Beat_177={63.718588235293957,0,D Maj,D} Beat_178={64.071529411764544,0,D Maj,D} Beat_179={64.424470588235138,0,D Maj,D} Beat_180={64.777411764705732,1,D Maj,D} Beat_181={65.130352941176326,0,D Maj,D} Beat_182={65.483294117646921,0,D Maj,D} Beat_183={65.836235294117515,0,D Maj,D} Beat_184={66.189176470588109,1,D Maj,G} Beat_185={66.5421176470587,0,D Maj,G} Beat_186={66.8950588235293,0,D Maj,G} Beat_187={67.247999999999891,0,D Maj,G} Beat_188={67.600941176470485,1,D Maj,A} Beat_189={67.953882352941079,0,D Maj,A} Beat_190={68.306823529411673,0,D Maj,A} Beat_191={68.659764705882267,0,D Maj,A} Beat_192={69.012705882352861,1,D Maj,F#m} Beat_193={69.365647058823455,0,D Maj,F#m} Beat_194={69.71858823529405,0,D Maj,F#m} Beat_195={70.071529411764644,0,D Maj,F#m} Beat_196={70.424470588235238,1,D Maj,Bm} Beat_197={70.777411764705832,0,D Maj,Bm} Beat_198={71.130352941176426,0,D Maj,Bm} Beat_199={71.48329411764702,0,D Maj,Bm} Beat_200={71.836235294117614,1,D Maj,Em} Beat_201={72.189176470588208,0,D Maj,Em} Beat_202={72.5421176470588,0,D Maj,Em} Beat_203={72.8950588235294,0,D Maj,Em} Beat_204={73.24799999999999,1,D Maj,A} Beat_205={73.600941176470585,0,D Maj,A} Beat_206={73.953882352941179,0,D Maj,A} Beat_207={74.306823529411773,0,D Maj,A} Beat_208={74.659764705882367,1,D Maj,D} Beat_209={75.012705882352961,0,D Maj,D} Beat_210={75.365647058823555,0,D Maj,D} Beat_211={75.718588235294149,0,D Maj,D} Beat_212={76.071529411764743,1,D Maj,D} Beat_213={76.424470588235337,0,D Maj,D} Beat_214={76.777411764705931,0,D Maj,D} Beat_215={77.130352941176525,0,D Maj,D} Beat_216={77.483294117647119,1,D Maj,G} Beat_217={77.836235294117714,0,D Maj,G} Beat_218={78.189176470588308,0,D Maj,G} Beat_219={78.5421176470589,0,D Maj,G} Beat_220={78.8950588235295,1,D Maj,A} Beat_221={79.24800000000009,0,D Maj,A} Beat_222={79.600941176470684,0,D Maj,A} Beat_223={79.953882352941278,0,D Maj,A} Beat_224={80.306823529411872,1,D Maj,F#m} Beat_225={80.659764705882466,0,D Maj,F#m} Beat_226={81.01270588235306,0,D Maj,F#m} Beat_227={81.365647058823654,0,D Maj,F#m} Beat_228={81.718588235294249,1,D Maj,Bm} Beat_229={82.071529411764843,0,D Maj,Bm} Beat_230={82.424470588235437,0,D Maj,Bm} Beat_231={82.777411764706031,0,D Maj,Bm} Beat_232={83.130352941176625,1,D Maj,Em} Beat_233={83.483294117647219,0,D Maj,Em} Beat_234={83.836235294117813,0,D Maj,Em} Beat_235={84.189176470588407,0,D Maj,Em} Beat_236={84.542117647059,1,D Maj,A} Beat_237={84.8950588235296,0,D Maj,A} Beat_238={85.248000000000189,0,D Maj,A} Beat_239={85.600941176470783,0,D Maj,A} Beat_240={85.953882352941378,1,D Maj,D} Beat_241={86.306823529411972,0,D Maj,D} Beat_242={86.659764705882566,0,D Maj,D} Beat_243={87.01270588235316,0,D Maj,D} Beat_244={87.365647058823754,1,D Maj,D} Beat_245={87.718588235294348,0,D Maj,D} Beat_246={88.071529411764942,0,D Maj,D} Beat_247={88.424470588235536,0,D Maj,D} Beat_248={88.77741176470613,1,D Maj,D} Beat_249={89.130352941176724,0,D Maj,D} Beat_250={89.483294117647318,0,D Maj,D} Beat_251={89.836235294117913,0,D Maj,D} Beat_252={90.1891764705885,1,D Maj,N} Beat_253={90.5421176470591,0,D Maj,N} Beat_254={90.8950588235297,0,D Maj,N} Beat_255={91.248000000000289,0,D Maj,N} Beat_256={91.600941176470883,1,D Maj,N} Beat_257={91.953882352941477,0,D Maj,N} Beat_258={92.306823529412071,0,D Maj,N} ",7974,True,2951.2964376522477,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. // = NetBeans IDEでのGitサポートの使用 :jbake-type: tutorial :jbake-tags: tutorials :jbake-status: published :icons: font :syntax: true :source-highlighter: pygments :toc: left :toc-title: :description: NetBeans IDEでのGitサポートの使用 - Apache NetBeans :keywords: Apache NetBeans, Tutorials, NetBeans IDEでのGitサポートの使用 NetBeans IDEはGitバージョン管理クライアントをサポートしています。IDEのGitサポートにより、IDE内のプロジェクトから直接バージョン管理タスクを実行できます。このドキュメントでは、バージョン管理ソフトウェアを使用する場合の標準的なワークフローを説明することによって、IDEの基本的なバージョン管理タスクの実行方法を示します。 Gitは、小さなプロジェクトから非常に大きなプロジェクトまであらゆるものを高速かつ効率的に処理するように設計された、無料かつオープン・ソースの分散バージョン管理システムです。すべてのGitクローンは、ネットワーク・アクセスや中央のサーバーに依存せずに、完全な履歴およびリビジョン・トラック機能を備え、すべてを完備したリポジトリです。分岐やマージの実行は高速で簡単です。Gitはファイルのバージョン管理に使用され、Mercurial、Subversion、CVS、Perforceなどのツールによく似ています。 == 内容 image::images/netbeans-stamp-80-74.png[title=""このページの内容は、NetBeans IDE 7.4および8.0に適用されます""] * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> == 要件 *このチュートリアルを完了するには、次のソフトウェアとリソースが必要です。* |=== |ソフトウェアまたはリソース |必須バージョン |link:https://netbeans.org/downloads/index.html[+NetBeans IDE+] |バージョン7.4または8.0 |link:http://www.oracle.com/technetwork/java/javase/downloads/index.html[+Java Development Kit+] (JDK) |バージョン7または8 |=== == Gitリポジトリの初期化 まだソース管理されていない既存のファイルからGitリポジトリを初期化するには、次の手順を完了する必要があります。 1. 「プロジェクト」ウィンドウで、バージョン管理されていないプロジェクトを選択し、プロジェクト名を右クリックします。 2. コンテキスト・メニューで「 ``バージョン管理`` 」>「 ``Gitリポジトリの初期化`` 」(または、メイン・メニューの「 ``チーム`` 」>「 ``Git`` 」>「 ``初期化`` 」)を選択します。 [.feature] -- image::images/initialize-git-repo-small.png[role=""left"", link=""images/initialize-git-repo.png""] -- 1. 「 ``Gitリポジトリの初期化`` 」ダイアログ・ボックスで、バージョン管理されるファイルの保存先リポジトリへのパスを指定するか、「参照」をクリックして、必要なディレクトリを参照します。 2. 「OK」をクリックします。 ``.git`` サブフォルダは、上のステップ3で指定したフォルダ(デフォルトでNetBeansプロジェクト・フォルダ)に作成され、プロジェクト・スナップショットのすべてのデータが格納されるGitリポジトリです。Gitは指定されたフォルダ内のすべてのファイルのバージョン管理を開始します。 「 ``ウィンドウ`` 」>「 ``出力`` 」>「 ``出力`` 」を開いて、ローカル作業ディレクトリ下のリポジトリの作成の進捗に関するIDEのレポートを表示できます。 image::images/output-init.png[] すべてのプロジェクト・ファイルが作業ツリーで「 ``追加済み`` 」とマークされます。ファイル・<>を表示するには、「プロジェクト」ウィンドウ内のファイル名の上にカーソルを置きます。次の図に示すように、作業ツリーのファイルのステータスが、斜線の右側に緑で表示されます。 image::images/new-locally.png[] Gitリポジトリの初期化後、Gitリポジトリにファイルを<>するか、または直接それらを<>します。 == Gitリポジトリのクローン 既存のGitリポジトリのコピーを取得するには、それをクローンする必要があります。IDEでリポジトリをクローン・ウィザードを起動する前に、GitリポジトリのURLがわかっていることを確認します。 1. メイン・メニューから「 ``チーム`` 」>「 ``Git`` 」>「 ``クローン`` 」を選択します。リポジトリをクローン・ウィザードが表示されます。 [.feature] -- image::images/clone-wizard-small.png[role=""left"", link=""images/clone-wizard.png""] -- 1. リポジトリ・ページで、Gitリポジトリの場所へのパス、ユーザー名、およびパスワードを指定します(必要に応じて、今後のためにそれらを保存できます)。 2. (オプション)「プロキシ構成」をクリックし、「オプション」ダイアログ・ボックスを表示して、プロキシ・サーバー設定を設定します。終了したら「OK」をクリックします。 3. 「次」をクリックして、ウィザードの次のステップに切り替えます。 4. リモート分岐ページで、ローカル・リポジトリにフェッチ(ダウンロード)するリポジトリ分岐を選択します。「次」をクリックします。 5. 出力先ディレクトリ・ページで、次を指定します。 * 「親ディレクトリ」フィールドでは、ハード・ドライブ上にクローンされるリポジトリ用のディレクトリへのパス(または、「参照」ボタンをクリックし、ディレクトリに移動する)。 「親ディレクトリ」フィールドには、すべてのNetBeansプロジェクトが格納されるデフォルトの ``NetBeansProjects`` ディレクトリへのパスが事前入力されています。 * 「クローン名」フィールドの、元のプロジェクトをクローンするローカル・フォルダの名前。 デフォルトで、「クローン名」には実際のGitリポジトリ名が入力されています。 * 「分岐のチェックアウト」フィールドで、作業ツリーにチェックアウトする分岐を選択します。 * 「リモート名」フィールドの、クローンする元のリポジトリを表す名前。 ``origin`` はクローンするリポジトリのデフォルトのエイリアスです。これは推奨される値です。 * 「クローン後にNetBeansプロジェクトをスキャン」チェックボックスを選択されたままにして、クローンの終了直後に、事後スキャンをアクティブ化します。(プラグインはクローンされたリソースでNetBeansプロジェクトを検索し、見つかったプロジェクトを開くように提案します。) . 「終了」をクリックします。 Gitリポジトリのクローン後、ウィザードで選択したフォルダ内にメタデータ ``.git`` フォルダが作成されます。 === SSHプロトコルによるGitHubからのリポジトリのクローン SSHプロトコルによってGitHubからリポジトリをクローンするには、次のように進みます。 *注意:* SSHによってクローンするには、GitHubアカウントを持っており、プロジェクト・メンバーである必要があります。 1. メイン・メニューから「 ``チーム`` 」>「 ``Git`` 」>「 ``クローン`` 」を選択します。リポジトリをクローン・ウィザードが表示されます。 2. リポジトリをクローン・ウィザードのリモート・リポジトリ・ページで、「リポジトリURL」フィールドに、必要なリポジトリへのパス、たとえば ``git@github.com:tstupka/koliba.git`` などを指定します。 3. 「ユーザー名」テキスト・フィールドに ``git`` が指定されていることを確認します。 4. 「秘密/公開鍵」オプションを選択します。 5. (*Gitサーバーへの自動化されたSSHアクセスにSSHエージェントまたはPageantを使用中の場合はスキップします。*)SSH秘密鍵およびパス・フレーズを使用してGitサーバーにアクセスするには次の手順を実行します。 [start=1] 1. 鍵ファイルへのパス、たとえば ``C:\\Users\\key`` などを指定します。 *注意:* OpenSSH秘密鍵形式が必要です。Microsoft Windowsに対応のPuTTYgenで生成された鍵は、IDEを使用する前に、OpenSSH形式に変換する必要があります。 . 鍵ファイルのパス・フレーズ、たとえば ``abcd`` などを入力します。 . (オプション)必要に応じて、「パス・フレーズを保存」オプションを選択します。 . (*Gitサーバーへの自動化されたSSHアクセスにSSHエージェントまたはPageantを使用中の場合に適用されます。*)正しく構成されたSSHエージェントまたはPageant経由でIDEからGitサーバーへの認証されたアクセスを得るには、「秘密鍵ファイル」および「パス・フレーズ」フィールドを空のままにします。 . (オプション)「プロキシ構成」をクリックし、「オプション」ダイアログ・ボックスを表示して、プロキシ・サーバー設定を設定します。終了したら「OK」をクリックします。 [.feature] -- image::images/github-repo-small.png[role=""left"", link=""images/github-repo.png""] -- . 「次」をクリックします。 . リモート分岐ページで、ローカル・リポジトリにフェッチ(ダウンロード)するリポジトリ分岐、たとえば ``master`` などを選択します。 [.feature] -- image::images/github-branches-small.png[role=""left"", link=""images/github-branches.png""] -- . 「次」をクリックします。 . 出力先ディレクトリ・ページで、次を指定します。 * 「親ディレクトリ」フィールドでは、ハード・ドライブ上にクローンされるリポジトリ用のディレクトリへのパス(または、「参照」ボタンをクリックし、ディレクトリに移動する)。 「親ディレクトリ」フィールドには、すべてのNetBeansプロジェクトが格納されるデフォルトの ``NetBeansProjects`` ディレクトリへのパスが事前入力されています。 * 「クローン名」フィールドの、元のプロジェクトをクローンするローカル・フォルダの名前。 デフォルトで、「クローン名」には実際のGitリポジトリ名が入力されています。 * 「分岐のチェックアウト」フィールドで、作業ツリーにチェックアウトする分岐を選択します。 * 「リモート名」フィールドの、クローンする元のリポジトリを表す名前。 ``origin`` はクローンするリポジトリのデフォルトのエイリアスです。これは推奨される値です。 * 「クローン後にNetBeansプロジェクトをスキャン」チェックボックスを選択されたままにして、クローンの終了直後に、事後スキャンをアクティブ化します。(プラグインはクローンされたリソースでNetBeansプロジェクトを検索し、見つかったプロジェクトを開くように提案します。) [.feature] -- image::images/github-destination-small.png[role=""left"", link=""images/github-destination.png""] -- 1. 「終了」をクリックします。 リポジトリがクローンされると、「クローン完了」メッセージが表示されます。 image::images/clone-completed.png[] 1. 目的のオプションを選択します。 == Gitリポジトリへのファイルの追加 新しいファイルのトラックを開始し、さらに、Gitリポジトリ内のすでにトラックされているファイルへの変更をステージングするには、それをリポジトリに追加する必要があります。 Gitリポジトリにファイルが追加されると、IDEはプロジェクトのスナップショットを作成し、最初に索引に保存します。コミットが実行されると、IDEはそれらのスナップショットをHEADに保存します。IDEでは、次の表に説明する2つのワークフローから選択できます。 |=== |ワークフローの説明 |新規または変更済のファイルを索引に明示的に追加し、索引でステージングされているファイルのみをHEADにコミットします。 |新規または変更済のファイルの索引への追加をスキップし、必要なファイルを直接HEADにコミットします。 |ワークフローに従う手順 | 1. 「プロジェクト」ウィンドウで、追加するファイルを右クリックします。 2. コンテキスト・メニューで「 ``Git`` 」>「 ``追加`` 」を選択します。 これにより、コミットする前に、ファイルの内容が索引に追加されます。 1. 「プロジェクト」ウィンドウで、コミットするファイルを右クリックします。 2. 「コミット」ダイアログ・ボックスで、「HEADと索引間の変更」(image:images/changes-head-index.png[])トグル・ボタンを選択します。 これにより、すでにステージングされているファイルの一覧が表示されます。 1. 下の<>の項で説明するように、ファイルをコミットします。 | 1. 「プロジェクト」ウィンドウで、コミットするファイルを右クリックします。 2. コンテキスト・メニューで、「 ``Git`` 」>「 ``コミット`` 」を選択します。 3. 「コミット」ダイアログ・ボックスで、「索引と作業ツリー間の変更」(image:images/changes-head-wt.png[])トグル・ボタンを選択します。 これにより、ステージングされていないファイルの一覧が表示されます。 [start=4] . 下の<>の項で説明するように、ファイルをコミットします。 |=== *注意:* 次の図に示すように、HEAD内のファイルの<>が、斜線の左側に緑で表示されます。 image::images/new.png[] アクションは、フォルダに対して起動した場合に、NetBeans IDEフラット・フォルダ内容構造を順守しながら、再帰的に動作します。 == ファイルの編集 Gitバージョン管理プロジェクトをIDEで開くと、ソースの変更を開始できます。NetBeans IDEで開く任意のプロジェクトと同様に、(「プロジェクト」(Ctrl-1)、「ファイル」(Ctrl-2)、「お気に入り」(Ctrl-3)ウィンドウなどの) IDEのウィンドウで表示されているファイルのノードをダブルクリックすると、ファイルをソース・エディタで開くことができます。 IDEでソース・ファイルを操作する場合、自由に使用できる様々なUIコンポーネントがあります。これらは、表示およびバージョン管理コマンドの操作で役立ちます。 * <> * <> * <> === ソース・エディタでの変更の表示 IDEのソース・エディタでバージョン管理されたファイルを開くと、Gitリポジトリからの基本バージョンに照らしあわせながら、そのファイルに行われた変更がリアル・タイムで表示されます。作業に伴って、IDEはソース・エディタのマージンに色分けを使用し、次の情報を伝えます。 |=== |*青* (     ) |古いリビジョンの後で変更された行を示します。 |*緑* (     ) |古いリビジョンの後で追加された行を示します。 |*赤* (     ) |古いリビジョンの後で除去された行を示します。 |=== ソース・エディタの左側のマージンには、行ごとに発生した変更が表示されています。行を変更すると、その変更がすぐに左側のマージンに表示されます。 image::images/left-margin.png[] *注意:* マージンの色グループをクリックして、バージョン管理コマンドをコールできます。たとえば、下の図は、赤いアイコンをクリックすると使用可能なウィジェットを示しており、ローカル・コピーから行が除去されたことを示します。 image::images/left-widgets.png[] ソース・エディタの右側のマージンには、上から下に向かって、ファイル全体に行われた変更の概要が表示されます。ファイルに変更を行うと、すぐに色分けが生成されます。 image::images/right-margin.png[] *注意*: マージンの特定の場所をクリックすると、インライン・カーソルがファイルのその場所にすぐに移動します。影響を受ける行数を表示するには、右側のマージンの色つきアイコンの上にマウスを動かします。 image::images/right-lines-number.png[] === ファイルのステータス情報の表示 「プロジェクト」(Ctrl-1)、「ファイル」(Ctrl-2)、「お気に入り」(Ctrl-3)または「バージョン管理」ビューで作業する場合、IDEには、ファイルのステータス情報を表示するのに役立つ視覚機能がいくつかあります。次の例では、バッジ(例: image:images/blue-badge.png[])、ファイル名の色、および隣接するステータス・ラベルすべての相互の対応方法を確認し、ファイルに対するバージョン管理情報をトラックする単純だが効果的な方法について説明します。 image::images/file-status.png[] バッジ、色分け、ファイル・ステータス・ラベル、およびおそらく最も重要なGit差分ビューアはすべて、IDEでのバージョン管理情報を効率的に表示し、管理する能力に貢献します。 * <> * <> * <> ==== バッジと色分け バッジはプロジェクト、フォルダおよびパッケージ・ノードに適用され、そのノードに含まれているファイルのステータスを示します。 バッジに使用される色のスキームを次の表に示します。 |=== |UIコンポーネント |説明 |*青のバッジ*(image:images/blue-badge.png[]) |作業ツリー内の変更、追加、または削除されたファイルの存在を示します。パッケージの場合、このバッジは、パッケージ自体にのみ適用され、そのサブパッケージには適用されません。プロジェクトまたはフォルダの場合、このバッジはその項目または含まれるサブフォルダ内の内容の変更を示します。 |*赤のバッジ*(image:images/red-badge.png[]) |_競合する_ファイルを含むプロジェクト、フォルダまたはパッケージをマークします。パッケージの場合、このバッジは、パッケージ自体にのみ適用され、そのサブパッケージには適用されません。プロジェクトまたはフォルダの場合、このバッジはその項目または含まれるサブフォルダ内の競合を示しています。 |=== 色分けは、リポジトリに照らして、現在のステータスを示す目的でファイル名に適用されます。 |=== |色 |例 |説明 |*特定の色なし(黒)* |image:images/black-text.png[] |ファイルに変更がないことを示します。 |*青* |image:images/blue-text.png[] |ファイルがローカルに変更されたことを示します。 |*緑* |image:images/green-text.png[] |ファイルがローカルに追加されたことを示します。 |*赤* |image:images/red-text.png[] |ファイルにマージの競合があることを示します。 |*グレー* |image:images/gray-text.png[] |ファイルがGitによって無視され、バージョン管理コマンド(更新やコミットなど)に含まれないことを示します。ファイルはバージョン管理されている場合、無視できません。 |=== ==== ファイル・ステータス・ラベル IDEはファイルの2つのステータス値を表示します。 * ファイルの作業ツリーと索引状態の相違を示すステータス。 * ファイルの索引状態と現在のHEADコミットの相違を示すステータス。 ファイル・ステータス・ラベルは、バージョン管理ファイルのステータスを、IDEのウィンドウにテキストで示します。 |=== |ステータス・ラベル |意味 |*-* |変更なし |*A* |追加済 |*U* |更新済であるが未マージ |*M* |変更 |*D* |削除済 |*I* |無視 |*R* |名前変更済 |=== デフォルトで、IDEは、ファイルをウィンドウに一覧表示するときに、そのファイルの右側にステータス情報(新規、変更済、無視など)およびフォルダ情報をグレー・テキストで表示します。 image::images/file-labels.png[] マージの競合があるファイルは未マージステータスを示し、一般にユーザーの明示的なアクションによって解決されるまで、赤い色で注釈が付けられます。マージされていないファイルのステータス・ラベルは、シナリオによって異なります(たとえば、 ``A/A`` - 未マージ、両方追加済)。 ファイル・ステータス・ラベルは、メイン・メニューから「 ``表示`` 」>「 ``バージョン・ラベルを表示`` 」を選択して、オンとオフを切り替えできます。 ==== Gitバージョン管理ビュー Gitバージョン管理ビューは、ローカルの作業ツリーの選択されたフォルダ内でファイルに行われた変更のすべてを、リアル・タイムで一覧表示します。これはIDEの下のパネルにデフォルトで開き、追加、削除または変更されたファイルを一覧表示します。 バージョン管理ビューを開くには、(「プロジェクト」ウィンドウ、「ファイル」ウィンドウまたは「お気に入り」ウィンドウなどから)バージョン管理ファイルまたはフォルダを選択し、右クリック・メニューから「 ``Git`` 」>「 ``変更を表示`` 」を選択するか、またはメイン・メニューから「 ``チーム`` 」>「 ``変更を表示`` 」を選択します。IDEの最下部に次のウィンドウが表示されます。 [.feature] -- image::images/versioning-view-small.png[role=""left"", link=""images/versioning-view.png""] -- デフォルトでは、バージョン管理ビューは、作業ツリー内の選択されたパッケージまたはフォルダ内の変更されたすべてのファイルを一覧表示します。ツールバーのボタンを使用して、索引とHEAD、作業ツリーと索引、または作業ツリーとHEAD間で相違があるファイルの一覧を表示するように選択できます。一覧表示されたファイルの上にある列の見出しをクリックして、名前、ステータス、または場所でファイルをソートすることもできます。 「バージョン管理」ビューのツールバーには、一覧に表示されているすべてのファイルに対して一般的なGitタスクを呼び出すことができるボタンも用意されています。次の表は、「バージョン管理」ビューのツールバーにあるGitコマンドをまとめています。 |=== |アイコン |名前 |機能 |image:images/changes-head-wt.png[] |*HEADと作業ツリー間の変更* |すでにステージングされているか、変更または作成のみされていて、まだステージングされていないファイルの一覧を表示します。 |image:images/changes-head-index.png[] |*HEADと索引間の変更* |ステージングされているファイルの一覧を表示します。 |image:images/changes-index-wt.png[] |*索引と作業ツリー間の変更* |ステージング済の状態と作業ツリーの状態に相違があるファイルを表示します。 |image:images/refresh.png[] |*ステータスのリフレッシュ* |選択したファイルとフォルダのステータスをリフレッシュします。「バージョン管理」ビューに表示されたファイルは、外部で行われた可能性のある任意の変更を反映してリフレッシュできます。 |image:images/open-diff.png[] |*差分を開く* |差分ビューアを開くと、ローカルのコピーとリポジトリで保持されているバージョンを並べた比較が表示されます。 |image:images/update.png[] |*変更内容を元に戻す* |「<>」ダイアログ・ボックスを表示します。 |image:images/commit-button.png[] |*変更をコミット* |「<>」ダイアログ・ボックスを表示します。 |=== 「バージョン管理」ビューで、変更したファイルに対応する表の行を選択し、右クリック・メニューからコマンドを選択すると、他のGitコマンドにアクセスできます。 [.feature] -- image::images/versioning-right-click-small.png[role=""left"", link=""images/versioning-right-click.png""] -- === ファイル・リビジョンの比較 ファイル・バージョンの比較は、バージョン管理されているプロジェクトでの作業で共通のタスクです。IDEでは、「差分」コマンドを使用して、リビジョンを比較できます。 *注意:* 複数の比較モード(「HEADとの差分」、「トラック済との差分」、「差分の対象」)がIDEで使用可能です。 1. バージョン管理されたファイルまたはフォルダを選択します(「 ``プロジェクト`` 」、「 ``ファイル`` 」、「 ``お気に入り`` 」ウィンドウなどから)。 2. メイン・メニューから「 ``チーム`` 」>「 ``差分`` 」>「 ``HEADとの差分`` 」を選択します。 選択したファイルとリビジョンについてグラフィカルな差分ビューアがIDEのメイン・ウィンドウで開きます。差分ビューアには2つのコピーが並んだパネルに表示されます。右側により現在に近いコピーが表示されるため、作業ツリーに対してリポジトリ・リビジョンを比較すると、右パネルに作業ツリーが表示されます。 [.feature] -- image::images/diff-viewer-small.png[role=""left"", link=""images/diff-viewer.png""] -- 差分ビューアは、バージョン管理の変更を表示する場所に使用されているのと同じ<>を利用します。前に表示したスクリーン・ショットの緑色のブロックは、より現在に近いリビジョンに追加された内容を示します。赤いブロックは、前のリビジョンの内容が、より最近のリビジョンから除去されたことを示します。青は、強調表示された行で変更が発生したことを示します。 *注意:* 他のリビジョンは、差分ビューア・ツールバーの下の「 ``差分`` 」および「 ``送信先`` 」ドロップダウン・リストから選択できます。 差分ビューアのツールバーには、一覧に表示されているすべてのファイルに対して一般的なGitタスクを呼び出すことができるボタンも用意されています。次の表は、差分ビューアのツールバーにあるGitコマンドをまとめています。 |=== |アイコン |名前 |機能 |image:images/changes-head-wt.png[] |*HEADと作業ツリー間の変更* |すでにステージングされているか、変更または作成のみされていて、まだステージングされていないファイルの一覧を表示します。 |image:images/changes-head-index.png[] |*HEADと索引間の変更* |ステージングされているファイルの一覧を表示します。 |image:images/changes-index-wt.png[] |*索引と作業ツリー間の変更* |ステージング済の状態と作業ツリーの状態に相違があるファイルを表示します。 |image:images/nextdiff.png[] |*次の差分へ* |ファイル内の次の差分を表示します。 |image:images/prevdiff.png[] |*前の差分へ* |ファイル内の前の差分を表示します。 |image:images/refresh.png[] |*ステータスのリフレッシュ* |選択したファイルとフォルダのステータスをリフレッシュします。「バージョン管理」ウィンドウに表示されたファイルは、外部で行われた可能性のある任意の変更を反映してリフレッシュできます。 |image:images/update.png[] |*変更内容を元に戻す* |「<>」ダイアログ・ボックスを表示します。 |image:images/commit-button.png[] |*変更をコミット* |「<>」ダイアログ・ボックスを表示します。 |=== 作業ツリー内のローカル・コピーで差分の取得を実行する場合、IDEの差分ビューア内から直接変更を行うことができます。これを行うには、カーソルを差分ビューアの右ペインに置き、それに従ってファイルを変更するか、または強調表示された各変更の前後で表示されるインライン・アイコンを使用します。 |=== |アイコン |名前 |機能 |image:images/insert.png[] |*置換* |強調表示されたテキストを作業ツリー・コピーに挿入します。 |image:images/arrow.png[] |*すべて移動* |ローカル作業ツリー・コピー全体を元に戻します。 |image:images/remove.png[] |*除去* |ローカル作業ツリー・コピーから強調表示されたテキストを除去します。 |=== === 変更を元に戻す 作業ツリー内の選択したファイルに行ったローカルの変更をスローし、それらのファイルを索引またはHEAD内のファイルで置き換えるには、次を実行します。 1. バージョン管理されたファイルまたはフォルダを選択します(「 ``プロジェクト`` 」、「 ``ファイル`` 」、「 ``お気に入り`` 」ウィンドウなどから)。 2. メイン・メニューから「 ``チーム`` 」>「 ``変更内容を元に戻す`` 」を選択します。 「 ``変更内容を元に戻す`` 」ダイアログ・ボックスが表示されます。 image::images/revert.png[] 1. 追加のオプション(「 ``索引のコミットされていない変更のみをHEADに戻す`` 」など)を指定します。 2. 「元に戻す」をクリックします。 IDEによって、選択したファイルが上の<>で指定したファイルで置き換えられます。 == リポジトリへのソースのコミット ファイルをGitリポジトリにコミットするには、次を実行します。 1. 「 ``プロジェクト`` 」ウィンドウで、コミットするファイルを右クリックします。 2. コンテキスト・メニューで、「 ``Git`` 」>「 ``コミット`` 」を選択します。 「 ``コミット`` 」ダイアログ・ボックスが表示されます。 [.feature] -- image::images/commit-small.png[role=""left"", link=""images/commit.png""] -- 「 ``コミット`` 」ダイアログ・ボックスには次のコンポーネントが含まれます。 * コミットされる変更を説明するための「 ``コミット・メッセージ`` 」テキスト領域 * 必要に応じて、変更を行ったユーザーと物理的にファイルをコミットしたユーザーを区別できる「 ``作成者`` 」および「 ``コミッタ`` 」ドロップダウン・リスト。 * 「 ``コミットするファイル`` 」セクションには、次が表示されます。 * 変更されたすべてのファイル * 作業ツリーで(ローカルで)削除されたすべてのファイル * すべての新規ファイル(Gitリポジトリにまだ存在しないファイル) * 名前を変更したすべてのファイル。 実際のコミットが実行されるモードを切り替える2つのトグル・ボタンがここで利用できます。 |=== |UIコンポーネント |名前 |説明 |image:images/changes-head-index.png[] |*HEADと索引間の変更* |ステージングされているファイルの一覧を表示します。 |image:images/changes-head-wt.png[] |*HEADと作業ツリー間の変更* |すでにステージングされているか、変更または作成のみされていて、まだステージングされていないファイルの一覧を表示します。 |=== *注意*: ここで、コミットから個々のファイルを除外するかどうかを指定するには、「 ``コミット`` 」という最初の列のチェックボックスを選択解除するか、「 ``コミット・アクション`` 」列のファイル行を右クリックし、ポップアップ・メニューから「 ``コミットから除外`` 」を選択します。ここで差分ビューアを表示するには、「 ``コミット・アクション`` 」列のファイル行を右クリックし、ポップアップ・メニューから「 ``差分`` 」を選択します。 * コミットされる変更に関する問題をトラックするための「 ``問題を更新`` 」セクション。 *注意*: IDEで問題のトラックを開始するには、JIRAまたはSubversionプラグインをインストールする必要があります。 1. 「 ``コミット・メッセージ`` 」テキスト領域にコミット・メッセージを入力します。または、次のいずれかを実行できます。 * 右上隅にある「 ``最近のメッセージ`` 」(image:images/recent-msgs.png[])アイコンをクリックして、以前使用したメッセージのリストを表示して選択します。 * 右上隅にある「 ``テンプレートをロード`` 」(image:images/msg-template.png[])アイコンをクリックして、メッセージ・テンプレートを選択します。 . 個々のファイルのアクションを指定して「 ``コミット`` 」をクリックします。 IDEによってコミットが実行され、スナップショットがリポジトリに保存されます。コミット・アクションが実行されると、インタフェースの右下にあるIDEのステータス・バーが表示されます。コミットに成功すると、「 ``プロジェクト`` 」、「 ``ファイル`` 」および「 ``お気に入り`` 」ウィンドウのバージョン管理バッジが消え、コミットされたファイルの色分けが黒に戻ります。 == 分岐の操作 IDEのGitサポートでは、分岐を使用して、コード・ベース全体の様々なバージョンを管理できます。 IDEで分岐を操作する場合、次のアクションがサポートされます。 * <> * <> * <> * <> === 分岐の作成 メイン・トランクを妨げずに、安定化や実験の目的で、別個のバージョンのファイル・システムを操作する場合に、ローカル分岐を作成するには、次の完了を実行します。 1. 「プロジェクト」または「ファイル」ウィンドウで、分岐を作成するリポジトリからプロジェクトまたはフォルダを選択します。 2. メイン・メニューで「チーム」>「分岐/タグ」>「分岐の作成」を選択します。 *注意:* または、バージョン管理されたプロジェクトまたはフォルダを右クリックし、ポップアップ・メニューから「Git」>「分岐/タグ」>「分岐の作成」を選択します。 「分岐の作成」ダイアログ・ボックスが表示されます。 [.feature] -- image::images/create-branch-small.png[role=""left"", link=""images/create-branch.png""] -- 1. 「分岐名」フィールドで、作成する分岐の名前を入力します。 2. コミットID、既存の分岐、またはタグ名を「リビジョン」フィールドに入力して、選択した項目の特定のリビジョンを入力するか、「選択」を押して、リポジトリで管理されているリビジョンの一覧を表示します。 3. (オプション)「リビジョンを選択」ダイアログ・ボックスで、「分岐」を展開し、必要な分岐を選択して、隣接する一覧のコミットIDを指定し、「選択」を押します。 4. 分岐させるリビジョンに固有の「コミットID」、「作成者」、「メッセージ」フィールドの情報を確認して、「作成」をクリックします。 分岐がGitリポジトリの ``「分岐」/「ローカル」`` フォルダに追加されます。 [.feature] -- image::images/branch-added-small.png[role=""left"", link=""images/branch-added.png""] -- === チェックアウト すでに存在する分岐上のファイルを編集する必要がある場合は、分岐をチェックアウトすることによって、ファイルを作業ツリーにコピーできます。 リビジョンをチェックアウトするには、次を実行します。 1. メイン・メニューから「チーム」>「チェックアウト」>「リビジョンのチェックアウト」を選択します。 「選択されたリビジョンをチェックアウト」ダイアログ・ボックスが表示されます。 [.feature] -- image::images/chkout-rev-small.png[role=""left"", link=""images/chkout-rev.png""] -- 1. コミットID、既存の分岐またはタグ名を「リビジョン」フィールドに入力して、必要なリビジョンを指定するか、「選択」を押して、リポジトリで管理されているリビジョンの一覧を表示します。 2. 前のステップで「選択」を押さなかった場合、スキップします。「リビジョンを選択」ダイアログ・ボックスで、「分岐」を展開し、必要な分岐を選択して、必要に応じて、隣接する一覧のコミットIDを指定し、「選択」を押します。 *注意:* 指定したリビジョンが分岐名でマークされていない有効なコミットを表している場合、HEADがデタッチされ、分岐上にいなくなります。 1. チェックアウトされるリビジョンに固有の「コミットID」、「作成者」、「メッセージ」フィールド情報を確認します。 2. チェックアウトしたリビジョンから新しい分岐を作成するには、「新しい分岐としてチェックアウト」オプションを選択し、「分岐名」フィールドに名前を入力します。 3. 「チェックアウト」を押して、リビジョンをチェックアウトします。 作業ツリーおよび索引内のファイルが、指定したリビジョンのバージョンに一致するように更新されます。 *注意:* すでに存在する分岐(いずれかの分岐の一番上にないコミットなど)にファイルを切り替える場合、「チーム」>「Git」>「分岐」>「分岐に切替え」コマンドを使用し、「選択された分岐に切替え」ダイアログ・ボックスで分岐を指定して、(オプションで)新しい分岐としてチェックアウトし、「切替え」を押します。 IDEは、IDEで現在選択されているファイル、フォルダまたはプロジェクトの状況に応じたチェックアウトをサポートしています。索引から、一部のファイル(分岐ではなく)をチェックアウトするには、次の手順を完了します。 1. メイン・メニューから「チーム」>「チェックアウト」>「ファイルのチェックアウト」を選択します。 「選択されたパスをチェックアウト」ダイアログ・ボックスが表示されます。 [.feature] -- image::images/chkout-path-small.png[role=""left"", link=""images/chkout-path.png""] -- 1. 「選択されたリビジョンからのエントリで索引を更新」オプションを選択します。 選択した場合、チェックアウト前に選択したリビジョンの状態で索引が更新されます(作業ツリーと索引の両方の選択したファイルが更新されます)。 [start=2] . コミットID、既存の分岐またはタグ名を「リビジョン」フィールドに入力して、必要なリビジョンを指定するか、「選択」を押して、リポジトリで管理されているリビジョンの一覧を表示します。 [start=3] . 前のステップで「選択」を押さなかった場合、スキップします。「リビジョンを選択」ダイアログ・ボックスで、「分岐」を展開し、必要な分岐を選択して、必要に応じて、隣接する一覧のリビジョン番号を指定し、「選択」を押します。 [start=4] . 「チェックアウト」を押して、チェックアウトを完了します。 === マージ リポジトリ・リビジョンから変更を作業ツリーに移行するには、次のように実行します。 1. メイン・メニューから「チーム」>「分岐/タグ」>「リビジョンをマージ」を選択します。 「リビジョンをマージ」ダイアログ・ボックスが表示されます。 [.feature] -- image::images/merge-small.png[role=""left"", link=""images/merge.png""] -- 1. コミットID、既存の分岐またはタグ名を「リビジョン」フィールドに入力して、必要なリビジョンを指定するか、「選択」を押して、リポジトリで管理されているリビジョンの一覧を表示します。 2. 前のステップで「選択」を押さなかった場合、スキップします。「リビジョンを選択」ダイアログ・ボックスで、「分岐」を展開し、必要な分岐を選択して、必要に応じて、隣接する一覧のコミットIDを指定し、「選択」を押します。 3. 「マージ」を押します。 現在の分岐、作業ツリーの内容、指定した分岐間の3方向のマージが実行されます。 *注意:* マージの競合が発生した場合、競合するファイルが<>でマークされ、競合が示されます。 *注意:* マージ後、変更をHEADに追加するために、変更を<>する必要があります。 === 分岐の削除 不要なローカル分岐を削除するには、次の手順を完了します。 1. メイン・メニューから「チーム」>「リポジトリ・ブラウザ」を選択します。 2. Gitリポジトリ・ブラウザで、削除する分岐を選択します。 *注意:* 分岐は非アクティブである、つまり現在作業ツリーにチェックアウトされていない必要があります。 1. 選択した分岐を右クリックし、ポップアップ・メニューから「分岐を削除」を選択します。 2. 「分岐を削除」ダイアログ・ボックスで、「OK」を押して、分岐の削除を確認します。 分岐がローカル・リポジトリとGitリポジトリ・ブラウザから除去されます。 == リモート・リポジトリの操作 他の開発者と協力する場合、作業を共有する必要があり、これには、インターネットまたはネットワーク上でホストされるリモート・リポジトリとのデータのフェッチ、プッシュ、プルが含まれます。 * <> * <> * <> === フェッチ フェッチは、元のリモート・リポジトリからまだ持っていない変更を取得します。これは、ローカル分岐を変更しません。フェッチはリモート・リポジトリからすべての分岐を取得し、いつでも分岐にマージしたり、単に検査したりすることができます。 更新をフェッチするには、次のように実行します。 1. 「チーム」>「リモート」>「フェッチ」を選択します。 「リモート・リポジトリからフェッチ」ウィザードが表示されます。 [.feature] -- image::images/fetch-small.png[role=""left"", link=""images/fetch.png""] -- 1. ウィザードのリモート・リポジトリ・ページで、構成済のリポジトリ(以前に構成されたリポジトリへのパスを使用する)または「Gitリポジトリの場所を指定」オプション(必要に応じて、まだアクセスされていないリモート・リポジトリへのパス、その名前、ログイン、パスワード、およびプロキシ構成を定義する)を選択し、「次」をクリックします。 2. ウィザードのリモート分岐ページで、変更をフェッチする分岐を選択し、「終了」をクリックします。 リモート分岐のローカル・コピーが作成されます。Gitリポジトリ・ブラウザの「 ``分岐`` 」>「 ``リモート`` 」ディレクトリで、選択した分岐が更新されます。 次に、フェッチした更新をローカル分岐にマージできます。 === プル リモートGitリポジトリから更新をプルすると、リポジトリから変更がフェッチされ、ローカル・リポジトリの現在のHEADにマージされます。 プルを実行するには、次の手順を完了します。 1. 「チーム」>「リモート」>「プル」を選択します。 リモート・リポジトリからプル・ウィザードが表示されます。 [.feature] -- image::images/pull-small.png[role=""left"", link=""images/pull.png""] -- 1. ウィザードのリモート・リポジトリ・ページで、構成済のリポジトリ(以前に構成されたリポジトリへのパスを使用する)または「Gitリポジトリの場所を指定」オプション(必要に応じて、まだアクセスされていないリモート・リポジトリへのパス、その名前、ログインとパスワードを定義する)を選択し、「次」をクリックします。 2. ウィザードのリモート分岐ページで、変更がプルされる分岐を選択し、「終了」をクリックします。 ローカル・リポジトリが元のリポジトリと同期されます。 === プッシュ ローカルGitリポジトリの変更を公開Gitリポジトリに貢献するには、次の手順を実行します。 1. 「チーム」>「リモート」>「プッシュ」を選択します。 リモート・リポジトリへプッシュ・ウィザードが表示されます。 [.feature] -- image::images/push-small.png[role=""left"", link=""images/push.png""] -- 1. ウィザードのリモート・リポジトリ・ページで、構成済のリポジトリ(以前に構成されたリポジトリへのパスを使用する)または「Gitリポジトリの場所を指定」オプション(必要に応じて、まだアクセスされていないリモート・リポジトリへのパス、その名前、ログインとパスワードを定義する)を選択し、「次」をクリックします。 2. ローカル分岐を選択ページで、編集をプッシュする分岐を選択し、「次」をクリックします。 3. ローカル参照を更新ページで、ローカル・リポジトリの「リモート」ディレクトリ内の更新する分岐を選択し、「終了」をクリックします。 指定したリモート・リポジトリの分岐がローカル分岐の最新の状態で更新されます。 == サマリー このチュートリアルでは、IDEのGitサポートを使用する場合の標準的なワークフローを説明することによって、IDEの基本的なバージョン管理タスクの実行方法を示しました。IDEに含まれるGit固有の機能の一部を紹介しながら、バージョン管理されたプロジェクトの設定とバージョン管理されたファイルの基本タスクの実行方法を示しました。 link:/about/contact_form.html?to=3&subject=Feedback:%20Using%20Git%20Support%20in%20NetBeans%20IDE[+このチュートリアルに関するご意見をお寄せください+] == 関連項目 関連する資料については、次のドキュメントを参照してください。 * link:clearcase.html[+NetBeans IDEでのClearCaseサポートの使用+] * link:subversion.html[+NetBeans IDEでのSubversionサポートの使用+] * link:mercurial.html[+NetBeans IDEでのMercurialサポートの使用+] * link:cvs.html[+NetBeans IDEでのCVSサポートの使用+] * link:http://www.oracle.com/pls/topic/lookup?ctx=nb8000&id=NBDAG234[+NetBeans IDEによるアプリケーションの開発+]の_バージョン管理によるアプリケーションのバージョニング_ ",12242,True,2561.0512094021437,median "/** * LED Matrix control - basic I2C Slave controlling 1x-8x 8x8 MAX7219 LED Matrix displays * I2C Master * * MIT License * Copyright (C) 2019 John Plocher */ /** * Demo of the library functionality, using a simple font */ #include #include #include #define MESSAGE "" SPCoast.com "" elapsedMillis lettertime; #define LETTERTIME (500) byte letter = 0; elapsedMillis dimtime; #define DIMTIME (2 * LETTERTIME) byte dim = 0; /** * 8x8 monochrome bitmap fonts for rendering * https://github.com/dhepper/font8x8 * These header files are directly derived from an assembler file fetched from: * http://dimensionalrift.homelinux.net/combuster/mos3/?p=viewsource&file=/modules/gfx/font8_8.asm * Author: * Marcel Sondaar * International Business Machines (public domain VGA fonts) * Author: Daniel Hepper (Arduino transcode) */ byte font[128][8] = { { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0000 (nul) { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0001 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0002 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0003 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0004 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0005 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0006 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0007 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0008 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0009 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+000A { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+000B { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+000C { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+000D { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+000E { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+000F { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0010 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0011 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0012 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0013 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0014 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0015 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0016 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0017 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0018 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0019 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+001A { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+001B { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+001C { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+001D { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+001E { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+001F { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0020 (space) { 0x18, 0x3C, 0x3C, 0x18, 0x18, 0x00, 0x18, 0x00}, // U+0021 (!) { 0x36, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0022 ("") { 0x36, 0x36, 0x7F, 0x36, 0x7F, 0x36, 0x36, 0x00}, // U+0023 (#) { 0x0C, 0x3E, 0x03, 0x1E, 0x30, 0x1F, 0x0C, 0x00}, // U+0024 ($) { 0x00, 0x63, 0x33, 0x18, 0x0C, 0x66, 0x63, 0x00}, // U+0025 (%) { 0x1C, 0x36, 0x1C, 0x6E, 0x3B, 0x33, 0x6E, 0x00}, // U+0026 (&) { 0x06, 0x06, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0027 (') { 0x18, 0x0C, 0x06, 0x06, 0x06, 0x0C, 0x18, 0x00}, // U+0028 (() { 0x06, 0x0C, 0x18, 0x18, 0x18, 0x0C, 0x06, 0x00}, // U+0029 ()) { 0x00, 0x66, 0x3C, 0xFF, 0x3C, 0x66, 0x00, 0x00}, // U+002A (*) { 0x00, 0x0C, 0x0C, 0x3F, 0x0C, 0x0C, 0x00, 0x00}, // U+002B (+) { 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x06}, // U+002C (,) { 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x00}, // U+002D (-) { 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x00}, // U+002E (.) { 0x60, 0x30, 0x18, 0x0C, 0x06, 0x03, 0x01, 0x00}, // U+002F (/) { 0x3E, 0x63, 0x73, 0x7B, 0x6F, 0x67, 0x3E, 0x00}, // U+0030 (0) { 0x0C, 0x0E, 0x0C, 0x0C, 0x0C, 0x0C, 0x3F, 0x00}, // U+0031 (1) { 0x1E, 0x33, 0x30, 0x1C, 0x06, 0x33, 0x3F, 0x00}, // U+0032 (2) { 0x1E, 0x33, 0x30, 0x1C, 0x30, 0x33, 0x1E, 0x00}, // U+0033 (3) { 0x38, 0x3C, 0x36, 0x33, 0x7F, 0x30, 0x78, 0x00}, // U+0034 (4) { 0x3F, 0x03, 0x1F, 0x30, 0x30, 0x33, 0x1E, 0x00}, // U+0035 (5) { 0x1C, 0x06, 0x03, 0x1F, 0x33, 0x33, 0x1E, 0x00}, // U+0036 (6) { 0x3F, 0x33, 0x30, 0x18, 0x0C, 0x0C, 0x0C, 0x00}, // U+0037 (7) { 0x1E, 0x33, 0x33, 0x1E, 0x33, 0x33, 0x1E, 0x00}, // U+0038 (8) { 0x1E, 0x33, 0x33, 0x3E, 0x30, 0x18, 0x0E, 0x00}, // U+0039 (9) { 0x00, 0x0C, 0x0C, 0x00, 0x00, 0x0C, 0x0C, 0x00}, // U+003A (:) { 0x00, 0x0C, 0x0C, 0x00, 0x00, 0x0C, 0x0C, 0x06}, // U+003B (//) { 0x18, 0x0C, 0x06, 0x03, 0x06, 0x0C, 0x18, 0x00}, // U+003C (<) { 0x00, 0x00, 0x3F, 0x00, 0x00, 0x3F, 0x00, 0x00}, // U+003D (=) { 0x06, 0x0C, 0x18, 0x30, 0x18, 0x0C, 0x06, 0x00}, // U+003E (>) { 0x1E, 0x33, 0x30, 0x18, 0x0C, 0x00, 0x0C, 0x00}, // U+003F (?) { 0x3E, 0x63, 0x7B, 0x7B, 0x7B, 0x03, 0x1E, 0x00}, // U+0040 (@) { 0x0C, 0x1E, 0x33, 0x33, 0x3F, 0x33, 0x33, 0x00}, // U+0041 (A) { 0x3F, 0x66, 0x66, 0x3E, 0x66, 0x66, 0x3F, 0x00}, // U+0042 (B) { 0x3C, 0x66, 0x03, 0x03, 0x03, 0x66, 0x3C, 0x00}, // U+0043 (C) { 0x1F, 0x36, 0x66, 0x66, 0x66, 0x36, 0x1F, 0x00}, // U+0044 (D) { 0x7F, 0x46, 0x16, 0x1E, 0x16, 0x46, 0x7F, 0x00}, // U+0045 (E) { 0x7F, 0x46, 0x16, 0x1E, 0x16, 0x06, 0x0F, 0x00}, // U+0046 (F) { 0x3C, 0x66, 0x03, 0x03, 0x73, 0x66, 0x7C, 0x00}, // U+0047 (G) { 0x33, 0x33, 0x33, 0x3F, 0x33, 0x33, 0x33, 0x00}, // U+0048 (H) { 0x1E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+0049 (I) { 0x78, 0x30, 0x30, 0x30, 0x33, 0x33, 0x1E, 0x00}, // U+004A (J) { 0x67, 0x66, 0x36, 0x1E, 0x36, 0x66, 0x67, 0x00}, // U+004B (K) { 0x0F, 0x06, 0x06, 0x06, 0x46, 0x66, 0x7F, 0x00}, // U+004C (L) { 0x63, 0x77, 0x7F, 0x7F, 0x6B, 0x63, 0x63, 0x00}, // U+004D (M) { 0x63, 0x67, 0x6F, 0x7B, 0x73, 0x63, 0x63, 0x00}, // U+004E (N) { 0x1C, 0x36, 0x63, 0x63, 0x63, 0x36, 0x1C, 0x00}, // U+004F (O) { 0x3F, 0x66, 0x66, 0x3E, 0x06, 0x06, 0x0F, 0x00}, // U+0050 (P) { 0x1E, 0x33, 0x33, 0x33, 0x3B, 0x1E, 0x38, 0x00}, // U+0051 (Q) { 0x3F, 0x66, 0x66, 0x3E, 0x36, 0x66, 0x67, 0x00}, // U+0052 (R) { 0x1E, 0x33, 0x07, 0x0E, 0x38, 0x33, 0x1E, 0x00}, // U+0053 (S) { 0x3F, 0x2D, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+0054 (T) { 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x3F, 0x00}, // U+0055 (U) { 0x33, 0x33, 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x00}, // U+0056 (V) { 0x63, 0x63, 0x63, 0x6B, 0x7F, 0x77, 0x63, 0x00}, // U+0057 (W) { 0x63, 0x63, 0x36, 0x1C, 0x1C, 0x36, 0x63, 0x00}, // U+0058 (X) { 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x0C, 0x1E, 0x00}, // U+0059 (Y) { 0x7F, 0x63, 0x31, 0x18, 0x4C, 0x66, 0x7F, 0x00}, // U+005A (Z) { 0x1E, 0x06, 0x06, 0x06, 0x06, 0x06, 0x1E, 0x00}, // U+005B ([) { 0x03, 0x06, 0x0C, 0x18, 0x30, 0x60, 0x40, 0x00}, // U+005C (\\) { 0x1E, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1E, 0x00}, // U+005D (]) { 0x08, 0x1C, 0x36, 0x63, 0x00, 0x00, 0x00, 0x00}, // U+005E (^) { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF}, // U+005F (_) { 0x0C, 0x0C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0060 (`) { 0x00, 0x00, 0x1E, 0x30, 0x3E, 0x33, 0x6E, 0x00}, // U+0061 (a) { 0x07, 0x06, 0x06, 0x3E, 0x66, 0x66, 0x3B, 0x00}, // U+0062 (b) { 0x00, 0x00, 0x1E, 0x33, 0x03, 0x33, 0x1E, 0x00}, // U+0063 (c) { 0x38, 0x30, 0x30, 0x3e, 0x33, 0x33, 0x6E, 0x00}, // U+0064 (d) { 0x00, 0x00, 0x1E, 0x33, 0x3f, 0x03, 0x1E, 0x00}, // U+0065 (e) { 0x1C, 0x36, 0x06, 0x0f, 0x06, 0x06, 0x0F, 0x00}, // U+0066 (f) { 0x00, 0x00, 0x6E, 0x33, 0x33, 0x3E, 0x30, 0x1F}, // U+0067 (g) { 0x07, 0x06, 0x36, 0x6E, 0x66, 0x66, 0x67, 0x00}, // U+0068 (h) { 0x0C, 0x00, 0x0E, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+0069 (i) { 0x30, 0x00, 0x30, 0x30, 0x30, 0x33, 0x33, 0x1E}, // U+006A (j) { 0x07, 0x06, 0x66, 0x36, 0x1E, 0x36, 0x67, 0x00}, // U+006B (k) { 0x0E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+006C (l) { 0x00, 0x00, 0x33, 0x7F, 0x7F, 0x6B, 0x63, 0x00}, // U+006D (m) { 0x00, 0x00, 0x1F, 0x33, 0x33, 0x33, 0x33, 0x00}, // U+006E (n) { 0x00, 0x00, 0x1E, 0x33, 0x33, 0x33, 0x1E, 0x00}, // U+006F (o) { 0x00, 0x00, 0x3B, 0x66, 0x66, 0x3E, 0x06, 0x0F}, // U+0070 (p) { 0x00, 0x00, 0x6E, 0x33, 0x33, 0x3E, 0x30, 0x78}, // U+0071 (q) { 0x00, 0x00, 0x3B, 0x6E, 0x66, 0x06, 0x0F, 0x00}, // U+0072 (r) { 0x00, 0x00, 0x3E, 0x03, 0x1E, 0x30, 0x1F, 0x00}, // U+0073 (s) { 0x08, 0x0C, 0x3E, 0x0C, 0x0C, 0x2C, 0x18, 0x00}, // U+0074 (t) { 0x00, 0x00, 0x33, 0x33, 0x33, 0x33, 0x6E, 0x00}, // U+0075 (u) { 0x00, 0x00, 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x00}, // U+0076 (v) { 0x00, 0x00, 0x63, 0x6B, 0x7F, 0x7F, 0x36, 0x00}, // U+0077 (w) { 0x00, 0x00, 0x63, 0x36, 0x1C, 0x36, 0x63, 0x00}, // U+0078 (x) { 0x00, 0x00, 0x33, 0x33, 0x33, 0x3E, 0x30, 0x1F}, // U+0079 (y) { 0x00, 0x00, 0x3F, 0x19, 0x0C, 0x26, 0x3F, 0x00}, // U+007A (z) { 0x38, 0x0C, 0x0C, 0x07, 0x0C, 0x0C, 0x38, 0x00}, // U+007B ({) { 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x00}, // U+007C (|) { 0x07, 0x0C, 0x0C, 0x38, 0x0C, 0x0C, 0x07, 0x00}, // U+007D (}) { 0x6E, 0x3B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+007E (~) { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} // U+007F }; I2CMatrix *matrix; void setup() { matrix = new I2CMatrix(0x01, 2); delay(500); matrix->writeDisplay(0, font[matrix->getFWVersion() + '0']); matrix->writeDisplay(1, font[matrix->getNumDisplays() + '0']); delay(1000); } void loop() { if (dimtime > DIMTIME) { matrix->setBrightness(dim++); dimtime = 0; if (dim > 15) dim = 0; } if (lettertime > LETTERTIME) { byte nextletter = letter + 1; if (nextletter >= sizeof(MESSAGE)) nextletter = 0; byte l1, l2; l1 = (byte)MESSAGE[letter]; l2 = (byte)MESSAGE[nextletter]; matrix->writeDisplay(0, font[l1]); // test writing an 8x8 block... for(int idy = 7; idy >= 0; idy--) { // test writing 8x individual rows... matrix->writeRow(1, 7-idy, font[l2][idy]); } lettertime = 0; letter = nextletter; } } ",8272,False,2446.418153014737,median "//---------------------------- //LIST OF FUNCTIONS & ROUTINES //---------------------------- // accelCalibrate(): one-time calibration routine for the IMU and High-G acceleromters // magCalibrate(): one-time calibration routine for the IMU magnetometer. Runs separate from the acceleration calibration routine // writeCalibration(): function to store calibration values in eeprom // setOrientation: part of the acceleromter calibration routine - automatically determines the flight computer orientation and stores in eeprom //-----------CHANGE LOG------------ //17 JUL 21: initial breakout created //--------------------------------- void accelCalibrate(){ Serial.println(F(""Accelerometer Calibration Mode Confirmed. Ensure the altimeter is pointed vertical and held steady on a level surface"")); for (byte i = 1; i < 20; i++){ digitalWrite(pins.beep, HIGH); delay(250); digitalWrite(pins.beep, LOW); delay(250);} digitalWrite(pins.beep, HIGH); //reset the pointers and directions accel.ptrX = &accel.rawX; accel.ptrY = &accel.rawY; accel.ptrZ = &accel.rawZ; accel.ptrXdir = &accel.dirX; accel.ptrYdir = &accel.dirY; accel.ptrZdir = &accel.dirZ; accel.orientX = 'X'; accel.orientY = 'Y'; accel.orientZ = 'Z'; accel.dirX = accel.dirY = accel.dirZ = 1; highG.ptrX = &highG.rawX; highG.ptrY = &highG.rawY; highG.ptrZ = &highG.rawZ; highG.ptrXdir = &highG.dirX; highG.ptrYdir = &highG.dirY; highG.ptrZdir = &highG.dirZ; highG.orientX = 'X'; highG.orientY = 'Y'; highG.orientZ = 'Z'; highG.dirX = highG.dirY = highG.dirZ = 1; /*//Align the highG accelerometer to the IMU highG.dirX = (int8_t)EEPROM.read(eeprom.IMU2hiGxSign); if((char)EEPROM.read(eeprom.IMU2hiGxAxis)=='X'){highG.ptrX = &highG.rawX; highG.orientX = 'X';} if((char)EEPROM.read(eeprom.IMU2hiGxAxis)=='Y'){highG.ptrX = &highG.rawY; highG.orientX = 'Y';} if((char)EEPROM.read(eeprom.IMU2hiGxAxis)=='Z'){highG.ptrX = &highG.rawZ; highG.orientX = 'Z';} highG.dirY = (int8_t)EEPROM.read(eeprom.IMU2hiGySign); if((char)EEPROM.read(eeprom.IMU2hiGyAxis)=='X'){highG.ptrY = &highG.rawX; highG.orientY = 'X';} if((char)EEPROM.read(eeprom.IMU2hiGyAxis)=='Y'){highG.ptrY = &highG.rawY; highG.orientY = 'Y';} if((char)EEPROM.read(eeprom.IMU2hiGyAxis)=='Z'){highG.ptrY = &highG.rawZ; highG.orientY = 'Z';} highG.dirZ = (int8_t)EEPROM.read(eeprom.IMU2hiGzSign); if((char)EEPROM.read(eeprom.IMU2hiGzAxis)=='X'){highG.ptrZ = &highG.rawX; highG.orientZ = 'X';} if((char)EEPROM.read(eeprom.IMU2hiGzAxis)=='Y'){highG.ptrZ = &highG.rawY; highG.orientZ = 'Y';} if((char)EEPROM.read(eeprom.IMU2hiGzAxis)=='Z'){highG.ptrZ = &highG.rawZ; highG.orientZ = 'Z';} //align the IMU switch (sensors.accel){ //LSM303 & L3GD20H case 1: //orient to common axis accel.dirX = mag.dirX = gyro.dirX = 1; accel.dirY = mag.dirY = gyro.dirY = 1; accel.dirZ = mag.dirZ = gyro.dirZ = 1; break; //LSM9DS1 case 2: //orient to common axis accel.dirX = mag.dirX = gyro.dirX = -1; accel.dirY = mag.dirY = gyro.dirY = 1; accel.dirZ = mag.dirZ = gyro.dirZ = 1; highG.dirX *= -1; break;}*/ Serial.println(F(""Calibrating..."")); accel.biasX = accel.biasY = accel.biasZ = 0; accel.sumX0 = accel.sumY0 = accel.sumZ0 = 0; highG.biasX = highG.biasY = highG.biasZ = 0; highG.sumX0 = highG.sumY0 = highG.sumZ0 = 0; int dispData = 0; int sampSize = 10000; uint32_t delayTime = 714*(1-0.8);//average cycle time * (100% - time spent in I2C comms) for (int i = 0; i < sampSize; i++){ getAccel(); getHighG(true); dispData++; if(dispData > 1000){ Serial.print(F(""Accel X,Y,Z: ""));Serial.print(accel.rawX);Serial.print(',');Serial.print(accel.rawY);Serial.print(',');Serial.println(accel.rawZ); Serial.print(F(""highG X,Y,Z: ""));Serial.print(highG.rawX);Serial.print(',');Serial.print(highG.rawY);Serial.print(',');Serial.println(highG.rawZ); dispData = 0;} accel.sumX0 += accel.rawX; accel.sumY0 += accel.rawY; accel.sumZ0 += accel.rawZ; highG.sumX0 += highG.rawX; highG.sumY0 += highG.rawY; highG.sumZ0 += highG.rawZ; delayMicroseconds(delayTime);} //calculate the bias accel.biasX = (int)(accel.sumX0 / sampSize); accel.biasY = (int)(accel.sumY0 / sampSize); accel.biasZ = (int)(accel.sumZ0 / sampSize); highG.biasX = (int)(highG.sumX0 / sampSize); highG.biasY = (int)(highG.sumY0 / sampSize); highG.biasZ = (int)(highG.sumZ0 / sampSize); //reset the counters accel.sumX0 = accel.sumY0 = accel.sumZ0 = 0; highG.sumX0 = highG.sumY0 = highG.sumZ0 = 0; //determine the altimeter orientation setOrientation(); //Store bias in EEPROM writeCalibration(accel.biasX, eeprom.accelBiasX); writeCalibration(accel.biasY, eeprom.accelBiasY); writeCalibration(accel.biasZ, eeprom.accelBiasZ); writeCalibration(highG.biasX, eeprom.highGbiasX); writeCalibration(highG.biasY, eeprom.highGbiasY); writeCalibration(highG.biasZ, eeprom.highGbiasZ); digitalWrite(pins.beep, LOW); Serial.println(F(""Calibration complete! Calculated values are:"")); Serial.print(F(""accel.biasX: ""));Serial.println(accel.biasX); Serial.print(F(""accel.biasY: ""));Serial.println(accel.biasY); Serial.print(F(""accel.biasZ: ""));Serial.println(accel.biasZ); Serial.print(F(""highG.biasX: ""));Serial.println(highG.biasX); Serial.print(F(""highG.biasY: ""));Serial.println(highG.biasY); Serial.print(F(""highG.biasZ: ""));Serial.println(highG.biasZ); }//end accelerometer/gyro calibration void magCalibrate(){ //reset the magnetometer gain setMagGain(false); //Clear out the FIFO getMag(); delay(100); getMag(); Serial.println(F(""Magnetometer Calibration Mode"")); //give a 20 second audible warning for(byte i = 0; i < 20; i++){ digitalWrite(pins.beep, HIGH); delay(250); digitalWrite(pins.beep, LOW); delay(750);} //initialize the offsets int maxMagX, maxMagY, maxMagZ; int minMagX, minMagY, minMagZ; boolean initMag = true; mag.biasX = mag.biasY = mag.biasZ = 0; Serial.println(F(""Sampling Magnetometer"")); //sample at 10Hz for 30seconds for(int i = 0; i < 300; i++){ getMag(); Serial.print(mag.rawX);Serial.print(',');Serial.print(mag.rawY);Serial.print(',');Serial.println(mag.rawZ); if(initMag){ maxMagX = minMagX = mag.rawX; maxMagY = minMagY = mag.rawY; maxMagZ = minMagZ = mag.rawZ; initMag = false;} if(mag.rawX > maxMagX){maxMagX = mag.rawX;} if(mag.rawY > maxMagY){maxMagY = mag.rawY;} if(mag.rawZ > maxMagZ){maxMagZ = mag.rawZ;} if(mag.rawX < minMagX){minMagX = mag.rawX;} if(mag.rawY < minMagY){minMagY = mag.rawY;} if(mag.rawZ < minMagZ){minMagZ = mag.rawZ;} delay(100);} //Calculate the bias Serial.print(""minMagX: "");Serial.print(minMagX);Serial.print("", maxMagX: "");Serial.println(maxMagX); Serial.print(""minMagY: "");Serial.print(minMagY);Serial.print("", maxMagY: "");Serial.println(maxMagY); Serial.print(""minMagZ: "");Serial.print(minMagZ);Serial.print("", maxMagZ: "");Serial.println(maxMagZ); mag.biasX = (int16_t)(minMagX + (maxMagX - minMagX)/2); mag.biasY = (int16_t)(minMagY + (maxMagY - minMagY)/2); mag.biasZ = (int16_t)(minMagZ + (maxMagZ - minMagZ)/2); //Write to EEPROM writeCalibration(mag.biasX, eeprom.magBiasX); writeCalibration(mag.biasY, eeprom.magBiasY); writeCalibration(mag.biasZ, eeprom.magBiasZ); //set the variables to proceed to bench-test mode settings.testMode = true; settings.magSwitchEnable = false; Serial.println(F(""Magnetometer Calibration Complete!"")); //beep three times to signal calibration complete digitalWrite(pins.beep, HIGH); delay(200); digitalWrite(pins.beep, LOW); delay(200); digitalWrite(pins.beep, HIGH); delay(200); digitalWrite(pins.beep, LOW); delay(200); digitalWrite(pins.beep, HIGH); delay(200); digitalWrite(pins.beep, LOW); delay(2000);} //end magnetometer calibration void writeCalibration(int16_t inValue, byte eepromStart){ calUnion.calValue = inValue; EEPROM.update(eepromStart, calUnion.calByte[0]); EEPROM.update(eepromStart + 1, calUnion.calByte[1]);} void setOrientation(){ byte orientCase = 0; //determine which of the 6 possible IMU orientations is present if(abs(accel.biasZ) > abs(accel.biasY) && abs(accel.biasZ) > abs(accel.biasX) && accel.biasZ > 0){orientCase = 1;}//Main IMU Z-axis is pointed to the nose if(abs(accel.biasZ) > abs(accel.biasY) && abs(accel.biasZ) > abs(accel.biasX) && accel.biasZ < 0){orientCase = 2;}//Main IMU Z-axis is pointed to the tail if(abs(accel.biasY) > abs(accel.biasZ) && abs(accel.biasY) > abs(accel.biasX) && accel.biasY > 0){orientCase = 3;}//Main IMU Y-axis is pointed to the nose if(abs(accel.biasY) > abs(accel.biasZ) && abs(accel.biasY) > abs(accel.biasX) && accel.biasY < 0){orientCase = 4;}//Main IMU Y-axis is pointed to the tail if(abs(accel.biasX) > abs(accel.biasZ) && abs(accel.biasX) > abs(accel.biasY) && accel.biasX > 0){orientCase = 5;}//Main IMU X-axis is pointed to the nose if(abs(accel.biasX) > abs(accel.biasZ) && abs(accel.biasX) > abs(accel.biasY) && accel.biasX < 0){orientCase = 6;}//Main IMU X-axis is pointed to the tail //set the orientation variables switch (orientCase) { case 1: //Main IMU Z-axis is pointed to the nose Serial.println(""Main IMU Z-axis is pointed to the nose""); //align IMU axes accel.orientX = mag.orientX = gyro.orientX = 'X'; accel.orientY = mag.orientY = gyro.orientY = 'Y'; accel.orientZ = mag.orientZ = gyro.orientZ = 'Z'; //set IMU axes direction accel.dirX = 1; accel.dirY = 1; accel.dirZ = 1; gyro.dirX = 1; gyro.dirY = 1; gyro.dirZ = 1; mag.dirX = 1; mag.dirY = 1; mag.dirZ = 1; break; case 2: //Main IMU Z-axis is pointed to the tail Serial.println(""Main IMU Z-axis is pointed to the tail""); //align IMU axes accel.orientX = mag.orientX = gyro.orientX = 'X'; accel.orientY = mag.orientY = gyro.orientY = 'Y'; accel.orientZ = mag.orientZ = gyro.orientZ = 'Z'; //set IMU axes direction accel.dirX = -1; accel.dirY = 1; accel.dirZ = -1; gyro.dirX = -1; gyro.dirY = 1; gyro.dirZ = -1; mag.dirX = -1; mag.dirY = 1; mag.dirZ = -1; break; case 3: //Main IMU Y-axis is pointed to the nose Serial.println(""Main IMU Y-axis is pointed to the nose""); //align IMU axes accel.orientX = mag.orientX = gyro.orientX = 'X'; accel.orientY = mag.orientY = gyro.orientY = 'Z'; accel.orientZ = mag.orientZ = gyro.orientZ = 'Y'; //set IMU axes direction accel.dirX = 1; accel.dirY = 1; accel.dirZ = -1; gyro.dirX = 1; gyro.dirY = 1; gyro.dirZ = -1; mag.dirX = 1; mag.dirY = 1; mag.dirZ = -1; break; case 4: //Main IMU Y-axis is pointed to the tail Serial.println(""Main IMU Y-axis is pointed to the tail""); //align IMU axes accel.orientX = mag.orientX = gyro.orientX = 'X'; accel.orientY = mag.orientY = gyro.orientY = 'Z'; accel.orientZ = mag.orientZ = gyro.orientZ = 'Y'; //set IMU axes direction accel.dirX = 1; accel.dirY = -1; accel.dirZ = 1; gyro.dirX = 1; gyro.dirY = -1; gyro.dirZ = 1; mag.dirX = 1; mag.dirY = -1; mag.dirZ = 1; break; case 5: //Main IMU X-axis is pointed to the nose Serial.println(""Main IMU X-axis is pointed to the nose""); //align IMU axes accel.orientX = mag.orientX = gyro.orientX = 'Z'; accel.orientY = mag.orientY = gyro.orientY = 'Y'; accel.orientZ = mag.orientZ = gyro.orientZ = 'X'; //set IMU axes direction accel.dirX = 1; accel.dirY = 1; accel.dirZ = -1; gyro.dirX = 1; gyro.dirY = 1; gyro.dirZ = -1; mag.dirX = 1; mag.dirY = 1; mag.dirZ = -1; break; case 6: //Main IMU X-axis is pointed to the tail Serial.println(""Main IMU X-axis is pointed to the tail""); //align IMU axes accel.orientX = mag.orientX = gyro.orientX = 'Z'; accel.orientY = mag.orientY = gyro.orientY = 'Y'; accel.orientZ = mag.orientZ = gyro.orientZ = 'X'; //set IMU axes direction accel.dirX = -1; accel.dirY = 1; accel.dirZ = 1; gyro.dirX = -1; gyro.dirY = 1; gyro.dirZ = 1; mag.dirX = -1; mag.dirY = 1; mag.dirZ = 1; break; default: //error has occured break; }//end case //set high-G accelerometer axes if((char)EEPROM.read(eeprom.IMU2hiGzAxis)=='Z'){highG.orientZ = accel.orientZ;}//vertical axis if((char)EEPROM.read(eeprom.IMU2hiGyAxis)=='Z'){highG.orientY = accel.orientZ;} if((char)EEPROM.read(eeprom.IMU2hiGxAxis)=='Z'){highG.orientX = accel.orientZ;} if((char)EEPROM.read(eeprom.IMU2hiGzAxis)=='Y'){highG.orientZ = accel.orientY;}//horizontal y axis if((char)EEPROM.read(eeprom.IMU2hiGyAxis)=='Y'){highG.orientY = accel.orientY;} if((char)EEPROM.read(eeprom.IMU2hiGxAxis)=='Y'){highG.orientX = accel.orientY;} if((char)EEPROM.read(eeprom.IMU2hiGzAxis)=='X'){highG.orientZ = accel.orientX;}//horizontal x axis if((char)EEPROM.read(eeprom.IMU2hiGyAxis)=='X'){highG.orientY = accel.orientX;} if((char)EEPROM.read(eeprom.IMU2hiGxAxis)=='X'){highG.orientX = accel.orientX;} //set high-G accelerometer direction if((char)EEPROM.read(eeprom.IMU2hiGzAxis)=='Z'){highG.dirZ = (int8_t)EEPROM.read(eeprom.IMU2hiGzSign) * accel.dirZ;}//vertical axis if((char)EEPROM.read(eeprom.IMU2hiGyAxis)=='Z'){highG.dirY = (int8_t)EEPROM.read(eeprom.IMU2hiGySign) * accel.dirZ;} if((char)EEPROM.read(eeprom.IMU2hiGxAxis)=='Z'){highG.dirX = (int8_t)EEPROM.read(eeprom.IMU2hiGxSign) * accel.dirZ;} if((char)EEPROM.read(eeprom.IMU2hiGzAxis)=='Y'){highG.dirZ = (int8_t)EEPROM.read(eeprom.IMU2hiGzSign) * accel.dirY;}//horizontal y axis if((char)EEPROM.read(eeprom.IMU2hiGyAxis)=='Y'){highG.dirY = (int8_t)EEPROM.read(eeprom.IMU2hiGySign) * accel.dirY;} if((char)EEPROM.read(eeprom.IMU2hiGxAxis)=='Y'){highG.dirX = (int8_t)EEPROM.read(eeprom.IMU2hiGxSign) * accel.dirY;} if((char)EEPROM.read(eeprom.IMU2hiGzAxis)=='X'){highG.dirZ = (int8_t)EEPROM.read(eeprom.IMU2hiGzSign) * accel.dirX;}//horizontal x axis if((char)EEPROM.read(eeprom.IMU2hiGyAxis)=='X'){highG.dirY = (int8_t)EEPROM.read(eeprom.IMU2hiGySign) * accel.dirX;} if((char)EEPROM.read(eeprom.IMU2hiGxAxis)=='X'){highG.dirX = (int8_t)EEPROM.read(eeprom.IMU2hiGxSign) * accel.dirX;} //correct IMU bias for 1G if(accel.orientX == 'Z'){accel.biasX -= accel.dirX * g;} if(accel.orientY == 'Z'){accel.biasY -= accel.dirY * g;} if(accel.orientZ == 'Z'){accel.biasZ -= accel.dirZ * g;} //correct high-G bias for 1G if(highG.orientX == 'Z'){highG.biasX -= highG.dirX * high1G;} if(highG.orientY == 'Z'){highG.biasY -= highG.dirY * high1G;} if(highG.orientZ == 'Z'){highG.biasZ -= highG.dirZ * high1G;} //write to EEPROM //IMU EEPROM.update(eeprom.imuXsign, accel.dirX); EEPROM.update(eeprom.imuXptr, accel.orientX); EEPROM.update(eeprom.imuYsign, accel.dirY); EEPROM.update(eeprom.imuYptr, accel.orientY); EEPROM.update(eeprom.imuZsign, accel.dirZ); EEPROM.update(eeprom.imuZptr, accel.orientZ); //highG EEPROM.update(eeprom.hiGxSign, highG.dirX); EEPROM.update(eeprom.hiGxPtr, highG.orientX); EEPROM.update(eeprom.hiGySign, highG.dirY); EEPROM.update(eeprom.hiGyPtr, highG.orientY); EEPROM.update(eeprom.hiGzSign, highG.dirZ); EEPROM.update(eeprom.hiGzPtr, highG.orientZ); //display values from EEPROM Serial.print(F(""IMU.X points to Hi-G: ""));Serial.print(((int8_t)EEPROM.read(eeprom.IMU2hiGxSign) == 1) ? '+' : '-');Serial.println((char)EEPROM.read(eeprom.IMU2hiGxAxis)); Serial.print(F(""IMU.Y points to Hi-G: ""));Serial.print(((int8_t)EEPROM.read(eeprom.IMU2hiGySign) == 1) ? '+' : '-');Serial.println((char)EEPROM.read(eeprom.IMU2hiGyAxis)); Serial.print(F(""IMU.Z points to Hi-G: ""));Serial.print(((int8_t)EEPROM.read(eeprom.IMU2hiGzSign) == 1) ? '+' : '-');Serial.println((char)EEPROM.read(eeprom.IMU2hiGzAxis)); Serial.print(F(""IMU.X is pointed to real world: ""));Serial.print((accel.dirX == 1) ? '+' : '-');Serial.println(accel.orientX); Serial.print(F(""IMU.Y is pointed to real world: ""));Serial.print((accel.dirY == 1) ? '+' : '-');Serial.println(accel.orientY); Serial.print(F(""IMU.Z is pointed to real world: ""));Serial.print((accel.dirZ == 1) ? '+' : '-');Serial.println(accel.orientZ); Serial.print(F(""highG.X is pointed to real world: ""));Serial.print((highG.dirX == 1) ? '+' : '-');Serial.println(highG.orientX); Serial.print(F(""highG.Y is pointed to real world: ""));Serial.print((highG.dirY == 1) ? '+' : '-');Serial.println(highG.orientY); Serial.print(F(""highG.Z is pointed to real world: ""));Serial.print((highG.dirZ == 1) ? '+' : '-');Serial.println(highG.orientZ); }//end void void baroCalibrate(){ //exit the beeping digitalWrite(pins.beep, LOW); beep_counter = 8; //Send user message Serial.println(F(""Barometer Calibration mode initiated"")); //clear the user input while(Serial.available() > 0){char input = Serial.read();} //Display the user temperature instructions Serial.println(F(""Enter the current ambient room temperature in degrees and tenths of a degree C, or enter e to exit: "")); //wait for user input, then enter into the array while(Serial.available() == 0){delay(100);} strPosn = 0; while(Serial.available() > 0){ char input = Serial.read(); dataString[strPosn] = input; strPosn++; if(input == 'e'){Serial.println(F(""Exiting calibration"")); return;}} dataString[strPosn] = '\\0'; //parse the data float userInput = atof(dataString); Serial.print(F(""User input: ""));Serial.println(userInput, 1); Serial.println(F(""Calibrating..."")); //Sample Temperature Sensor float tempSum = 0.0F; baroTempOffset = 0.0F; for(int i = 0; i < 300; i++){ getBaro(); tempSum += temperature; delayMicroseconds(timeBtwnBaro);} baroTempOffset = (tempSum / 300) - userInput; Serial.println(baroTempOffset, 1); //Print the sample conditions Serial.println(F(""Temperature calibration complete"")); Serial.print(F(""Sampled atmospheric temperature: "")); Serial.println(tempSum/300, 1); Serial.print(""Temperature Offset: "");Serial.println(baroTempOffset, 1); //Display the user temperature instructions Serial.println(F(""Enter the current barometric pressure in hPa: "")); //wait for user input, then enter into the array while(Serial.available()==0){delay(100);} strPosn = 0; while(Serial.available() > 0){ char input = Serial.read(); dataString[strPosn] = input; strPosn++;} dataString[strPosn] = '\\0'; //parse the data userInput = atof(dataString); Serial.print(F(""User input: ""));Serial.println(userInput, 2); Serial.println(F(""Calibrating..."")); //Sample Barometer baroPressOffset = 0.0F; float baroSum = 0.0F; for(int i = 0; i < 300; i++){ getBaro(); baroSum += pressure; delayMicroseconds(timeBtwnBaro);} baroPressOffset = (baroSum / 300) - userInput; //Print the sample conditions Serial.println(F(""Barometer calibration Complete"")); Serial.print(F(""Sampled barometric pressure: "")); Serial.println(baroSum/300, 2); Serial.print(""Barometric Offset: "");Serial.print(baroPressOffset, 2); Serial.println(F("" hPa"")); //write to eeprom floatUnion.val = baroTempOffset; for(byte i = 0; i < 4; i++){EEPROM.update(eeprom.baroTempOffset + i, floatUnion.Byte[i]);} floatUnion.val = baroPressOffset; for(byte i = 0; i < 4; i++){EEPROM.update(eeprom.baroPressOffset + i, floatUnion.Byte[i]);} delay(2000); }//End of barometer calibration char a; char b; char d; void setCanardTrim(){ //Send instructions to the user Serial.println(F(""Enter the servo number and direction of rotation. Each entry will add/subtract 1 degree of Trim."")); Serial.println(F(""Ex: 2+ will move Servo #2 one degree clockwise, 6- will move Servo #6 one degree counter clockwise"")); Serial.println(F(""Send ee to exit"")); //clear the buffer while(Serial.available()>0){a = Serial.read();} //Set loop flags boolean errorFlag = false; boolean exitFlag = false; //loop and wait for the user to enter a value while(!exitFlag){ if(Serial.available() == 3){ //read data a = Serial.read(); b = Serial.read(); d = Serial.read(); //exit condition if(a == 'e' || b == 'e'){exitFlag = true;} //error check if(a!='1' && a!='2' && a!='3' && a!='4' && a!='5' && a!='6' && a!='7' && a!='8'){errorFlag = true;} if(b!='+' && b!='-'){errorFlag = true;} //update trim settings if(a=='1'){servo1trim += (b=='+'? 1 : -1); Serial.print(F(""Servo1 Trim: ""));Serial.println(servo1trim); wiggleServo(1);} if(a=='2'){servo2trim += (b=='+'? 1 : -1); Serial.print(F(""Servo2 Trim: ""));Serial.println(servo2trim); wiggleServo(2);} if(a=='3'){servo3trim += (b=='+'? 1 : -1); Serial.print(F(""Servo3 Trim: ""));Serial.println(servo3trim); wiggleServo(3);} if(a=='4'){servo4trim += (b=='+'? 1 : -1); Serial.print(F(""Servo4 Trim: ""));Serial.println(servo4trim); wiggleServo(4);} if(a=='5'){servo5trim += (b=='+'? 1 : -1); Serial.print(F(""Servo5 Trim: ""));Serial.println(servo5trim); wiggleServo(5);} if(a=='6'){servo6trim += (b=='+'? 1 : -1); Serial.print(F(""Servo6 Trim: ""));Serial.println(servo6trim); wiggleServo(6);} if(a=='7'){servo7trim += (b=='+'? 1 : -1); Serial.print(F(""Servo7 Trim: ""));Serial.println(servo7trim); wiggleServo(7);} if(a=='8'){servo8trim += (b=='+'? 1 : -1); Serial.print(F(""Servo8 Trim: ""));Serial.println(servo8trim); wiggleServo(8);}} else if(Serial.available() > 0){ Serial.print(""Sent Bytes: "");Serial.println(Serial.available()); while(Serial.available() > 0){a = (char)Serial.read(); Serial.print(a);} Serial.println(' '); errorFlag = true;} //report error message if needed if(!exitFlag && errorFlag){ Serial.println(F(""Error: Send a valid two character string. Ex: 3+"")); errorFlag = false;} delay(100); }//end trim update loop //update the EEPROM EEPROM.update(eeprom.servo1trim, servo1trim); EEPROM.update(eeprom.servo2trim, servo2trim); EEPROM.update(eeprom.servo3trim, servo3trim); EEPROM.update(eeprom.servo4trim, servo4trim); EEPROM.update(eeprom.servo5trim, servo5trim); EEPROM.update(eeprom.servo6trim, servo6trim); EEPROM.update(eeprom.servo7trim, servo7trim); EEPROM.update(eeprom.servo8trim, servo8trim); //display settings to user Serial.println(F(""FINAL SERVO TRIM SETTINGS"")); Serial.print(F(""Servo1 Trim: ""));Serial.println(servo1trim); Serial.print(F(""Servo2 Trim: ""));Serial.println(servo2trim); Serial.print(F(""Servo3 Trim: ""));Serial.println(servo3trim); Serial.print(F(""Servo4 Trim: ""));Serial.println(servo4trim); Serial.print(F(""Servo5 Trim: ""));Serial.println(servo5trim); Serial.print(F(""Servo6 Trim: ""));Serial.println(servo6trim); Serial.print(F(""Servo7 Trim: ""));Serial.println(servo7trim); Serial.print(F(""Servo8 Trim: ""));Serial.println(servo8trim); } void wiggleServo( byte servo){ switch (servo){ case 1: canardYaw1.write(80);delay(250); canardYaw1.write(100);delay(250); canardYaw1.write(90-servo1trim); break; case 2: canardYaw2.write(80);delay(250); canardYaw2.write(100);delay(250); canardYaw2.write(90-servo2trim); break; case 3: canardPitch3.write(80);delay(250); canardPitch3.write(100);delay(250); canardPitch3.write(90-servo3trim); break; case 4: canardPitch4.write(80);delay(250); canardPitch4.write(100);delay(250); canardPitch4.write(90-servo4trim); break; case 5: actionServo5.write(80);delay(250); actionServo5.write(100);delay(250); actionServo5.write(90-servo5trim); break; case 6: actionServo6.write(80);delay(250); actionServo6.write(100);delay(250); actionServo6.write(90-servo6trim); break; case 7: actionServo7.write(80);delay(250); actionServo7.write(100);delay(250); actionServo7.write(90-servo7trim); break; case 8: actionServo8.write(80);delay(250); actionServo8.write(100);delay(250); actionServo8.write(90-servo8trim); break;} }//end void wiggle servo ",8102,False,1389.6029653509802,median "// ************************************************************************************************************* // CurrentRanger(TM) stock firmware // https://lowpowerlab.com/CurrentRanger // CurrentRanger is a high-side precision current meter featuring: // - autoranging // - uni/bi-directional modes (ie. DC/AC measurements) // - ultra low burden voltage // - 1mV per nA/uA/mA measurements with DMM/scope // - OLED standalone readings // - bluetooth data logging option via 3.3v/RX/TX header // - full digital control for power/switching // - LiPo powered with auto power-off feature (0.6uA quiescent current) // ************************************************************************************************************* #ifndef CURRENT_RANGER #error You need to choose CurrentRanger board as target, see guide for details how to add it to the IDE. #endif //*********************************************************************************************************** #include //for analogReadCorrection, comes with ArduinoIDE #include //for emulated EEPROM - https://github.com/cmaglie/FlashStorage #include //https://github.com/adafruit/Adafruit_FreeTouch #include //https://github.com/olikraus/u8g2/wiki/u8g2reference fonts:https://github.com/olikraus/u8g2/wiki/fntlistall //#include //*********************************************************************************************************** #define OFFSET_LED 11 #define LPFPIN 4 #define LPFLED LED_BUILTIN #define MA 38 #define UA 2 #define NA 5 #define AUTOFF PIN_AUTO_OFF char rangeUnit = 'm'; uint32_t lastInteraction = 0; //*********************************************************************************************************** #define LDO_OUTPUT 3.3 //volts, change to actual LDO output (measure GND-3V on OLED header) //*********************************************************************************************************** #define SENSE_OUTPUT A3 #define SENSE_GNDISO A2 #define SENSE_VIN A5 #define ADCREADINGS 1 //do averaging in hardware rather than software #define VBATREADLOOPS 10 //read vbat every this many OLED_REFRESH_INTERVAL loops, originally 100 for 200 ms oled refresh #define LOBAT_THRESHOLD 3.40 //volts #define DAC_GND_ISO_OFFSET 0 #define DAC_HALF_SUPPLY_OFFSET 512 #define OUTPUT_CALIB_FACTOR 1.00 //calibrate final VOUT value #define ADC_OVERLOAD 4000 //assuming DAC output is very close to 0, this is max value less ground offset (varies from unit to unit, 4000 is a safe value) //*********************************************************************************************************** //#define ADC_CALIBRATE_EN #define ADC_CALIBRATE_FORCED //uncomment to set manual offset/gain values below rc3105 #define ADC_CALIBRATE_FORCED_OFFSET 25 #define ADC_CALIBRATE_FORCED_GAIN 2061 //*********************************************************************************************************** #define BUZZER 1 // BUZZER pin #define NOTE_C5 523 #define NOTE_D5 587 #define NOTE_E5 659 #define NOTE_F5 698 #define NOTE_G5 784 #define NOTE_A5 880 #define NOTE_B5 988 #define NOTE_C6 1047 #define TONE_BEEP 4200 //*********************************************************************************************************** #define AUTORANGING_EN #define MODE_MANUAL 0 #define MODE_AUTORANGE 1 #define STARTUP_MODE MODE_MANUAL //MODE_AUTORANGE #define SWITCHDELAY_UP 8 //ms #define SWITCHDELAY_DOWN 8 //ms #define RANGE_SWITCH_THRESHOLD_HIGH ADC_OVERLOAD //ADC's 12bit value #define RANGE_SWITCH_THRESHOLD_LOW 0 //*********************************************************************************************************** #define OLED_EN #ifdef OLED_EN #include //i2c scanner: https://playground.arduino.cc/Main/I2cScanner #define OLED_ADDRESS 0x3C //i2c address on most small OLEDs #define OLED_REFRESH_INTERVAL 1000 //ms originally 200 U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); byte OLED_found = false; #endif //*********************************************************************************************************** #define TOUCH_N 8 #define TOUCH_U 9 #define TOUCH_M A4 Adafruit_FreeTouch qt[3] = { Adafruit_FreeTouch( TOUCH_N, OVERSAMPLE_8, RESISTOR_20K, FREQ_MODE_HOP ), Adafruit_FreeTouch( TOUCH_U, OVERSAMPLE_8, RESISTOR_20K, FREQ_MODE_HOP ), Adafruit_FreeTouch( TOUCH_M, OVERSAMPLE_8, RESISTOR_20K, FREQ_MODE_HOP ), }; #define TOUCH_HIGH_THRESHOLD 600 //range is 0..1023 #define MA_PRESSED qt[2].measure()>TOUCH_HIGH_THRESHOLD #define MA_NOT_PRESSED qt[2].measure()TOUCH_HIGH_THRESHOLD #define UA_NOT_PRESSED qt[1].measure()TOUCH_HIGH_THRESHOLD #define NA_NOT_PRESSED qt[0].measure() 1MEG > SENSE_VIN > 2MEG > GND pinMode(AUTOFF, INPUT_PULLUP); pinMode(OFFSET_LED, OUTPUT); pinMode(LPFLED, OUTPUT); //STATUS/LPF-LED pinMode(LPFPIN, OUTPUT); //LPF control pin pinMode(BUZZER, OUTPUT); pinMode(MA, OUTPUT); pinMode(UA, OUTPUT); pinMode(NA, OUTPUT); qt[0].begin(); qt[1].begin(); qt[2].begin(); //touch pads analogReadResolution(12); analogWriteResolution(10); //DAC resolution //DAC->CTRLA.bit.RUNSTDBY = 0x01;delay(1); //DAC->CTRLB.bit.REFSEL=0;//pick internal reference, skip SYNCDAC (done by analogWrite) analogWrite(A0, DAC_GND_ISO_OFFSET); // Initialize Dac to OFFSET #ifdef ADC_CALIBRATE_EN #ifndef ADC_CALIBRATE_FORCED adcCorrectionCheck(); #else //or hardcoded: analogReadCorrectionForced(ADC_CALIBRATE_FORCED_OFFSET, ADC_CALIBRATE_FORCED_GAIN); //(offset, gain) - gain is 12 bit number (1 bit integer + 11bit fractional, see DS p895) // - offset is 12bit 2s complement format (p896) #endif if (OLED_found && !calibrationPerformed && MA_PRESSED) { u8g2.clearBuffer(); SerialUSB.println(""ADC calib. values:""); SerialUSB.print(""Offset=""); SerialUSB.println(offsetCorrectionValue); SerialUSB.print(""Gain=""); SerialUSB.println(gainCorrectionValue); u8g2.setFont(u8g2_font_9x15B_tf); u8g2.setCursor(0, 28); u8g2.print(""ADC CALIB:""); u8g2.setCursor(0, 40); u8g2.print(""offset:""); u8g2.setCursor(64, 40); u8g2.print(offsetCorrectionValue); u8g2.setCursor(0, 54); u8g2.print(""gain :""); u8g2.setCursor(64, 54); u8g2.print(gainCorrectionValue); u8g2.sendBuffer(); delay(2000); } #endif //BT check Serial.begin(SERIALBAUD); SerialUSB.print(""Bluetooth AT check @""); SerialUSB.print(SERIALBAUD); SerialUSB.print(""baud...""); Serial.print(""AT""); //assuming HC-06, no line ending required uint32_t timer = millis(); while (millis() - timer < 1000) //about 1s to respond { if (Serial.available() == 2 && Serial.read() == 'O' && Serial.read() == 'K') { BT_found = true; break; } BT_found = true; } //SerialUSB.print(BT_found?""OK!"":""No response. Checking for version 3.0.\\r\\n""); //rc3105 if (!BT_found) { Serial.print(""\\r\\n""); //assuming HC-06 version 3.0 that requires line ending uint32_t timer = millis(); while (millis() - timer < 50) //about 50ms to respond { if (Serial.available() == 4 && Serial.read() == 'O' && Serial.read() == 'K' && Serial.read() == '\\r' && Serial.read() == '\\n') { BT_found = true; break; } } SerialUSB.print(BT_found ? ""OK!"" : ""No response.""); } rangeNA(); // orig rangeMA(); //done in bootloader rc3105 WDTset(); /* // ADC Linearity/Bias Calibration from NVM (should already be done done in core) uint32_t bias = (*((uint32_t *) ADC_FUSES_BIASCAL_ADDR) & ADC_FUSES_BIASCAL_Msk) >> ADC_FUSES_BIASCAL_Pos; uint32_t linearity = (*((uint32_t *) ADC_FUSES_LINEARITY_0_ADDR) & ADC_FUSES_LINEARITY_0_Msk) >> ADC_FUSES_LINEARITY_0_Pos; linearity |= ((*((uint32_t *) ADC_FUSES_LINEARITY_1_ADDR) & ADC_FUSES_LINEARITY_1_Msk) >> ADC_FUSES_LINEARITY_1_Pos) << 5; ADC->CALIB.reg = ADC_CALIB_BIAS_CAL(bias) | ADC_CALIB_LINEARITY_CAL(linearity); */ if (STARTUP_MODE == MODE_AUTORANGE) toggleAutoranging(); } uint32_t oledInterval = 0, lpfInterval = 0, offsetInterval = 0, autorangeInterval = 0, btInterval = 0; byte LPF = 0, OFFSET = 0, AUTORANGE = 0; byte readVbatLoop = 0; float vbat = 0; float read1 = 0, read2 = 0, readDiff = 0; bool rangeSwitched = false; #define RANGE_MA rangeUnit=='m' #define RANGE_UA rangeUnit=='u' #define RANGE_NA rangeUnit=='n' void rangeBeep(uint16_t switch_delay = 0) { uint16_t freq = NOTE_C5; if (RANGE_UA) freq = NOTE_D5; if (RANGE_MA) freq = NOTE_E5; if (switch_delay == 0) tone(BUZZER, freq, 20); else { tone(BUZZER, freq); delay(switch_delay); noTone(BUZZER); } } void loop() { WDTclear(); //keep the dog happy handleTouchPads(); handleAutoOff(); #ifdef AUTORANGING_EN if (AUTORANGE) { readVOUT(); //assumes we only auto-range in DC mode (no bias) if (readDiff <= RANGE_SWITCH_THRESHOLD_LOW) { if (RANGE_MA) { rangeUA(); rangeSwitched = true; rangeBeep(SWITCHDELAY_DOWN); } else if (RANGE_UA) { rangeNA(); rangeSwitched = true; rangeBeep(SWITCHDELAY_DOWN); } } else if (readDiff >= RANGE_SWITCH_THRESHOLD_HIGH) { if (RANGE_NA) { rangeUA(); rangeSwitched = true; rangeBeep(SWITCHDELAY_UP); } else if (RANGE_UA) { rangeMA(); rangeSwitched = true; rangeBeep(SWITCHDELAY_UP); } } if (rangeSwitched) { rangeSwitched = false; return; } } #endif if (BT_found && millis() - btInterval > BT_REFRESH_INTERVAL) //refresh rate (ms) { btInterval = millis(); readVOUT(); float VOUT = ((readDiff) / 4096.0) * LDO_OUTPUT * 1000 * (OFFSET ? 1 : OUTPUT_CALIB_FACTOR); #if defined BT_OUTPUT_ADC Serial.println(readDiff, 0); #elif defined BT_OUTPUT_AMPS Serial.print(VOUT); Serial.print(""E""); Serial.println(RANGE_NA ? -9 : RANGE_UA ? -6 : -3); #elif defined BT_OUTPUT_NANOS //line 299 Serial.print(VOUT * (RANGE_NA ? 1 : RANGE_UA ? 1000 : 1000000)); int nanoAmps_int = (VOUT * (RANGE_NA ? 1 : RANGE_UA ? 1000 : 1000000)); Serial.print("" ""); Serial.print(nanoAmps_int); Serial.println("" ""); //rc3105 #endif //SerialUSB.println(""\\r\\nReading GND and 3.3V ADC levels""); //Serial.print(VOUT * (RANGE_NA ? 1 : RANGE_UA ? 1000 : 1000000)); nanoAmps_int = (VOUT * (RANGE_NA ? 1 : RANGE_UA ? 1000 : 1000000)); SerialUSB.print("" ""); SerialUSB.print(nanoAmps_int); SerialUSB.println("" ""); //rc3105 } //rc3105 if (OLED_found && millis() - oledInterval > OLED_REFRESH_INTERVAL) //refresh rate (ms) { oledInterval = millis(); readVOUT(); float VOUT = ((readDiff) / 4096.0) * LDO_OUTPUT * 1000 * (OFFSET ? 1 : OUTPUT_CALIB_FACTOR); u8g2.clearBuffer(); u8g2.setFont(u8g2_font_9x15B_tf); //limit how often we read the battery since it's not expected to change a lot if (readVbatLoop == 0) { vbat = adcRead(SENSE_VIN); vbat = ((vbat / 4096.0) * LDO_OUTPUT) * 1.5; //1.5 given by vbat->A5 resistor ratio } if (readVbatLoop == 100) readVbatLoop = 0; else readVbatLoop++; if (vbat < LOBAT_THRESHOLD) u8g2.drawStr(78, 12, ""LoBat!""); else { u8g2.drawStr(88, 12, ""vBat""); u8g2.setCursor(52, 12); u8g2.print(vbat); //VIN } //float VOUTDIFF = (readDiff/4096.0)*LDO_OUTPUT*1000; //*(OFFSET?1:OUTPUT_CALIB_FACTOR) if (AUTORANGE) { //u8g2.setFontMode(0); //u8g2.setDrawColor(0); u8g2.drawStr(0, 12, ""AUTO""); u8g2.setCursor(0, 24); u8g2.print(readDiff, 0); } else { u8g2.setCursor(0, 12); u8g2.print(readDiff, 0); } //u8g2.setCursor(0,24); u8g2.print(offsetCorrectionValue); //u8g2.setCursor(40,24); u8g2.print(gainCorrectionValue); u8g2.setFont(u8g2_font_helvB24_te); u8g2.setCursor(106, 64); u8g2.print('A'); u8g2.setCursor(rangeUnit == 'm' ? 102 : 106, 38); u8g2.print(rangeUnit == 'u' ? char('µ') : rangeUnit); u8g2.setFont(u8g2_font_logisoso32_tr); u8g2.setCursor(0, 64); u8g2.print((OFFSET && abs(VOUT) >= 1 || !OFFSET && VOUT >= 1) ? VOUT : 0, abs(VOUT) >= 1000 ? 0 : 1); //diff if (!OFFSET && readDiff > ADC_OVERLOAD || OFFSET && abs(readDiff) > ADC_OVERLOAD / 2) { u8g2.setFont(u8g2_font_9x15B_tf); u8g2.drawStr(0, 28, ""OVERLOAD!""); } u8g2.sendBuffer(); } } //void loop uint32_t buttonLastChange_range; uint16_t valM = 0, valU = 0, valN = 0; void handleTouchPads() { if (millis() - buttonLastChange_range < 200) return; if (MA_PRESSED || UA_PRESSED || NA_PRESSED) lastInteraction = millis(); //range switching if (!AUTORANGE) { if (MA_PRESSED && UA_NOT_PRESSED && NA_NOT_PRESSED && rangeUnit != 'm') { rangeMA(); rangeBeep(); } if (UA_PRESSED && MA_NOT_PRESSED && NA_NOT_PRESSED && rangeUnit != 'u') { rangeUA(); rangeBeep(); } if (NA_PRESSED && UA_NOT_PRESSED && MA_NOT_PRESSED && rangeUnit != 'n') { rangeNA(); rangeBeep(); } } //LPF activation --- [NA+UA] if (UA_PRESSED && NA_PRESSED && MA_NOT_PRESSED && millis() - lpfInterval > 1000) { toggleLPF(); Beep(3, false); } //offset toggling (GNDISO to half supply) --- [MA+UA] if (MA_PRESSED && UA_PRESSED && NA_NOT_PRESSED && millis() - offsetInterval > 1000) { toggleOffset(); Beep(3, false); } //AUTORANGE toggling if (MA_PRESSED && NA_PRESSED && UA_NOT_PRESSED && millis() - autorangeInterval > 1000) { toggleAutoranging(); Beep(20, false); delay(50); (20, false); } } void rangeMA() { rangeUnit = 'm'; digitalWrite(MA, HIGH); digitalWrite(UA, LOW); digitalWrite(NA, LOW); #ifdef BT_OUTPUT_ADC if (BT_found) Serial.println(""RANGE: MA""); #endif } void rangeUA() { rangeUnit = 'u'; digitalWrite(UA, HIGH); digitalWrite(MA, LOW); digitalWrite(NA, LOW); #ifdef BT_OUTPUT_ADC if (BT_found) Serial.println(""RANGE: UA""); #endif } void rangeNA() { rangeUnit = 'n'; digitalWrite(NA, HIGH); digitalWrite(MA, LOW); digitalWrite(UA, LOW); #ifdef BT_OUTPUT_ADC if (BT_found) Serial.println(""RANGE: NA""); #endif } #define AUTOFFBUZZDELAY 500 byte AUTOOFFBUZZ = 0; uint32_t autoOffBuzzInterval = 0; byte autoffWarning = false; void handleAutoOff() { #ifdef AUTOFF_EN if (millis() - lastInteraction > AUTOFF_INTERVAL - 5000) { autoffWarning = true; if (millis() - autoOffBuzzInterval > AUTOFFBUZZDELAY) { autoOffBuzzInterval = millis(); AUTOOFFBUZZ = !AUTOOFFBUZZ; if (AUTOOFFBUZZ) tone(BUZZER, NOTE_B5); else noTone(BUZZER); } if (millis() - lastInteraction > AUTOFF_INTERVAL) { pinMode(AUTOFF, OUTPUT); digitalWrite(AUTOFF, LOW); } } else if (autoffWarning) { autoffWarning = false; digitalWrite(AUTOFF, HIGH); noTone(BUZZER); } #endif } void readVOUT() { read1 = 0, read2 = 0; for (byte i = 0; i < ADCREADINGS; i++) { read1 += adcRead(SENSE_GNDISO); read2 += adcRead(SENSE_OUTPUT); //readDiff+=analogDifferentialRaw(0x1C, 0x04); //DAC-AIN4 (mux_pos,uint8_t mux_neg) //readDiff+=analogDifferentialRaw(0x04, 0x03); //AIN4-AIN3 //readDiff+=analogDifferential(SENSE_OUTPUT,SENSE_GNDISO); } read1 /= ADCREADINGS; read2 /= ADCREADINGS; readDiff = read2 - read1; } void toggleLPF() { LPF = !LPF; lpfInterval = millis(); digitalWrite(LPFPIN, LPF); digitalWrite(LPFLED, LPF); if (AUTORANGE && !LPF) toggleAutoranging(); //turn off AUTORANGE } void toggleOffset() { OFFSET = !OFFSET; offsetInterval = millis(); analogWrite(A0, (OFFSET ? DAC_HALF_SUPPLY_OFFSET : DAC_GND_ISO_OFFSET)); digitalWrite(OFFSET_LED, OFFSET); if (AUTORANGE && OFFSET) toggleAutoranging(); //turn off AUTORANGE } void toggleAutoranging() { autorangeInterval = millis(); AUTORANGE = !AUTORANGE; if (AUTORANGE && OFFSET) toggleOffset(); //turn off OFFSET if (AUTORANGE && !LPF) toggleLPF(); //turn on OFFSET } void Beep(byte theDelay, boolean twoSounds) { //if (theDelay > 20) theDelay = 20; tone(BUZZER, TONE_BEEP, theDelay); if (twoSounds) { delay(10); tone(BUZZER, 4500, theDelay); } } #define ADCSYNC while (ADC->STATUS.bit.SYNCBUSY) int adcRead(byte ADCpin) { ADC->CTRLA.bit.ENABLE = 0; // disable ADC ADCSYNC; int CTRLBoriginal = ADC->CTRLB.reg; int AVGCTRLoriginal = ADC->AVGCTRL.reg; int SAMPCTRLoriginal = ADC->SAMPCTRL.reg; ADC->CTRLB.reg &= 0b1111100011111111; // mask PRESCALER bits ADC->CTRLB.reg |= ADC_CTRLB_PRESCALER_DIV64; // divide Clock by 64 //ADC->AVGCTRL.reg = ADC_AVGCTRL_SAMPLENUM_1 | ADC_AVGCTRL_ADJRES(0x00ul); // take 1 sample, adjusting result by 0 //ADC->AVGCTRL.reg = ADC_AVGCTRL_SAMPLENUM_16 | ADC_AVGCTRL_ADJRES(0x4ul); //take 16 samples adjust by 4 ADC->AVGCTRL.reg = ADC_AVGCTRL_SAMPLENUM_1024 | ADC_AVGCTRL_ADJRES(0x4ul); //take 1024 samples adjust by 4 //sample timing (0 .. 0b111); ADC->SAMPCTRL.reg = 0b100; //0x00 fastest ADC->CTRLA.bit.ENABLE = 1; // enable ADC ADCSYNC; int adc = analogRead(ADCpin); ADC->CTRLB.reg = CTRLBoriginal; ADC->AVGCTRL.reg = AVGCTRLoriginal; ADC->SAMPCTRL.reg = SAMPCTRLoriginal; return adc; } //*********************************************************************************************************** //ADC OFFSET/GAIN CALIBRATION - adapted from SAMD_AnalogCorrection>CorrectADCResponse Example // calibration runs automatically ONCE after unit is (re)programmed, and stores calib values in EEPROM // (EEPROM is emulated and gets erased when reflashing SAMD21) //*********************************************************************************************************** #define ADC_GND_PIN A6 #define ADC_3V3_PIN A1 #define ADC_READS_SHIFT 8 #define ADC_READS_COUNT (1 << ADC_READS_SHIFT) #define ADC_MIN_GAIN 0x0400 #define ADC_UNITY_GAIN 0x0800 #define ADC_MAX_GAIN (0x1000 - 1) #define ADC_RESOLUTION_BITS 12 #define ADC_RANGE (1 << ADC_RESOLUTION_BITS) #define ADC_TOP_VALUE (ADC_RANGE - 1) #define MAX_TOP_VALUE_READS 10 FlashStorage(eeprom_ADCoffset, int); FlashStorage(eeprom_ADCgain, uint16_t); void adcCorrectionCheck() { offsetCorrectionValue = eeprom_ADCoffset.read(); gainCorrectionValue = eeprom_ADCgain.read(); if (offsetCorrectionValue == 0 && gainCorrectionValue == 0) { if (OLED_found) { u8g2.clearBuffer(); u8g2.setFont(u8g2_font_9x15B_tf); u8g2.setCursor(0, 12); u8g2.print(""ADC CALIB...""); u8g2.sendBuffer(); } delay(1000); SerialUSB.println(""Starting ADC Calibration...""); gainCorrectionValue = ADC_UNITY_GAIN; calibrateADC(); } else { analogReadCorrection(offsetCorrectionValue, gainCorrectionValue); } } void analogReadCorrectionForced(int offset, uint16_t gain) { offsetCorrectionValue = offset; gainCorrectionValue = gain; analogReadCorrection(offset, gain); } void calibrateADC() { calibrationPerformed = true; SerialUSB.println(""\\r\\nCalibrating ADC with factory values""); analogReadResolution(ADC_RESOLUTION_BITS); SerialUSB.println(""\\r\\nReading GND and 3.3V ADC levels""); SerialUSB.print("" ""); readGndLevel(); SerialUSB.print("" ""); read3V3Level(); SerialUSB.print(""\\r\\nOffset correction (@gain = ""); SerialUSB.print(gainCorrectionValue); SerialUSB.println("" (unity gain))""); // Set default correction values and enable correction analogReadCorrection(offsetCorrectionValue, gainCorrectionValue); for (int offset = 0; offset < (int)(ADC_OFFSETCORR_MASK >> 1); ++offset) { analogReadCorrection(offset, gainCorrectionValue); SerialUSB.print("" Offset = ""); SerialUSB.print(offset); SerialUSB.print("", ""); if (readGndLevel() == 0) { offsetCorrectionValue = offset; break; } } SerialUSB.println(""\\r\\nGain correction""); uint8_t topValueReadsCount = 0U; uint16_t minGain = 0U, maxGain = 0U; analogReadCorrection(offsetCorrectionValue, gainCorrectionValue); SerialUSB.print("" Gain = ""); SerialUSB.print(gainCorrectionValue); SerialUSB.print("", ""); uint16_t highLevelRead = read3V3Level(); if (highLevelRead < ADC_TOP_VALUE) { for (uint16_t gain = ADC_UNITY_GAIN + 1; gain <= ADC_MAX_GAIN; ++gain) { analogReadCorrection(offsetCorrectionValue, gain); SerialUSB.print("" Gain = ""); SerialUSB.print(gain); SerialUSB.print("", ""); highLevelRead = read3V3Level(); if (highLevelRead == ADC_TOP_VALUE) { if (minGain == 0U) minGain = gain; if (++topValueReadsCount >= MAX_TOP_VALUE_READS) { maxGain = minGain; break; } maxGain = gain; } if (highLevelRead > ADC_TOP_VALUE) break; } } else if (highLevelRead >= ADC_TOP_VALUE) { if (highLevelRead == ADC_TOP_VALUE) maxGain = ADC_UNITY_GAIN; for (uint16_t gain = ADC_UNITY_GAIN - 1; gain >= ADC_MIN_GAIN; --gain) { analogReadCorrection(offsetCorrectionValue, gain); SerialUSB.print("" Gain = ""); SerialUSB.print(gain); SerialUSB.print("", ""); highLevelRead = read3V3Level(); if (highLevelRead == ADC_TOP_VALUE) { if (maxGain == 0U) maxGain = gain; minGain = gain; } SerialUSB.print(""* LOOP : minGain=""); SerialUSB.print( minGain ); SerialUSB.print("" maxGain=""); SerialUSB.println( maxGain ); if (highLevelRead < ADC_TOP_VALUE) { if (minGain == 0U) minGain = maxGain; break; } } } gainCorrectionValue = (minGain + maxGain) >> 1; analogReadCorrection(offsetCorrectionValue, gainCorrectionValue); //save values to EEPROM eeprom_ADCoffset.write(offsetCorrectionValue); eeprom_ADCgain.write(gainCorrectionValue); if (OLED_found) { u8g2.clearBuffer(); SerialUSB.println(""ADC Calib done. Values:""); SerialUSB.print(""Offset=""); SerialUSB.println(offsetCorrectionValue); SerialUSB.print(""Gain=""); SerialUSB.println(gainCorrectionValue); u8g2.setFont(u8g2_font_9x15B_tf); u8g2.setCursor(0, 12); u8g2.print(""ADC CALIB...""); u8g2.setCursor(0, 28); u8g2.print(""DONE:""); u8g2.setCursor(0, 40); u8g2.print(""offset:""); u8g2.setCursor(64, 40); u8g2.print(offsetCorrectionValue); u8g2.setCursor(0, 54); u8g2.print(""gain :""); u8g2.setCursor(64, 54); u8g2.print(gainCorrectionValue); u8g2.sendBuffer(); delay(3000); } } uint16_t readGndLevel() { uint32_t readAccumulator = 0; for (int i = 0; i < ADC_READS_COUNT; ++i) readAccumulator += analogRead(ADC_GND_PIN); uint16_t readValue = readAccumulator >> ADC_READS_SHIFT; SerialUSB.print(""ADC(GND) = ""); SerialUSB.println(readValue); return readValue; } uint16_t read3V3Level() { uint32_t readAccumulator = 0; for (int i = 0; i < ADC_READS_COUNT; ++i) readAccumulator += analogRead(ADC_3V3_PIN); uint16_t readValue = readAccumulator >> ADC_READS_SHIFT; if (readValue < (ADC_RANGE >> 1)) readValue += ADC_RANGE; SerialUSB.print(""ADC(3.3V) = ""); SerialUSB.println(readValue); return readValue; } void WDTset() { // Generic clock generator 2, divisor = 32 (2^(DIV+1)) GCLK->GENDIV.reg = GCLK_GENDIV_ID(2) | GCLK_GENDIV_DIV(4); // Enable clock generator 2 using low-power 32KHz oscillator. With /32 divisor above, this yields 1024Hz(ish) clock. GCLK->GENCTRL.reg = GCLK_GENCTRL_ID(2) | GCLK_GENCTRL_GENEN | GCLK_GENCTRL_SRC_OSCULP32K | GCLK_GENCTRL_DIVSEL; while (GCLK->STATUS.bit.SYNCBUSY); // WDT clock = clock gen 2 GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID_WDT | GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK2; WDT->CTRL.reg = 0; //disable WDT while (WDT->STATUS.bit.SYNCBUSY); WDT->INTENCLR.bit.EW = 1; //disable early warning WDT->CONFIG.bit.PER = 0x7; //period ~1s WDT->CTRL.bit.WEN = 0; //disable window mode while (WDT->STATUS.bit.SYNCBUSY); WDTclear(); WDT->CTRL.bit.ENABLE = 1; //enable WDT while (WDT->STATUS.bit.SYNCBUSY); } void WDTclear() { WDT->CLEAR.reg = WDT_CLEAR_CLEAR_KEY; while (WDT->STATUS.bit.SYNCBUSY); } ",7947,False,1284.3889936141377,median "// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include ""content/browser/renderer_host/render_view_host_impl.h"" #include #include #include #include #include ""base/callback.h"" #include ""base/command_line.h"" #include ""base/debug/trace_event.h"" #include ""base/i18n/rtl.h"" #include ""base/json/json_reader.h"" #include ""base/message_loop/message_loop.h"" #include ""base/metrics/histogram.h"" #include ""base/stl_util.h"" #include ""base/strings/string_util.h"" #include ""base/strings/utf_string_conversions.h"" #include ""base/sys_info.h"" #include ""base/time/time.h"" #include ""base/values.h"" #include ""cc/base/switches.h"" #include ""content/browser/accessibility/browser_accessibility_manager.h"" #include ""content/browser/child_process_security_policy_impl.h"" #include ""content/browser/cross_site_request_manager.h"" #include ""content/browser/dom_storage/session_storage_namespace_impl.h"" #include ""content/browser/frame_host/frame_tree.h"" #include ""content/browser/gpu/compositor_util.h"" #include ""content/browser/gpu/gpu_data_manager_impl.h"" #include ""content/browser/gpu/gpu_process_host.h"" #include ""content/browser/gpu/gpu_surface_tracker.h"" #include ""content/browser/host_zoom_map_impl.h"" #include ""content/browser/loader/resource_dispatcher_host_impl.h"" #include ""content/browser/renderer_host/dip_util.h"" #include ""content/browser/renderer_host/input/timeout_monitor.h"" #include ""content/browser/renderer_host/media/audio_renderer_host.h"" #include ""content/browser/renderer_host/render_process_host_impl.h"" #include ""content/browser/renderer_host/render_view_host_delegate.h"" #include ""content/common/accessibility_messages.h"" #include ""content/common/browser_plugin/browser_plugin_messages.h"" #include ""content/common/content_switches_internal.h"" #include ""content/common/desktop_notification_messages.h"" #include ""content/common/drag_messages.h"" #include ""content/common/frame_messages.h"" #include ""content/common/input_messages.h"" #include ""content/common/inter_process_time_ticks_converter.h"" #include ""content/common/speech_recognition_messages.h"" #include ""content/common/swapped_out_messages.h"" #include ""content/common/view_messages.h"" #include ""content/port/browser/render_view_host_delegate_view.h"" #include ""content/port/browser/render_widget_host_view_port.h"" #include ""content/public/browser/ax_event_notification_details.h"" #include ""content/public/browser/browser_accessibility_state.h"" #include ""content/public/browser/browser_context.h"" #include ""content/public/browser/browser_message_filter.h"" #include ""content/public/browser/content_browser_client.h"" #include ""content/public/browser/native_web_keyboard_event.h"" #include ""content/public/browser/notification_details.h"" #include ""content/public/browser/notification_service.h"" #include ""content/public/browser/notification_types.h"" #include ""content/public/browser/render_frame_host.h"" #include ""content/public/browser/render_widget_host_iterator.h"" #include ""content/public/browser/user_metrics.h"" #include ""content/public/common/bindings_policy.h"" #include ""content/public/common/content_constants.h"" #include ""content/public/common/content_switches.h"" #include ""content/public/common/context_menu_params.h"" #include ""content/public/common/drop_data.h"" #include ""content/public/common/result_codes.h"" #include ""content/public/common/url_constants.h"" #include ""content/public/common/url_utils.h"" #include ""net/base/net_util.h"" #include ""net/base/network_change_notifier.h"" #include ""net/url_request/url_request_context_getter.h"" #include ""third_party/skia/include/core/SkBitmap.h"" #include ""ui/accessibility/ax_tree.h"" #include ""ui/base/touch/touch_device.h"" #include ""ui/base/touch/touch_enabled.h"" #include ""ui/base/ui_base_switches.h"" #include ""ui/gfx/image/image_skia.h"" #include ""ui/gfx/native_widget_types.h"" #include ""ui/native_theme/native_theme_switches.h"" #include ""ui/shell_dialogs/selected_file_info.h"" #include ""webkit/browser/fileapi/isolated_context.h"" #if defined(OS_MACOSX) #include ""content/browser/renderer_host/popup_menu_helper_mac.h"" #elif defined(OS_ANDROID) #include ""content/browser/media/android/browser_media_player_manager.h"" #elif defined(OS_WIN) #include ""base/win/win_util.h"" #endif using base::TimeDelta; using blink::WebConsoleMessage; using blink::WebDragOperation; using blink::WebDragOperationNone; using blink::WebDragOperationsMask; using blink::WebInputEvent; using blink::WebMediaPlayerAction; using blink::WebPluginAction; namespace content { namespace { // Translate a WebKit text direction into a base::i18n one. base::i18n::TextDirection WebTextDirectionToChromeTextDirection( blink::WebTextDirection dir) { switch (dir) { case blink::WebTextDirectionLeftToRight: return base::i18n::LEFT_TO_RIGHT; case blink::WebTextDirectionRightToLeft: return base::i18n::RIGHT_TO_LEFT; default: NOTREACHED(); return base::i18n::UNKNOWN_DIRECTION; } } #if defined(OS_WIN) const int kVirtualKeyboardDisplayWaitTimeoutMs = 100; const int kMaxVirtualKeyboardDisplayRetries = 5; void DismissVirtualKeyboardTask() { static int virtual_keyboard_display_retries = 0; // If the virtual keyboard is not yet visible, then we execute the task again // waiting for it to show up. if (!base::win::DismissVirtualKeyboard()) { if (virtual_keyboard_display_retries < kMaxVirtualKeyboardDisplayRetries) { BrowserThread::PostDelayedTask( BrowserThread::UI, FROM_HERE, base::Bind(base::IgnoreResult(&DismissVirtualKeyboardTask)), TimeDelta::FromMilliseconds(kVirtualKeyboardDisplayWaitTimeoutMs)); ++virtual_keyboard_display_retries; } else { virtual_keyboard_display_retries = 0; } } } #endif } // namespace // static const int RenderViewHostImpl::kUnloadTimeoutMS = 1000; /////////////////////////////////////////////////////////////////////////////// // RenderViewHost, public: // static bool RenderViewHostImpl::IsRVHStateActive(RenderViewHostImplState rvh_state) { if (rvh_state == STATE_DEFAULT || rvh_state == STATE_WAITING_FOR_UNLOAD_ACK || rvh_state == STATE_WAITING_FOR_COMMIT || rvh_state == STATE_WAITING_FOR_CLOSE) return true; return false; } // static RenderViewHost* RenderViewHost::FromID(int render_process_id, int render_view_id) { return RenderViewHostImpl::FromID(render_process_id, render_view_id); } // static RenderViewHost* RenderViewHost::From(RenderWidgetHost* rwh) { DCHECK(rwh->IsRenderView()); return static_cast(RenderWidgetHostImpl::From(rwh)); } /////////////////////////////////////////////////////////////////////////////// // RenderViewHostImpl, public: // static RenderViewHostImpl* RenderViewHostImpl::FromID(int render_process_id, int render_view_id) { RenderWidgetHost* widget = RenderWidgetHost::FromID(render_process_id, render_view_id); if (!widget || !widget->IsRenderView()) return NULL; return static_cast(RenderWidgetHostImpl::From(widget)); } RenderViewHostImpl::RenderViewHostImpl( SiteInstance* instance, RenderViewHostDelegate* delegate, RenderWidgetHostDelegate* widget_delegate, int routing_id, int main_frame_routing_id, bool swapped_out, bool hidden) : RenderWidgetHostImpl(widget_delegate, instance->GetProcess(), routing_id, hidden), frames_ref_count_(0), delegate_(delegate), instance_(static_cast(instance)), waiting_for_drag_context_response_(false), enabled_bindings_(0), navigations_suspended_(false), has_accessed_initial_document_(false), main_frame_routing_id_(main_frame_routing_id), run_modal_reply_msg_(NULL), run_modal_opener_id_(MSG_ROUTING_NONE), is_waiting_for_beforeunload_ack_(false), unload_ack_is_for_cross_site_transition_(false), are_javascript_messages_suppressed_(false), sudden_termination_allowed_(false), render_view_termination_status_(base::TERMINATION_STATUS_STILL_RUNNING), virtual_keyboard_requested_(false), weak_factory_(this) { DCHECK(instance_.get()); CHECK(delegate_); // http://crbug.com/82827 GetProcess()->EnableSendQueue(); if (swapped_out) { rvh_state_ = STATE_SWAPPED_OUT; } else { rvh_state_ = STATE_DEFAULT; instance_->increment_active_view_count(); } if (ResourceDispatcherHostImpl::Get()) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&ResourceDispatcherHostImpl::OnRenderViewHostCreated, base::Unretained(ResourceDispatcherHostImpl::Get()), GetProcess()->GetID(), GetRoutingID())); } #if defined(OS_ANDROID) media_player_manager_.reset(BrowserMediaPlayerManager::Create(this)); #endif unload_event_monitor_timeout_.reset(new TimeoutMonitor(base::Bind( &RenderViewHostImpl::OnSwappedOut, weak_factory_.GetWeakPtr(), true))); } RenderViewHostImpl::~RenderViewHostImpl() { if (ResourceDispatcherHostImpl::Get()) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&ResourceDispatcherHostImpl::OnRenderViewHostDeleted, base::Unretained(ResourceDispatcherHostImpl::Get()), GetProcess()->GetID(), GetRoutingID())); } delegate_->RenderViewDeleted(this); // Be sure to clean up any leftover state from cross-site requests. CrossSiteRequestManager::GetInstance()->SetHasPendingCrossSiteRequest( GetProcess()->GetID(), GetRoutingID(), false); // If this was swapped out, it already decremented the active view // count of the SiteInstance it belongs to. if (IsRVHStateActive(rvh_state_)) instance_->decrement_active_view_count(); } RenderViewHostDelegate* RenderViewHostImpl::GetDelegate() const { return delegate_; } SiteInstance* RenderViewHostImpl::GetSiteInstance() const { return instance_.get(); } bool RenderViewHostImpl::CreateRenderView( const base::string16& frame_name, int opener_route_id, int32 max_page_id) { TRACE_EVENT0(""renderer_host"", ""RenderViewHostImpl::CreateRenderView""); DCHECK(!IsRenderViewLive()) << ""Creating view twice""; // The process may (if we're sharing a process with another host that already // initialized it) or may not (we have our own process or the old process // crashed) have been initialized. Calling Init multiple times will be // ignored, so this is safe. if (!GetProcess()->Init()) return false; DCHECK(GetProcess()->HasConnection()); DCHECK(GetProcess()->GetBrowserContext()); renderer_initialized_ = true; GpuSurfaceTracker::Get()->SetSurfaceHandle( surface_id(), GetCompositingSurface()); // Ensure the RenderView starts with a next_page_id larger than any existing // page ID it might be asked to render. int32 next_page_id = 1; if (max_page_id > -1) next_page_id = max_page_id + 1; ViewMsg_New_Params params; params.renderer_preferences = delegate_->GetRendererPrefs(GetProcess()->GetBrowserContext()); params.web_preferences = delegate_->GetWebkitPrefs(); params.view_id = GetRoutingID(); params.main_frame_routing_id = main_frame_routing_id_; params.surface_id = surface_id(); params.session_storage_namespace_id = delegate_->GetSessionStorageNamespace(instance_)->id(); params.frame_name = frame_name; // Ensure the RenderView sets its opener correctly. params.opener_route_id = opener_route_id; params.swapped_out = !IsRVHStateActive(rvh_state_); params.hidden = is_hidden(); params.next_page_id = next_page_id; GetWebScreenInfo(¶ms.screen_info); params.accessibility_mode = accessibility_mode(); Send(new ViewMsg_New(params)); // If it's enabled, tell the renderer to set up the Javascript bindings for // sending messages back to the browser. if (GetProcess()->IsGuest()) DCHECK_EQ(0, enabled_bindings_); Send(new ViewMsg_AllowBindings(GetRoutingID(), enabled_bindings_)); // Let our delegate know that we created a RenderView. delegate_->RenderViewCreated(this); return true; } bool RenderViewHostImpl::IsRenderViewLive() const { return GetProcess()->HasConnection() && renderer_initialized_; } void RenderViewHostImpl::SyncRendererPrefs() { Send(new ViewMsg_SetRendererPrefs(GetRoutingID(), delegate_->GetRendererPrefs( GetProcess()->GetBrowserContext()))); } WebPreferences RenderViewHostImpl::GetWebkitPrefs(const GURL& url) { TRACE_EVENT0(""browser"", ""RenderViewHostImpl::GetWebkitPrefs""); WebPreferences prefs; const CommandLine& command_line = *CommandLine::ForCurrentProcess(); prefs.javascript_enabled = !command_line.HasSwitch(switches::kDisableJavaScript); prefs.web_security_enabled = !command_line.HasSwitch(switches::kDisableWebSecurity); prefs.plugins_enabled = !command_line.HasSwitch(switches::kDisablePlugins); prefs.java_enabled = !command_line.HasSwitch(switches::kDisableJava); prefs.remote_fonts_enabled = !command_line.HasSwitch(switches::kDisableRemoteFonts); prefs.xslt_enabled = !command_line.HasSwitch(switches::kDisableXSLT); prefs.xss_auditor_enabled = !command_line.HasSwitch(switches::kDisableXSSAuditor); prefs.application_cache_enabled = !command_line.HasSwitch(switches::kDisableApplicationCache); prefs.local_storage_enabled = !command_line.HasSwitch(switches::kDisableLocalStorage); prefs.databases_enabled = !command_line.HasSwitch(switches::kDisableDatabases); #if defined(OS_ANDROID) && defined(ARCH_CPU_X86) prefs.webaudio_enabled = command_line.HasSwitch(switches::kEnableWebAudio); #else prefs.webaudio_enabled = !command_line.HasSwitch(switches::kDisableWebAudio); #endif prefs.experimental_webgl_enabled = GpuProcessHost::gpu_enabled() && !command_line.HasSwitch(switches::kDisable3DAPIs) && !command_line.HasSwitch(switches::kDisableExperimentalWebGL); prefs.pepper_3d_enabled = !command_line.HasSwitch(switches::kDisablePepper3d); prefs.flash_3d_enabled = GpuProcessHost::gpu_enabled() && !command_line.HasSwitch(switches::kDisableFlash3d); prefs.flash_stage3d_enabled = GpuProcessHost::gpu_enabled() && !command_line.HasSwitch(switches::kDisableFlashStage3d); prefs.flash_stage3d_baseline_enabled = GpuProcessHost::gpu_enabled() && !command_line.HasSwitch(switches::kDisableFlashStage3d); prefs.gl_multisampling_enabled = !command_line.HasSwitch(switches::kDisableGLMultisampling); prefs.privileged_webgl_extensions_enabled = command_line.HasSwitch(switches::kEnablePrivilegedWebGLExtensions); prefs.site_specific_quirks_enabled = !command_line.HasSwitch(switches::kDisableSiteSpecificQuirks); prefs.allow_file_access_from_file_urls = command_line.HasSwitch(switches::kAllowFileAccessFromFiles); prefs.layer_squashing_enabled = false; if (command_line.HasSwitch(switches::kEnableLayerSquashing)) prefs.layer_squashing_enabled = true; if (command_line.HasSwitch(switches::kDisableLayerSquashing)) prefs.layer_squashing_enabled = false; prefs.show_paint_rects = command_line.HasSwitch(switches::kShowPaintRects); prefs.accelerated_compositing_enabled = GpuProcessHost::gpu_enabled() && !command_line.HasSwitch(switches::kDisableAcceleratedCompositing); prefs.force_compositing_mode = content::IsForceCompositingModeEnabled() && !command_line.HasSwitch(switches::kDisableForceCompositingMode); prefs.accelerated_2d_canvas_enabled = GpuProcessHost::gpu_enabled() && !command_line.HasSwitch(switches::kDisableAccelerated2dCanvas); prefs.antialiased_2d_canvas_disabled = command_line.HasSwitch(switches::kDisable2dCanvasAntialiasing); prefs.accelerated_2d_canvas_msaa_sample_count = atoi(command_line.GetSwitchValueASCII( switches::kAcceleratedCanvas2dMSAASampleCount).c_str()); prefs.deferred_filters_enabled = command_line.HasSwitch(switches::kEnableDeferredFilters); prefs.accelerated_compositing_for_3d_transforms_enabled = prefs.accelerated_compositing_for_animation_enabled = !command_line.HasSwitch(switches::kDisableAcceleratedLayers); prefs.accelerated_compositing_for_plugins_enabled = true; prefs.accelerated_compositing_for_video_enabled = !command_line.HasSwitch(switches::kDisableAcceleratedVideo); prefs.lazy_layout_enabled = command_line.HasSwitch(switches::kEnableExperimentalWebPlatformFeatures); prefs.region_based_columns_enabled = command_line.HasSwitch(switches::kEnableRegionBasedColumns); prefs.threaded_html_parser = !command_line.HasSwitch(switches::kDisableThreadedHTMLParser); prefs.experimental_websocket_enabled = command_line.HasSwitch(switches::kEnableExperimentalWebSocket); if (command_line.HasSwitch(cc::switches::kEnablePinchVirtualViewport)) { prefs.pinch_virtual_viewport_enabled = true; prefs.pinch_overlay_scrollbar_thickness = 10; } prefs.use_solid_color_scrollbars = ui::IsOverlayScrollbarEnabled(); #if defined(OS_ANDROID) prefs.user_gesture_required_for_media_playback = !command_line.HasSwitch( switches::kDisableGestureRequirementForMediaPlayback); prefs.user_gesture_required_for_media_fullscreen = !command_line.HasSwitch( switches::kDisableGestureRequirementForMediaFullscreen); #endif prefs.touch_enabled = ui::AreTouchEventsEnabled(); prefs.device_supports_touch = prefs.touch_enabled && ui::IsTouchDevicePresent(); #if defined(OS_ANDROID) prefs.device_supports_mouse = false; #endif prefs.pointer_events_max_touch_points = ui::MaxTouchPoints(); prefs.touch_adjustment_enabled = !command_line.HasSwitch(switches::kDisableTouchAdjustment); prefs.compositor_touch_hit_testing = !command_line.HasSwitch( cc::switches::kDisableCompositorTouchHitTesting) && !command_line.HasSwitch(switches::kEnableBleedingEdgeRenderingFastPaths); #if defined(OS_MACOSX) || defined(OS_CHROMEOS) bool default_enable_scroll_animator = true; #else bool default_enable_scroll_animator = false; #endif prefs.enable_scroll_animator = default_enable_scroll_animator; if (command_line.HasSwitch(switches::kEnableSmoothScrolling)) prefs.enable_scroll_animator = true; if (command_line.HasSwitch(switches::kDisableSmoothScrolling)) prefs.enable_scroll_animator = false; prefs.visual_word_movement_enabled = command_line.HasSwitch(switches::kEnableVisualWordMovement); // Certain GPU features might have been blacklisted. GpuDataManagerImpl::GetInstance()->UpdateRendererWebPrefs(&prefs); if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings( GetProcess()->GetID())) { prefs.loads_images_automatically = true; prefs.javascript_enabled = true; } prefs.is_online = !net::NetworkChangeNotifier::IsOffline(); prefs.fixed_position_creates_stacking_context = !command_line.HasSwitch( switches::kDisableFixedPositionCreatesStackingContext); prefs.gesture_tap_highlight_enabled = !command_line.HasSwitch( switches::kDisableGestureTapHighlight); prefs.number_of_cpu_cores = base::SysInfo::NumberOfProcessors(); prefs.viewport_meta_enabled = command_line.HasSwitch(switches::kEnableViewportMeta); prefs.viewport_enabled = command_line.HasSwitch(switches::kEnableViewport) || prefs.viewport_meta_enabled; prefs.main_frame_resizes_are_orientation_changes = command_line.HasSwitch(switches::kMainFrameResizesAreOrientationChanges); prefs.deferred_image_decoding_enabled = command_line.HasSwitch(switches::kEnableDeferredImageDecoding) || content::IsImplSidePaintingEnabled(); prefs.spatial_navigation_enabled = command_line.HasSwitch( switches::kEnableSpatialNavigation); GetContentClient()->browser()->OverrideWebkitPrefs(this, url, &prefs); // Disable compositing in guests until we have compositing path implemented // for guests. bool guest_compositing_enabled = !command_line.HasSwitch( switches::kDisableBrowserPluginCompositing); if (GetProcess()->IsGuest() && !guest_compositing_enabled) { prefs.force_compositing_mode = false; prefs.accelerated_compositing_enabled = false; } return prefs; } void RenderViewHostImpl::Navigate(const FrameMsg_Navigate_Params& params) { TRACE_EVENT0(""renderer_host"", ""RenderViewHostImpl::Navigate""); delegate_->GetFrameTree()->GetMainFrame()->Navigate(params); } void RenderViewHostImpl::NavigateToURL(const GURL& url) { delegate_->GetFrameTree()->GetMainFrame()->NavigateToURL(url); } void RenderViewHostImpl::SetNavigationsSuspended( bool suspend, const base::TimeTicks& proceed_time) { // This should only be called to toggle the state. DCHECK(navigations_suspended_ != suspend); navigations_suspended_ = suspend; if (!suspend && suspended_nav_params_) { // There's navigation message params waiting to be sent. Now that we're not // suspended anymore, resume navigation by sending them. If we were swapped // out, we should also stop filtering out the IPC messages now. SetState(STATE_DEFAULT); DCHECK(!proceed_time.is_null()); suspended_nav_params_->browser_navigation_start = proceed_time; Send(new FrameMsg_Navigate( main_frame_routing_id_, *suspended_nav_params_.get())); suspended_nav_params_.reset(); } } void RenderViewHostImpl::CancelSuspendedNavigations() { // Clear any state if a pending navigation is canceled or pre-empted. if (suspended_nav_params_) suspended_nav_params_.reset(); navigations_suspended_ = false; } void RenderViewHostImpl::SuppressDialogsUntilSwapOut() { Send(new ViewMsg_SuppressDialogsUntilSwapOut(GetRoutingID())); } void RenderViewHostImpl::OnSwappedOut(bool timed_out) { // Ignore spurious swap out ack. if (!IsWaitingForUnloadACK()) return; unload_event_monitor_timeout_->Stop(); if (timed_out) { base::ProcessHandle process_handle = GetProcess()->GetHandle(); int views = 0; // Count the number of active widget hosts for the process, which // is equivalent to views using the process as of this writing. scoped_ptr widgets( RenderWidgetHost::GetRenderWidgetHosts()); while (RenderWidgetHost* widget = widgets->GetNextHost()) { if (widget->GetProcess()->GetID() == GetProcess()->GetID()) ++views; } if (!RenderProcessHost::run_renderer_in_process() && process_handle && views <= 1) { // The process can safely be terminated, only if WebContents sets // SuddenTerminationAllowed, which indicates that the timer has expired. // This is not the case if we load data URLs or about:blank. The reason // is that those have no network requests and this code is hit without // setting the unresponsiveness timer. This allows a corner case where a // navigation to a data URL will leave a process running, if the // beforeunload handler completes fine, but the unload handler hangs. // At this time, the complexity to solve this edge case is not worthwhile. if (SuddenTerminationAllowed()) { // We should kill the process, but for now, just log the data so we can // diagnose the kill rate and investigate if separate timer is needed. // http://crbug.com/104346. // Log a histogram point to help us diagnose how many of those kills // we have performed. 1 is the enum value for RendererType Normal for // the histogram. UMA_HISTOGRAM_PERCENTAGE( ""BrowserRenderProcessHost.ChildKillsUnresponsive"", 1); } } } switch (rvh_state_) { case STATE_WAITING_FOR_UNLOAD_ACK: SetState(STATE_WAITING_FOR_COMMIT); break; case STATE_PENDING_SWAP_OUT: SetState(STATE_SWAPPED_OUT); break; case STATE_PENDING_SHUTDOWN: DCHECK(!pending_shutdown_on_swap_out_.is_null()); pending_shutdown_on_swap_out_.Run(); break; default: NOTREACHED(); } } void RenderViewHostImpl::WasSwappedOut( const base::Closure& pending_delete_on_swap_out) { Send(new ViewMsg_WasSwappedOut(GetRoutingID())); if (rvh_state_ == STATE_WAITING_FOR_UNLOAD_ACK) { SetState(STATE_PENDING_SWAP_OUT); if (!instance_->active_view_count()) SetPendingShutdown(pending_delete_on_swap_out); } else if (rvh_state_ == STATE_WAITING_FOR_COMMIT) { SetState(STATE_SWAPPED_OUT); } else if (rvh_state_ == STATE_DEFAULT) { // When the RenderView is not live, the RenderFrameHostManager will call // CommitPending directly, without calling SwapOut on the old RVH. This will // cause WasSwappedOut to be called directly on the live old RVH. DCHECK(!IsRenderViewLive()); SetState(STATE_SWAPPED_OUT); } else { NOTREACHED(); } } void RenderViewHostImpl::SetPendingShutdown(const base::Closure& on_swap_out) { pending_shutdown_on_swap_out_ = on_swap_out; SetState(STATE_PENDING_SHUTDOWN); } void RenderViewHostImpl::ClosePage() { SetState(STATE_WAITING_FOR_CLOSE); StartHangMonitorTimeout(TimeDelta::FromMilliseconds(kUnloadTimeoutMS)); if (IsRenderViewLive()) { // Since we are sending an IPC message to the renderer, increase the event // count to prevent the hang monitor timeout from being stopped by input // event acknowledgements. increment_in_flight_event_count(); // TODO(creis): Should this be moved to Shutdown? It may not be called for // RenderViewHosts that have been swapped out. NotificationService::current()->Notify( NOTIFICATION_RENDER_VIEW_HOST_WILL_CLOSE_RENDER_VIEW, Source(this), NotificationService::NoDetails()); Send(new ViewMsg_ClosePage(GetRoutingID())); } else { // This RenderViewHost doesn't have a live renderer, so just skip the unload // event and close the page. ClosePageIgnoringUnloadEvents(); } } void RenderViewHostImpl::ClosePageIgnoringUnloadEvents() { StopHangMonitorTimeout(); is_waiting_for_beforeunload_ack_ = false; sudden_termination_allowed_ = true; delegate_->Close(this); } bool RenderViewHostImpl::HasPendingCrossSiteRequest() { return CrossSiteRequestManager::GetInstance()->HasPendingCrossSiteRequest( GetProcess()->GetID(), GetRoutingID()); } void RenderViewHostImpl::SetHasPendingCrossSiteRequest( bool has_pending_request) { CrossSiteRequestManager::GetInstance()->SetHasPendingCrossSiteRequest( GetProcess()->GetID(), GetRoutingID(), has_pending_request); } #if defined(OS_ANDROID) void RenderViewHostImpl::ActivateNearestFindResult(int request_id, float x, float y) { Send(new InputMsg_ActivateNearestFindResult(GetRoutingID(), request_id, x, y)); } void RenderViewHostImpl::RequestFindMatchRects(int current_version) { Send(new ViewMsg_FindMatchRects(GetRoutingID(), current_version)); } void RenderViewHostImpl::DisableFullscreenEncryptedMediaPlayback() { media_player_manager_->DisableFullscreenEncryptedMediaPlayback(); } #endif #if defined(USE_MOJO) void RenderViewHostImpl::SetWebUIHandle(mojo::ScopedMessagePipeHandle handle) { // Never grant any bindings to browser plugin guests. if (GetProcess()->IsGuest()) { NOTREACHED() << ""Never grant bindings to a guest process.""; return; } if ((enabled_bindings_ & BINDINGS_POLICY_WEB_UI) == 0) { NOTREACHED() << ""You must grant bindings before setting the handle""; return; } DCHECK(renderer_initialized_); RenderProcessHostImpl* process = static_cast(GetProcess()); process->SetWebUIHandle(GetRoutingID(), handle.Pass()); } #endif void RenderViewHostImpl::DragTargetDragEnter( const DropData& drop_data, const gfx::Point& client_pt, const gfx::Point& screen_pt, WebDragOperationsMask operations_allowed, int key_modifiers) { const int renderer_id = GetProcess()->GetID(); ChildProcessSecurityPolicyImpl* policy = ChildProcessSecurityPolicyImpl::GetInstance(); // The URL could have been cobbled together from any highlighted text string, // and can't be interpreted as a capability. DropData filtered_data(drop_data); GetProcess()->FilterURL(true, &filtered_data.url); if (drop_data.did_originate_from_renderer) { filtered_data.filenames.clear(); } // The filenames vector, on the other hand, does represent a capability to // access the given files. fileapi::IsolatedContext::FileInfoSet files; for (std::vector::iterator iter( filtered_data.filenames.begin()); iter != filtered_data.filenames.end(); ++iter) { // A dragged file may wind up as the value of an input element, or it // may be used as the target of a navigation instead. We don't know // which will happen at this point, so generously grant both access // and request permissions to the specific file to cover both cases. // We do not give it the permission to request all file:// URLs. // Make sure we have the same display_name as the one we register. if (iter->display_name.empty()) { std::string name; files.AddPath(iter->path, &name); iter->display_name = base::FilePath::FromUTF8Unsafe(name); } else { files.AddPathWithName(iter->path, iter->display_name.AsUTF8Unsafe()); } policy->GrantRequestSpecificFileURL(renderer_id, net::FilePathToFileURL(iter->path)); // If the renderer already has permission to read these paths, we don't need // to re-grant them. This prevents problems with DnD for files in the CrOS // file manager--the file manager already had read/write access to those // directories, but dragging a file would cause the read/write access to be // overwritten with read-only access, making them impossible to delete or // rename until the renderer was killed. if (!policy->CanReadFile(renderer_id, iter->path)) policy->GrantReadFile(renderer_id, iter->path); } fileapi::IsolatedContext* isolated_context = fileapi::IsolatedContext::GetInstance(); DCHECK(isolated_context); std::string filesystem_id = isolated_context->RegisterDraggedFileSystem( files); if (!filesystem_id.empty()) { // Grant the permission iff the ID is valid. policy->GrantReadFileSystem(renderer_id, filesystem_id); } filtered_data.filesystem_id = base::UTF8ToUTF16(filesystem_id); Send(new DragMsg_TargetDragEnter(GetRoutingID(), filtered_data, client_pt, screen_pt, operations_allowed, key_modifiers)); } void RenderViewHostImpl::DragTargetDragOver( const gfx::Point& client_pt, const gfx::Point& screen_pt, WebDragOperationsMask operations_allowed, int key_modifiers) { Send(new DragMsg_TargetDragOver(GetRoutingID(), client_pt, screen_pt, operations_allowed, key_modifiers)); } void RenderViewHostImpl::DragTargetDragLeave() { Send(new DragMsg_TargetDragLeave(GetRoutingID())); } void RenderViewHostImpl::DragTargetDrop( const gfx::Point& client_pt, const gfx::Point& screen_pt, int key_modifiers) { Send(new DragMsg_TargetDrop(GetRoutingID(), client_pt, screen_pt, key_modifiers)); } void RenderViewHostImpl::DesktopNotificationPermissionRequestDone( int callback_context) { Send(new DesktopNotificationMsg_PermissionRequestDone( GetRoutingID(), callback_context)); } void RenderViewHostImpl::DesktopNotificationPostDisplay(int callback_context) { Send(new DesktopNotificationMsg_PostDisplay(GetRoutingID(), callback_context)); } void RenderViewHostImpl::DesktopNotificationPostError( int notification_id, const base::string16& message) { Send(new DesktopNotificationMsg_PostError( GetRoutingID(), notification_id, message)); } void RenderViewHostImpl::DesktopNotificationPostClose(int notification_id, bool by_user) { Send(new DesktopNotificationMsg_PostClose( GetRoutingID(), notification_id, by_user)); } void RenderViewHostImpl::DesktopNotificationPostClick(int notification_id) { Send(new DesktopNotificationMsg_PostClick(GetRoutingID(), notification_id)); } void RenderViewHostImpl::ExecuteJavascriptInWebFrame( const base::string16& frame_xpath, const base::string16& jscript) { Send(new ViewMsg_ScriptEvalRequest(GetRoutingID(), frame_xpath, jscript, 0, false)); } void RenderViewHostImpl::ExecuteJavascriptInWebFrameCallbackResult( const base::string16& frame_xpath, const base::string16& jscript, const JavascriptResultCallback& callback) { static int next_id = 1; int key = next_id++; Send(new ViewMsg_ScriptEvalRequest(GetRoutingID(), frame_xpath, jscript, key, true)); javascript_callbacks_.insert(std::make_pair(key, callback)); } void RenderViewHostImpl::JavaScriptDialogClosed( IPC::Message* reply_msg, bool success, const base::string16& user_input) { GetProcess()->SetIgnoreInputEvents(false); bool is_waiting = is_waiting_for_beforeunload_ack_ || IsWaitingForUnloadACK(); // If we are executing as part of (before)unload event handling, we don't // want to use the regular hung_renderer_delay_ms_ if the user has agreed to // leave the current page. In this case, use the regular timeout value used // during the (before)unload handling. if (is_waiting) { StartHangMonitorTimeout(TimeDelta::FromMilliseconds( success ? kUnloadTimeoutMS : hung_renderer_delay_ms_)); } ViewHostMsg_RunJavaScriptMessage::WriteReplyParams(reply_msg, success, user_input); Send(reply_msg); // If we are waiting for an unload or beforeunload ack and the user has // suppressed messages, kill the tab immediately; a page that's spamming // alerts in onbeforeunload is presumably malicious, so there's no point in // continuing to run its script and dragging out the process. // This must be done after sending the reply since RenderView can't close // correctly while waiting for a response. if (is_waiting && are_javascript_messages_suppressed_) delegate_->RendererUnresponsive( this, is_waiting_for_beforeunload_ack_, IsWaitingForUnloadACK()); } void RenderViewHostImpl::DragSourceEndedAt( int client_x, int client_y, int screen_x, int screen_y, WebDragOperation operation) { Send(new DragMsg_SourceEndedOrMoved( GetRoutingID(), gfx::Point(client_x, client_y), gfx::Point(screen_x, screen_y), true, operation)); } void RenderViewHostImpl::DragSourceMovedTo( int client_x, int client_y, int screen_x, int screen_y) { Send(new DragMsg_SourceEndedOrMoved( GetRoutingID(), gfx::Point(client_x, client_y), gfx::Point(screen_x, screen_y), false, WebDragOperationNone)); } void RenderViewHostImpl::DragSourceSystemDragEnded() { Send(new DragMsg_SourceSystemDragEnded(GetRoutingID())); } RenderFrameHost* RenderViewHostImpl::GetMainFrame() { return RenderFrameHost::FromID(GetProcess()->GetID(), main_frame_routing_id_); } void RenderViewHostImpl::AllowBindings(int bindings_flags) { // Never grant any bindings to browser plugin guests. if (GetProcess()->IsGuest()) { NOTREACHED() << ""Never grant bindings to a guest process.""; return; } // Ensure we aren't granting WebUI bindings to a process that has already // been used for non-privileged views. if (bindings_flags & BINDINGS_POLICY_WEB_UI && GetProcess()->HasConnection() && !ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings( GetProcess()->GetID())) { // This process has no bindings yet. Make sure it does not have more // than this single active view. RenderProcessHostImpl* process = static_cast(GetProcess()); if (process->GetActiveViewCount() > 1) return; } if (bindings_flags & BINDINGS_POLICY_WEB_UI) { ChildProcessSecurityPolicyImpl::GetInstance()->GrantWebUIBindings( GetProcess()->GetID()); } enabled_bindings_ |= bindings_flags; if (renderer_initialized_) Send(new ViewMsg_AllowBindings(GetRoutingID(), enabled_bindings_)); } int RenderViewHostImpl::GetEnabledBindings() const { return enabled_bindings_; } void RenderViewHostImpl::SetWebUIProperty(const std::string& name, const std::string& value) { // This is a sanity check before telling the renderer to enable the property. // It could lie and send the corresponding IPC messages anyway, but we will // not act on them if enabled_bindings_ doesn't agree. If we get here without // WebUI bindings, kill the renderer process. if (enabled_bindings_ & BINDINGS_POLICY_WEB_UI) { Send(new ViewMsg_SetWebUIProperty(GetRoutingID(), name, value)); } else { RecordAction( base::UserMetricsAction(""BindingsMismatchTerminate_RVH_WebUI"")); base::KillProcess( GetProcess()->GetHandle(), content::RESULT_CODE_KILLED, false); } } void RenderViewHostImpl::GotFocus() { RenderWidgetHostImpl::GotFocus(); // Notifies the renderer it got focus. RenderViewHostDelegateView* view = delegate_->GetDelegateView(); if (view) view->GotFocus(); } void RenderViewHostImpl::LostCapture() { RenderWidgetHostImpl::LostCapture(); delegate_->LostCapture(); } void RenderViewHostImpl::LostMouseLock() { RenderWidgetHostImpl::LostMouseLock(); delegate_->LostMouseLock(); } void RenderViewHostImpl::SetInitialFocus(bool reverse) { Send(new ViewMsg_SetInitialFocus(GetRoutingID(), reverse)); } void RenderViewHostImpl::FilesSelectedInChooser( const std::vector& files, FileChooserParams::Mode permissions) { // Grant the security access requested to the given files. for (size_t i = 0; i < files.size(); ++i) { const ui::SelectedFileInfo& file = files[i]; if (permissions == FileChooserParams::Save) { ChildProcessSecurityPolicyImpl::GetInstance()->GrantCreateReadWriteFile( GetProcess()->GetID(), file.local_path); } else { ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile( GetProcess()->GetID(), file.local_path); } } Send(new ViewMsg_RunFileChooserResponse(GetRoutingID(), files)); } void RenderViewHostImpl::DirectoryEnumerationFinished( int request_id, const std::vector& files) { // Grant the security access requested to the given files. for (std::vector::const_iterator file = files.begin(); file != files.end(); ++file) { ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile( GetProcess()->GetID(), *file); } Send(new ViewMsg_EnumerateDirectoryResponse(GetRoutingID(), request_id, files)); } void RenderViewHostImpl::LoadStateChanged( const GURL& url, const net::LoadStateWithParam& load_state, uint64 upload_position, uint64 upload_size) { delegate_->LoadStateChanged(url, load_state, upload_position, upload_size); } bool RenderViewHostImpl::SuddenTerminationAllowed() const { return sudden_termination_allowed_ || GetProcess()->SuddenTerminationAllowed(); } /////////////////////////////////////////////////////////////////////////////// // RenderViewHostImpl, IPC message handlers: bool RenderViewHostImpl::OnMessageReceived(const IPC::Message& msg) { if (!BrowserMessageFilter::CheckCanDispatchOnUI(msg, this)) return true; // Filter out most IPC messages if this renderer is swapped out. // We still want to handle certain ACKs to keep our state consistent. if (IsSwappedOut()) { if (!SwappedOutMessages::CanHandleWhileSwappedOut(msg)) { // If this is a synchronous message and we decided not to handle it, // we must send an error reply, or else the renderer will be stuck // and won't respond to future requests. if (msg.is_sync()) { IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg); reply->set_reply_error(); Send(reply); } // Don't continue looking for someone to handle it. return true; } } if (delegate_->OnMessageReceived(this, msg)) return true; bool handled = true; bool msg_is_ok = true; IPC_BEGIN_MESSAGE_MAP_EX(RenderViewHostImpl, msg, msg_is_ok) IPC_MESSAGE_HANDLER(ViewHostMsg_ShowView, OnShowView) IPC_MESSAGE_HANDLER(ViewHostMsg_ShowWidget, OnShowWidget) IPC_MESSAGE_HANDLER(ViewHostMsg_ShowFullscreenWidget, OnShowFullscreenWidget) IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_RunModal, OnRunModal) IPC_MESSAGE_HANDLER(ViewHostMsg_RenderViewReady, OnRenderViewReady) IPC_MESSAGE_HANDLER(ViewHostMsg_RenderProcessGone, OnRenderProcessGone) IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateState, OnUpdateState) IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateTitle, OnUpdateTitle) IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateEncoding, OnUpdateEncoding) IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateTargetURL, OnUpdateTargetURL) IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateInspectorSetting, OnUpdateInspectorSetting) IPC_MESSAGE_HANDLER(ViewHostMsg_Close, OnClose) IPC_MESSAGE_HANDLER(ViewHostMsg_RequestMove, OnRequestMove) IPC_MESSAGE_HANDLER(ViewHostMsg_DidChangeLoadProgress, OnDidChangeLoadProgress) IPC_MESSAGE_HANDLER(ViewHostMsg_DidDisownOpener, OnDidDisownOpener) IPC_MESSAGE_HANDLER(ViewHostMsg_DocumentAvailableInMainFrame, OnDocumentAvailableInMainFrame) IPC_MESSAGE_HANDLER(ViewHostMsg_DocumentOnLoadCompletedInMainFrame, OnDocumentOnLoadCompletedInMainFrame) IPC_MESSAGE_HANDLER(ViewHostMsg_ToggleFullscreen, OnToggleFullscreen) IPC_MESSAGE_HANDLER(ViewHostMsg_DidContentsPreferredSizeChange, OnDidContentsPreferredSizeChange) IPC_MESSAGE_HANDLER(ViewHostMsg_DidChangeScrollOffset, OnDidChangeScrollOffset) IPC_MESSAGE_HANDLER(ViewHostMsg_DidChangeScrollbarsForMainFrame, OnDidChangeScrollbarsForMainFrame) IPC_MESSAGE_HANDLER(ViewHostMsg_DidChangeScrollOffsetPinningForMainFrame, OnDidChangeScrollOffsetPinningForMainFrame) IPC_MESSAGE_HANDLER(ViewHostMsg_DidChangeNumWheelEvents, OnDidChangeNumWheelEvents) IPC_MESSAGE_HANDLER(ViewHostMsg_RouteCloseEvent, OnRouteCloseEvent) IPC_MESSAGE_HANDLER(ViewHostMsg_RouteMessageEvent, OnRouteMessageEvent) IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_RunJavaScriptMessage, OnRunJavaScriptMessage) IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_RunBeforeUnloadConfirm, OnRunBeforeUnloadConfirm) IPC_MESSAGE_HANDLER(DragHostMsg_StartDragging, OnStartDragging) IPC_MESSAGE_HANDLER(DragHostMsg_UpdateDragCursor, OnUpdateDragCursor) IPC_MESSAGE_HANDLER(DragHostMsg_TargetDrop_ACK, OnTargetDropACK) IPC_MESSAGE_HANDLER(ViewHostMsg_TakeFocus, OnTakeFocus) IPC_MESSAGE_HANDLER(ViewHostMsg_FocusedNodeChanged, OnFocusedNodeChanged) IPC_MESSAGE_HANDLER(ViewHostMsg_AddMessageToConsole, OnAddMessageToConsole) IPC_MESSAGE_HANDLER(ViewHostMsg_ClosePage_ACK, OnClosePageACK) #if defined(OS_ANDROID) IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionRootBoundsChanged, OnSelectionRootBoundsChanged) #endif IPC_MESSAGE_HANDLER(ViewHostMsg_ScriptEvalResponse, OnScriptEvalResponse) IPC_MESSAGE_HANDLER(ViewHostMsg_DidZoomURL, OnDidZoomURL) IPC_MESSAGE_HANDLER(DesktopNotificationHostMsg_RequestPermission, OnRequestDesktopNotificationPermission) IPC_MESSAGE_HANDLER(DesktopNotificationHostMsg_Show, OnShowDesktopNotification) IPC_MESSAGE_HANDLER(DesktopNotificationHostMsg_Cancel, OnCancelDesktopNotification) #if defined(OS_MACOSX) || defined(OS_ANDROID) IPC_MESSAGE_HANDLER(ViewHostMsg_ShowPopup, OnShowPopup) IPC_MESSAGE_HANDLER(ViewHostMsg_HidePopup, OnHidePopup) #endif IPC_MESSAGE_HANDLER(ViewHostMsg_RunFileChooser, OnRunFileChooser) IPC_MESSAGE_HANDLER(ViewHostMsg_DidAccessInitialDocument, OnDidAccessInitialDocument) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_Events, OnAccessibilityEvents) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_LocationChanges, OnAccessibilityLocationChanges) IPC_MESSAGE_HANDLER(ViewHostMsg_FocusedNodeTouched, OnFocusedNodeTouched) // Have the super handle all other messages. IPC_MESSAGE_UNHANDLED( handled = RenderWidgetHostImpl::OnMessageReceived(msg)) IPC_END_MESSAGE_MAP_EX() if (!msg_is_ok) { // The message had a handler, but its de-serialization failed. // Kill the renderer. RecordAction(base::UserMetricsAction(""BadMessageTerminate_RVH"")); GetProcess()->ReceivedBadMessage(); } return handled; } void RenderViewHostImpl::Init() { RenderWidgetHostImpl::Init(); } void RenderViewHostImpl::Shutdown() { // If we are being run modally (see RunModal), then we need to cleanup. if (run_modal_reply_msg_) { Send(run_modal_reply_msg_); run_modal_reply_msg_ = NULL; RenderViewHostImpl* opener = RenderViewHostImpl::FromID(GetProcess()->GetID(), run_modal_opener_id_); if (opener) { opener->StartHangMonitorTimeout(TimeDelta::FromMilliseconds( hung_renderer_delay_ms_)); // Balance out the decrement when we got created. opener->increment_in_flight_event_count(); } run_modal_opener_id_ = MSG_ROUTING_NONE; } RenderWidgetHostImpl::Shutdown(); } bool RenderViewHostImpl::IsRenderView() const { return true; } void RenderViewHostImpl::CreateNewWindow( int route_id, int main_frame_route_id, const ViewHostMsg_CreateWindow_Params& params, SessionStorageNamespace* session_storage_namespace) { ViewHostMsg_CreateWindow_Params validated_params(params); GetProcess()->FilterURL(false, &validated_params.target_url); GetProcess()->FilterURL(false, &validated_params.opener_url); GetProcess()->FilterURL(true, &validated_params.opener_security_origin); delegate_->CreateNewWindow( GetProcess()->GetID(), route_id, main_frame_route_id, validated_params, session_storage_namespace); } void RenderViewHostImpl::CreateNewWidget(int route_id, blink::WebPopupType popup_type) { delegate_->CreateNewWidget(GetProcess()->GetID(), route_id, popup_type); } void RenderViewHostImpl::CreateNewFullscreenWidget(int route_id) { delegate_->CreateNewFullscreenWidget(GetProcess()->GetID(), route_id); } void RenderViewHostImpl::OnShowView(int route_id, WindowOpenDisposition disposition, const gfx::Rect& initial_pos, bool user_gesture) { if (IsRVHStateActive(rvh_state_)) { delegate_->ShowCreatedWindow( route_id, disposition, initial_pos, user_gesture); } Send(new ViewMsg_Move_ACK(route_id)); } void RenderViewHostImpl::OnShowWidget(int route_id, const gfx::Rect& initial_pos) { if (IsRVHStateActive(rvh_state_)) delegate_->ShowCreatedWidget(route_id, initial_pos); Send(new ViewMsg_Move_ACK(route_id)); } void RenderViewHostImpl::OnShowFullscreenWidget(int route_id) { if (IsRVHStateActive(rvh_state_)) delegate_->ShowCreatedFullscreenWidget(route_id); Send(new ViewMsg_Move_ACK(route_id)); } void RenderViewHostImpl::OnRunModal(int opener_id, IPC::Message* reply_msg) { DCHECK(!run_modal_reply_msg_); run_modal_reply_msg_ = reply_msg; run_modal_opener_id_ = opener_id; RecordAction(base::UserMetricsAction(""ShowModalDialog"")); RenderViewHostImpl* opener = RenderViewHostImpl::FromID(GetProcess()->GetID(), run_modal_opener_id_); if (opener) { opener->StopHangMonitorTimeout(); // The ack for the mouse down won't come until the dialog closes, so fake it // so that we don't get a timeout. opener->decrement_in_flight_event_count(); } // TODO(darin): Bug 1107929: Need to inform our delegate to show this view in // an app-modal fashion. } void RenderViewHostImpl::OnRenderViewReady() { render_view_termination_status_ = base::TERMINATION_STATUS_STILL_RUNNING; SendScreenRects(); WasResized(); delegate_->RenderViewReady(this); } void RenderViewHostImpl::OnRenderProcessGone(int status, int exit_code) { // Keep the termination status so we can get at it later when we // need to know why it died. render_view_termination_status_ = static_cast(status); // Reset frame tree state associated with this process. delegate_->GetFrameTree()->RenderProcessGone(this); // Our base class RenderWidgetHost needs to reset some stuff. RendererExited(render_view_termination_status_, exit_code); delegate_->RenderViewTerminated(this, static_cast(status), exit_code); } void RenderViewHostImpl::OnUpdateState(int32 page_id, const PageState& state) { // Without this check, the renderer can trick the browser into using // filenames it can't access in a future session restore. if (!CanAccessFilesOfPageState(state)) { GetProcess()->ReceivedBadMessage(); return; } delegate_->UpdateState(this, page_id, state); } void RenderViewHostImpl::OnUpdateTitle( int32 page_id, const base::string16& title, blink::WebTextDirection title_direction) { if (title.length() > kMaxTitleChars) { NOTREACHED() << ""Renderer sent too many characters in title.""; return; } delegate_->UpdateTitle(this, page_id, title, WebTextDirectionToChromeTextDirection( title_direction)); } void RenderViewHostImpl::OnUpdateEncoding(const std::string& encoding_name) { delegate_->UpdateEncoding(this, encoding_name); } void RenderViewHostImpl::OnUpdateTargetURL(int32 page_id, const GURL& url) { if (IsRVHStateActive(rvh_state_)) delegate_->UpdateTargetURL(page_id, url); // Send a notification back to the renderer that we are ready to // receive more target urls. Send(new ViewMsg_UpdateTargetURL_ACK(GetRoutingID())); } void RenderViewHostImpl::OnUpdateInspectorSetting( const std::string& key, const std::string& value) { GetContentClient()->browser()->UpdateInspectorSetting( this, key, value); } void RenderViewHostImpl::OnClose() { // If the renderer is telling us to close, it has already run the unload // events, and we can take the fast path. ClosePageIgnoringUnloadEvents(); } void RenderViewHostImpl::OnRequestMove(const gfx::Rect& pos) { if (IsRVHStateActive(rvh_state_)) delegate_->RequestMove(pos); Send(new ViewMsg_Move_ACK(GetRoutingID())); } void RenderViewHostImpl::OnDidChangeLoadProgress(double load_progress) { delegate_->DidChangeLoadProgress(load_progress); } void RenderViewHostImpl::OnDidDisownOpener() { delegate_->DidDisownOpener(this); } void RenderViewHostImpl::OnDocumentAvailableInMainFrame() { delegate_->DocumentAvailableInMainFrame(this); } void RenderViewHostImpl::OnDocumentOnLoadCompletedInMainFrame( int32 page_id) { delegate_->DocumentOnLoadCompletedInMainFrame(this, page_id); } void RenderViewHostImpl::OnToggleFullscreen(bool enter_fullscreen) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); delegate_->ToggleFullscreenMode(enter_fullscreen); // We need to notify the contents that its fullscreen state has changed. This // is done as part of the resize message. WasResized(); } void RenderViewHostImpl::OnDidContentsPreferredSizeChange( const gfx::Size& new_size) { delegate_->UpdatePreferredSize(new_size); } void RenderViewHostImpl::OnRenderAutoResized(const gfx::Size& new_size) { delegate_->ResizeDueToAutoResize(new_size); } void RenderViewHostImpl::OnDidChangeScrollOffset() { if (view_) view_->ScrollOffsetChanged(); } void RenderViewHostImpl::OnDidChangeScrollbarsForMainFrame( bool has_horizontal_scrollbar, bool has_vertical_scrollbar) { if (view_) view_->SetHasHorizontalScrollbar(has_horizontal_scrollbar); } void RenderViewHostImpl::OnDidChangeScrollOffsetPinningForMainFrame( bool is_pinned_to_left, bool is_pinned_to_right) { if (view_) view_->SetScrollOffsetPinning(is_pinned_to_left, is_pinned_to_right); } void RenderViewHostImpl::OnDidChangeNumWheelEvents(int count) { } #if defined(OS_ANDROID) void RenderViewHostImpl::OnSelectionRootBoundsChanged( const gfx::Rect& bounds) { if (view_) { view_->SelectionRootBoundsChanged(bounds); } } #endif void RenderViewHostImpl::OnRouteCloseEvent() { // Have the delegate route this to the active RenderViewHost. delegate_->RouteCloseEvent(this); } void RenderViewHostImpl::OnRouteMessageEvent( const ViewMsg_PostMessage_Params& params) { // Give to the delegate to route to the active RenderViewHost. delegate_->RouteMessageEvent(this, params); } void RenderViewHostImpl::OnRunJavaScriptMessage( const base::string16& message, const base::string16& default_prompt, const GURL& frame_url, JavaScriptMessageType type, IPC::Message* reply_msg) { // While a JS message dialog is showing, tabs in the same process shouldn't // process input events. GetProcess()->SetIgnoreInputEvents(true); StopHangMonitorTimeout(); delegate_->RunJavaScriptMessage(this, message, default_prompt, frame_url, type, reply_msg, &are_javascript_messages_suppressed_); } void RenderViewHostImpl::OnRunBeforeUnloadConfirm(const GURL& frame_url, const base::string16& message, bool is_reload, IPC::Message* reply_msg) { // While a JS before unload dialog is showing, tabs in the same process // shouldn't process input events. GetProcess()->SetIgnoreInputEvents(true); StopHangMonitorTimeout(); delegate_->RunBeforeUnloadConfirm(this, message, is_reload, reply_msg); } void RenderViewHostImpl::OnStartDragging( const DropData& drop_data, WebDragOperationsMask drag_operations_mask, const SkBitmap& bitmap, const gfx::Vector2d& bitmap_offset_in_dip, const DragEventSourceInfo& event_info) { RenderViewHostDelegateView* view = delegate_->GetDelegateView(); if (!view) return; DropData filtered_data(drop_data); RenderProcessHost* process = GetProcess(); ChildProcessSecurityPolicyImpl* policy = ChildProcessSecurityPolicyImpl::GetInstance(); // Allow drag of Javascript URLs to enable bookmarklet drag to bookmark bar. if (!filtered_data.url.SchemeIs(kJavaScriptScheme)) process->FilterURL(true, &filtered_data.url); process->FilterURL(false, &filtered_data.html_base_url); // Filter out any paths that the renderer didn't have access to. This prevents // the following attack on a malicious renderer: // 1. StartDragging IPC sent with renderer-specified filesystem paths that it // doesn't have read permissions for. // 2. We initiate a native DnD operation. // 3. DnD operation immediately ends since mouse is not held down. DnD events // still fire though, which causes read permissions to be granted to the // renderer for any file paths in the drop. filtered_data.filenames.clear(); for (std::vector::const_iterator it = drop_data.filenames.begin(); it != drop_data.filenames.end(); ++it) { if (policy->CanReadFile(GetProcess()->GetID(), it->path)) filtered_data.filenames.push_back(*it); } float scale = ui::GetImageScale(GetScaleFactorForView(GetView())); gfx::ImageSkia image(gfx::ImageSkiaRep(bitmap, scale)); view->StartDragging(filtered_data, drag_operations_mask, image, bitmap_offset_in_dip, event_info); } void RenderViewHostImpl::OnUpdateDragCursor(WebDragOperation current_op) { RenderViewHostDelegateView* view = delegate_->GetDelegateView(); if (view) view->UpdateDragCursor(current_op); } void RenderViewHostImpl::OnTargetDropACK() { NotificationService::current()->Notify( NOTIFICATION_RENDER_VIEW_HOST_DID_RECEIVE_DRAG_TARGET_DROP_ACK, Source(this), NotificationService::NoDetails()); } void RenderViewHostImpl::OnTakeFocus(bool reverse) { RenderViewHostDelegateView* view = delegate_->GetDelegateView(); if (view) view->TakeFocus(reverse); } void RenderViewHostImpl::OnFocusedNodeChanged(bool is_editable_node) { if (view_) view_->FocusedNodeChanged(is_editable_node); #if defined(OS_WIN) if (!is_editable_node && virtual_keyboard_requested_) { virtual_keyboard_requested_ = false; BrowserThread::PostDelayedTask( BrowserThread::UI, FROM_HERE, base::Bind(base::IgnoreResult(&DismissVirtualKeyboardTask)), TimeDelta::FromMilliseconds(kVirtualKeyboardDisplayWaitTimeoutMs)); } #endif NotificationService::current()->Notify( NOTIFICATION_FOCUS_CHANGED_IN_PAGE, Source(this), Details(&is_editable_node)); } void RenderViewHostImpl::OnAddMessageToConsole( int32 level, const base::string16& message, int32 line_no, const base::string16& source_id) { if (delegate_->AddMessageToConsole(level, message, line_no, source_id)) return; // Pass through log level only on WebUI pages to limit console spew. int32 resolved_level = HasWebUIScheme(delegate_->GetURL()) ? level : 0; if (resolved_level >= ::logging::GetMinLogLevel()) { logging::LogMessage(""CONSOLE"", line_no, resolved_level).stream() << ""\\"""" << message << ""\\"", source: "" << source_id << "" ("" << line_no << "")""; } } void RenderViewHostImpl::OnUserGesture() { delegate_->OnUserGesture(); } void RenderViewHostImpl::OnClosePageACK() { decrement_in_flight_event_count(); ClosePageIgnoringUnloadEvents(); } void RenderViewHostImpl::NotifyRendererUnresponsive() { delegate_->RendererUnresponsive( this, is_waiting_for_beforeunload_ack_, IsWaitingForUnloadACK()); } void RenderViewHostImpl::NotifyRendererResponsive() { delegate_->RendererResponsive(this); } void RenderViewHostImpl::RequestToLockMouse(bool user_gesture, bool last_unlocked_by_target) { delegate_->RequestToLockMouse(user_gesture, last_unlocked_by_target); } bool RenderViewHostImpl::IsFullscreen() const { return delegate_->IsFullscreenForCurrentTab(); } void RenderViewHostImpl::OnFocus() { // Note: We allow focus and blur from swapped out RenderViewHosts, even when // the active RenderViewHost is in a different BrowsingInstance (e.g., WebUI). delegate_->Activate(); } void RenderViewHostImpl::OnBlur() { delegate_->Deactivate(); } gfx::Rect RenderViewHostImpl::GetRootWindowResizerRect() const { return delegate_->GetRootWindowResizerRect(); } void RenderViewHostImpl::ForwardMouseEvent( const blink::WebMouseEvent& mouse_event) { // We make a copy of the mouse event because // RenderWidgetHost::ForwardMouseEvent will delete |mouse_event|. blink::WebMouseEvent event_copy(mouse_event); RenderWidgetHostImpl::ForwardMouseEvent(event_copy); switch (event_copy.type) { case WebInputEvent::MouseMove: delegate_->HandleMouseMove(); break; case WebInputEvent::MouseLeave: delegate_->HandleMouseLeave(); break; case WebInputEvent::MouseDown: delegate_->HandleMouseDown(); break; case WebInputEvent::MouseWheel: if (ignore_input_events()) delegate_->OnIgnoredUIEvent(); break; case WebInputEvent::MouseUp: delegate_->HandleMouseUp(); default: // For now, we don't care about the rest. break; } } void RenderViewHostImpl::OnPointerEventActivate() { delegate_->HandlePointerActivate(); } void RenderViewHostImpl::ForwardKeyboardEvent( const NativeWebKeyboardEvent& key_event) { if (ignore_input_events()) { if (key_event.type == WebInputEvent::RawKeyDown) delegate_->OnIgnoredUIEvent(); return; } RenderWidgetHostImpl::ForwardKeyboardEvent(key_event); } #if defined(OS_ANDROID) void RenderViewHostImpl::DidSelectPopupMenuItems( const std::vector& selected_indices) { Send(new ViewMsg_SelectPopupMenuItems(GetRoutingID(), false, selected_indices)); } void RenderViewHostImpl::DidCancelPopupMenu() { Send(new ViewMsg_SelectPopupMenuItems(GetRoutingID(), true, std::vector())); } #endif #if defined(OS_MACOSX) void RenderViewHostImpl::DidSelectPopupMenuItem(int selected_index) { Send(new ViewMsg_SelectPopupMenuItem(GetRoutingID(), selected_index)); } void RenderViewHostImpl::DidCancelPopupMenu() { Send(new ViewMsg_SelectPopupMenuItem(GetRoutingID(), -1)); } #endif void RenderViewHostImpl::SendOrientationChangeEvent(int orientation) { Send(new ViewMsg_OrientationChangeEvent(GetRoutingID(), orientation)); } void RenderViewHostImpl::ToggleSpeechInput() { Send(new InputTagSpeechMsg_ToggleSpeechInput(GetRoutingID())); } bool RenderViewHostImpl::IsWaitingForUnloadACK() const { return rvh_state_ == STATE_WAITING_FOR_UNLOAD_ACK || rvh_state_ == STATE_WAITING_FOR_CLOSE || rvh_state_ == STATE_PENDING_SHUTDOWN || rvh_state_ == STATE_PENDING_SWAP_OUT; } void RenderViewHostImpl::ExitFullscreen() { RejectMouseLockOrUnlockIfNecessary(); // Notify delegate_ and renderer of fullscreen state change. OnToggleFullscreen(false); } WebPreferences RenderViewHostImpl::GetWebkitPreferences() { return delegate_->GetWebkitPrefs(); } void RenderViewHostImpl::DisownOpener() { // This should only be called when swapped out. DCHECK(IsSwappedOut()); Send(new ViewMsg_DisownOpener(GetRoutingID())); } void RenderViewHostImpl::SetAccessibilityCallbackForTesting( const base::Callback& callback) { accessibility_testing_callback_ = callback; } void RenderViewHostImpl::UpdateWebkitPreferences(const WebPreferences& prefs) { Send(new ViewMsg_UpdateWebPreferences(GetRoutingID(), prefs)); } void RenderViewHostImpl::GetAudioOutputControllers( const GetAudioOutputControllersCallback& callback) const { AudioRendererHost* audio_host = static_cast(GetProcess())->audio_renderer_host(); audio_host->GetOutputControllers(GetRoutingID(), callback); } void RenderViewHostImpl::ClearFocusedElement() { Send(new ViewMsg_ClearFocusedElement(GetRoutingID())); } void RenderViewHostImpl::Zoom(PageZoom zoom) { Send(new ViewMsg_Zoom(GetRoutingID(), zoom)); } void RenderViewHostImpl::ReloadFrame() { Send(new ViewMsg_ReloadFrame(GetRoutingID())); } void RenderViewHostImpl::DisableScrollbarsForThreshold(const gfx::Size& size) { Send(new ViewMsg_DisableScrollbarsForSmallWindows(GetRoutingID(), size)); } void RenderViewHostImpl::EnablePreferredSizeMode() { Send(new ViewMsg_EnablePreferredSizeChangedMode(GetRoutingID())); } void RenderViewHostImpl::EnableAutoResize(const gfx::Size& min_size, const gfx::Size& max_size) { SetShouldAutoResize(true); Send(new ViewMsg_EnableAutoResize(GetRoutingID(), min_size, max_size)); } void RenderViewHostImpl::DisableAutoResize(const gfx::Size& new_size) { SetShouldAutoResize(false); Send(new ViewMsg_DisableAutoResize(GetRoutingID(), new_size)); } void RenderViewHostImpl::CopyImageAt(int x, int y) { Send(new ViewMsg_CopyImageAt(GetRoutingID(), x, y)); } void RenderViewHostImpl::ExecuteMediaPlayerActionAtLocation( const gfx::Point& location, const blink::WebMediaPlayerAction& action) { Send(new ViewMsg_MediaPlayerActionAt(GetRoutingID(), location, action)); } void RenderViewHostImpl::ExecutePluginActionAtLocation( const gfx::Point& location, const blink::WebPluginAction& action) { Send(new ViewMsg_PluginActionAt(GetRoutingID(), location, action)); } void RenderViewHostImpl::NotifyMoveOrResizeStarted() { Send(new ViewMsg_MoveOrResizeStarted(GetRoutingID())); } void RenderViewHostImpl::OnAccessibilityEvents( const std::vector& params) { if ((accessibility_mode() != AccessibilityModeOff) && view_ && IsRVHStateActive(rvh_state_)) { if (accessibility_mode() & AccessibilityModeFlagPlatform) { view_->CreateBrowserAccessibilityManagerIfNeeded(); BrowserAccessibilityManager* manager = view_->GetBrowserAccessibilityManager(); if (manager) manager->OnAccessibilityEvents(params); } std::vector details; for (unsigned int i = 0; i < params.size(); ++i) { const AccessibilityHostMsg_EventParams& param = params[i]; AXEventNotificationDetails detail( param.nodes, param.event_type, param.id, GetRoutingID()); details.push_back(detail); } delegate_->AccessibilityEventReceived(details); } // Always send an ACK or the renderer can be in a bad state. Send(new AccessibilityMsg_Events_ACK(GetRoutingID())); // The rest of this code is just for testing; bail out if we're not // in that mode. if (accessibility_testing_callback_.is_null()) return; for (unsigned i = 0; i < params.size(); i++) { const AccessibilityHostMsg_EventParams& param = params[i]; if (static_cast(param.event_type) < 0) continue; ui::AXTreeUpdate update; update.nodes = param.nodes; if (!ax_tree_) ax_tree_.reset(new ui::AXTree(update)); else CHECK(ax_tree_->Unserialize(update)) << ax_tree_->error(); accessibility_testing_callback_.Run(param.event_type); } } void RenderViewHostImpl::OnAccessibilityLocationChanges( const std::vector& params) { if (view_ && IsRVHStateActive(rvh_state_)) { if (accessibility_mode() & AccessibilityModeFlagPlatform) { view_->CreateBrowserAccessibilityManagerIfNeeded(); BrowserAccessibilityManager* manager = view_->GetBrowserAccessibilityManager(); if (manager) manager->OnLocationChanges(params); } // TODO(aboxhall): send location change events to web contents observers too } } void RenderViewHostImpl::OnScriptEvalResponse(int id, const base::ListValue& result) { const base::Value* result_value; if (!result.Get(0, &result_value)) { // Programming error or rogue renderer. NOTREACHED() << ""Got bad arguments for OnScriptEvalResponse""; return; } std::map::iterator it = javascript_callbacks_.find(id); if (it != javascript_callbacks_.end()) { // ExecuteJavascriptInWebFrameCallbackResult was used; do callback. it->second.Run(result_value); javascript_callbacks_.erase(it); } else { NOTREACHED() << ""Received script response for unknown request""; } } void RenderViewHostImpl::OnDidZoomURL(double zoom_level, bool remember, const GURL& url) { HostZoomMapImpl* host_zoom_map = static_cast( HostZoomMap::GetForBrowserContext(GetProcess()->GetBrowserContext())); if (remember) { host_zoom_map-> SetZoomLevelForHost(net::GetHostOrSpecFromURL(url), zoom_level); } else { host_zoom_map->SetTemporaryZoomLevel( GetProcess()->GetID(), GetRoutingID(), zoom_level); } } void RenderViewHostImpl::OnRequestDesktopNotificationPermission( const GURL& source_origin, int callback_context) { GetContentClient()->browser()->RequestDesktopNotificationPermission( source_origin, callback_context, GetProcess()->GetID(), GetRoutingID()); } void RenderViewHostImpl::OnShowDesktopNotification( const ShowDesktopNotificationHostMsgParams& params) { GetContentClient()->browser()->ShowDesktopNotification( params, GetProcess()->GetID(), GetRoutingID(), false); } void RenderViewHostImpl::OnCancelDesktopNotification(int notification_id) { GetContentClient()->browser()->CancelDesktopNotification( GetProcess()->GetID(), GetRoutingID(), notification_id); } void RenderViewHostImpl::OnRunFileChooser(const FileChooserParams& params) { delegate_->RunFileChooser(this, params); } void RenderViewHostImpl::OnDidAccessInitialDocument() { has_accessed_initial_document_ = true; delegate_->DidAccessInitialDocument(); } void RenderViewHostImpl::OnFocusedNodeTouched(bool editable) { #if defined(OS_WIN) if (editable) { virtual_keyboard_requested_ = base::win::DisplayVirtualKeyboard(); } else { virtual_keyboard_requested_ = false; base::win::DismissVirtualKeyboard(); } #endif } #if defined(OS_MACOSX) || defined(OS_ANDROID) void RenderViewHostImpl::OnShowPopup( const ViewHostMsg_ShowPopup_Params& params) { RenderViewHostDelegateView* view = delegate_->GetDelegateView(); if (view) { view->ShowPopupMenu(params.bounds, params.item_height, params.item_font_size, params.selected_item, params.popup_items, params.right_aligned, params.allow_multiple_selection); } } void RenderViewHostImpl::OnHidePopup() { RenderViewHostDelegateView* view = delegate_->GetDelegateView(); if (view) view->HidePopupMenu(); } #endif void RenderViewHostImpl::SetState(RenderViewHostImplState rvh_state) { // We update the number of RenderViews in a SiteInstance when the // swapped out status of this RenderView gets flipped to/from live. if (!IsRVHStateActive(rvh_state_) && IsRVHStateActive(rvh_state)) instance_->increment_active_view_count(); else if (IsRVHStateActive(rvh_state_) && !IsRVHStateActive(rvh_state)) instance_->decrement_active_view_count(); // Whenever we change the RVH state to and from live or swapped out state, we // should not be waiting for beforeunload or unload acks. We clear them here // to be safe, since they can cause navigations to be ignored in OnNavigate. if (rvh_state == STATE_DEFAULT || rvh_state == STATE_SWAPPED_OUT || rvh_state_ == STATE_DEFAULT || rvh_state_ == STATE_SWAPPED_OUT) { is_waiting_for_beforeunload_ack_ = false; } rvh_state_ = rvh_state; } bool RenderViewHostImpl::CanAccessFilesOfPageState( const PageState& state) const { ChildProcessSecurityPolicyImpl* policy = ChildProcessSecurityPolicyImpl::GetInstance(); const std::vector& file_paths = state.GetReferencedFiles(); for (std::vector::const_iterator file = file_paths.begin(); file != file_paths.end(); ++file) { if (!policy->CanReadFile(GetProcess()->GetID(), *file)) return false; } return true; } void RenderViewHostImpl::AttachToFrameTree() { FrameTree* frame_tree = delegate_->GetFrameTree(); frame_tree->ResetForMainFrameSwap(); } } // namespace content ",16233,True,3123.838645580708,median "[[aggregator]] === Aggregator Basically a mirror-image of the splitter, the aggregator is a type of message handler that receives multiple messages and combines them into a single message. In fact, an aggregator is often a downstream consumer in a pipeline that includes a splitter. Technically, the aggregator is more complex than a splitter, because it is stateful. It must hold the messages to be aggregated and determine when the complete group of messages is ready to be aggregated. In order to do so, it requires a `MessageStore`. [[aggregator-functionality]] ==== Functionality The Aggregator combines a group of related messages, by correlating and storing them, until the group is deemed to be complete. At that point, the aggregator creates a single message by processing the whole group and sends the aggregated message as output. Implementing an aggregator requires providing the logic to perform the aggregation (that is, the creation of a single message from many). Two related concepts are correlation and release. Correlation determines how messages are grouped for aggregation. In Spring Integration, correlation is done by default, based on the `IntegrationMessageHeaderAccessor.CORRELATION_ID` message header. Messages with the same `IntegrationMessageHeaderAccessor.CORRELATION_ID` are grouped together. However, you can customize the correlation strategy to allow other ways of specifying how the messages should be grouped together. To do so, you can implement a `CorrelationStrategy` (covered later in this chapter). To determine the point at which a group of messages is ready to be processed, a `ReleaseStrategy` is consulted. The default release strategy for the aggregator releases a group when all messages included in a sequence are present, based on the `IntegrationMessageHeaderAccessor.SEQUENCE_SIZE` header. You can override this default strategy by providing a reference to a custom `ReleaseStrategy` implementation. [[aggregator-api]] ==== Programming Model The Aggregation API consists of a number of classes: * The interface `MessageGroupProcessor`, and its subclasses: `MethodInvokingAggregatingMessageGroupProcessor` and `ExpressionEvaluatingMessageGroupProcessor` * The `ReleaseStrategy` interface and its default implementation: `SimpleSequenceSizeReleaseStrategy` * The `CorrelationStrategy` interface and its default implementation: `HeaderAttributeCorrelationStrategy` ===== `AggregatingMessageHandler` The `AggregatingMessageHandler` (a subclass of `AbstractCorrelatingMessageHandler`) is a `MessageHandler` implementation, encapsulating the common functionality of an aggregator (and other correlating use cases), which are as follows: * Correlating messages into a group to be aggregated * Maintaining those messages in a `MessageStore` until the group can be released * Deciding when the group can be released * Aggregating the released group into a single message * Recognizing and responding to an expired group The responsibility for deciding how the messages should be grouped together is delegated to a `CorrelationStrategy` instance. The responsibility for deciding whether the message group can be released is delegated to a `ReleaseStrategy` instance. The following listing shows a brief highlight of the base `AbstractAggregatingMessageGroupProcessor` (the responsibility for implementing the `aggregatePayloads` method is left to the developer): ==== [source,java] ---- public abstract class AbstractAggregatingMessageGroupProcessor implements MessageGroupProcessor { protected Map aggregateHeaders(MessageGroup group) { // default implementation exists } protected abstract Object aggregatePayloads(MessageGroup group, Map defaultHeaders); } ---- ==== See `DefaultAggregatingMessageGroupProcessor`, `ExpressionEvaluatingMessageGroupProcessor` and `MethodInvokingMessageGroupProcessor` as out-of-the-box implementations of the `AbstractAggregatingMessageGroupProcessor`. Starting with version 5.2, a `Function>` strategy is available for the `AbstractAggregatingMessageGroupProcessor` to merge and compute (aggregate) headers for an output message. The `DefaultAggregateHeadersFunction` implementation is available with logic that returns all headers that have no conflicts among the group; an absent header on one or more messages within the group is not considered a conflict. Conflicting headers are omitted. Along with the newly introduced `DelegatingMessageGroupProcessor`, this function is used for any arbitrary (non-`AbstractAggregatingMessageGroupProcessor`) `MessageGroupProcessor` implementation. Essentially, the framework injects a provided function into an `AbstractAggregatingMessageGroupProcessor` instance and wraps all other implementations into a `DelegatingMessageGroupProcessor`. The difference in logic between the `AbstractAggregatingMessageGroupProcessor` and the `DelegatingMessageGroupProcessor` that the latter doesn't compute headers in advance, before calling the delegate strategy, and doesn't invoke the function if the delegate returns a `Message` or `AbstractIntegrationMessageBuilder`. In that case, the framework assumes that the target implementation has taken care of producing a proper set of headers populated into the returned result. The `Function>` strategy is available as the `headers-function` reference attribute for XML configuration, as the `AggregatorSpec.headersFunction()` option for the Java DSL and as `AggregatorFactoryBean.setHeadersFunction()` for plain Java configuration. The `CorrelationStrategy` is owned by the `AbstractCorrelatingMessageHandler` and has a default value based on the `IntegrationMessageHeaderAccessor.CORRELATION_ID` message header, as the following example shows: ==== [source,java] ---- public AbstractCorrelatingMessageHandler(MessageGroupProcessor processor, MessageGroupStore store, CorrelationStrategy correlationStrategy, ReleaseStrategy releaseStrategy) { ... this.correlationStrategy = correlationStrategy == null ? new HeaderAttributeCorrelationStrategy(IntegrationMessageHeaderAccessor.CORRELATION_ID) : correlationStrategy; this.releaseStrategy = releaseStrategy == null ? new SimpleSequenceSizeReleaseStrategy() : releaseStrategy; ... } ---- ==== As for the actual processing of the message group, the default implementation is the `DefaultAggregatingMessageGroupProcessor`. It creates a single `Message` whose payload is a `List` of the payloads received for a given group. This works well for simple scatter-gather implementations with a splitter, a publish-subscribe channel, or a recipient list router upstream. NOTE: When using a publish-subscribe channel or a recipient list router in this type of scenario, be sure to enable the `apply-sequence` flag. Doing so adds the necessary headers: `CORRELATION_ID`, `SEQUENCE_NUMBER`, and `SEQUENCE_SIZE`. That behavior is enabled by default for splitters in Spring Integration, but it is not enabled for publish-subscribe channels or for recipient list routers because those components may be used in a variety of contexts in which these headers are not necessary. When implementing a specific aggregator strategy for an application, you can extend `AbstractAggregatingMessageGroupProcessor` and implement the `aggregatePayloads` method. However, there are better solutions, less coupled to the API, for implementing the aggregation logic, which can be configured either through XML or through annotations. In general, any POJO can implement the aggregation algorithm if it provides a method that accepts a single `java.util.List` as an argument (parameterized lists are supported as well). This method is invoked for aggregating messages as follows: * If the argument is a `java.util.Collection` and the parameter type T is assignable to `Message`, the whole list of messages accumulated for aggregation is sent to the aggregator. * If the argument is a non-parameterized `java.util.Collection` or the parameter type is not assignable to `Message`, the method receives the payloads of the accumulated messages. * If the return type is not assignable to `Message`, it is treated as the payload for a `Message` that is automatically created by the framework. NOTE: In the interest of code simplicity and promoting best practices such as low coupling, testability, and others, the preferred way of implementing the aggregation logic is through a POJO and using the XML or annotation support for configuring it in the application. Starting with version 5.3, after processing message group, an `AbstractCorrelatingMessageHandler` performs a `MessageBuilder.popSequenceDetails()` message headers modification for the proper splitter-aggregator scenario with several nested levels. It is done only if the message group release result is not a collection of messages. In that case a target `MessageGroupProcessor` is responsible for the `MessageBuilder.popSequenceDetails()` call while building those messages. If the `MessageGroupProcessor` returns a `Message`, a `MessageBuilder.popSequenceDetails()` will be performed on the output message only if the `sequenceDetails` matches with first message in group. (Previously this has been done only if a plain payload or an `AbstractIntegrationMessageBuilder` has been returned from the `MessageGroupProcessor`.) This functionality can be controlled by a new `popSequence` `boolean` property, so the `MessageBuilder.popSequenceDetails()` can be disabled in some scenarios when correlation details have not been populated by the standard splitter. This property, essentially, undoes what has been done by the nearest upstream `applySequence = true` in the `AbstractMessageSplitter`. See <<./splitter.adoc#splitter,Splitter>> for more information. [[agg-message-collection]] IMPORTANT: The `SimpleMessageGroup.getMessages()` method returns an `unmodifiableCollection`. Therefore, if your aggregating POJO method has a `Collection` parameter, the argument passed in is exactly that `Collection` instance and, when you use a `SimpleMessageStore` for the aggregator, that original `Collection` is cleared after releasing the group. Consequently, the `Collection` variable in the POJO is cleared too, if it is passed out of the aggregator. If you wish to simply release that collection as-is for further processing, you must build a new `Collection` (for example, `new ArrayList(messages)`). Starting with version 4.3, the framework no longer copies the messages to a new collection, to avoid undesired extra object creation. If the `processMessageGroup` method of the `MessageGroupProcessor` returns a collection, it must be a collection of `Message` objects. In this case, the messages are individually released. Prior to version 4.2, it was not possible to provide a `MessageGroupProcessor` by using XML configuration. Only POJO methods could be used for aggregation. Now, if the framework detects that the referenced (or inner) bean implements `MessageProcessor`, it is used as the aggregator's output processor. If you wish to release a collection of objects from a custom `MessageGroupProcessor` as the payload of a message, your class should extend `AbstractAggregatingMessageGroupProcessor` and implement `aggregatePayloads()`. Also, since version 4.2, a `SimpleMessageGroupProcessor` is provided. It returns the collection of messages from the group, which, as indicated earlier, causes the released messages to be sent individually. This lets the aggregator work as a message barrier, where arriving messages are held until the release strategy fires and the group is released as a sequence of individual messages. ===== `ReleaseStrategy` The `ReleaseStrategy` interface is defined as follows: ==== [source,java] ---- public interface ReleaseStrategy { boolean canRelease(MessageGroup group); } ---- ==== In general, any POJO can implement the completion decision logic if it provides a method that accepts a single `java.util.List` as an argument (parameterized lists are supported as well) and returns a boolean value. This method is invoked after the arrival of each new message, to decide whether the group is complete or not, as follows: * If the argument is a `java.util.List` and the parameter type `T` is assignable to `Message`, the whole list of messages accumulated in the group is sent to the method. * If the argument is a non-parametrized `java.util.List` or the parameter type is not assignable to `Message`, the method receives the payloads of the accumulated messages. * The method must return `true` if the message group is ready for aggregation or false otherwise. The following example shows how to use the `@ReleaseStrategy` annotation for a `List` of type `Message`: ==== [source,java] ---- public class MyReleaseStrategy { @ReleaseStrategy public boolean canMessagesBeReleased(List>) {...} } ---- ==== The following example shows how to use the `@ReleaseStrategy` annotation for a `List` of type `String`: ==== [source,java] ---- public class MyReleaseStrategy { @ReleaseStrategy public boolean canMessagesBeReleased(List) {...} } ---- ==== Based on the signatures in the preceding two examples, the POJO-based release strategy is passed a `Collection` of not-yet-released messages (if you need access to the whole `Message`) or a `Collection` of payload objects (if the type parameter is anything other than `Message`). This satisfies the majority of use cases. However if, for some reason, you need to access the full `MessageGroup`, you should provide an implementation of the `ReleaseStrategy` interface. [WARNING] ===== When handling potentially large groups, you should understand how these methods are invoked, because the release strategy may be invoked multiple times before the group is released. The most efficient is an implementation of `ReleaseStrategy`, because the aggregator can invoke it directly. The second most efficient is a POJO method with a `Collection>` parameter type. The least efficient is a POJO method with a `Collection` type. The framework has to copy the payloads from the messages in the group into a new collection (and possibly attempt conversion on the payloads to `Something`) every time the release strategy is called. Using `Collection` avoids the conversion but still requires creating the new `Collection`. For these reasons, for large groups, we recommended that you implement `ReleaseStrategy`. ===== When the group is released for aggregation, all its not-yet-released messages are processed and removed from the group. If the group is also complete (that is, if all messages from a sequence have arrived or if there is no sequence defined), then the group is marked as complete. Any new messages for this group are sent to the discard channel (if defined). Setting `expire-groups-upon-completion` to `true` (the default is `false`) removes the entire group, and any new messages (with the same correlation ID as the removed group) form a new group. You can release partial sequences by using a `MessageGroupStoreReaper` together with `send-partial-result-on-expiry` being set to `true`. IMPORTANT: To facilitate discarding of late-arriving messages, the aggregator must maintain state about the group after it has been released. This can eventually cause out-of-memory conditions. To avoid such situations, you should consider configuring a `MessageGroupStoreReaper` to remove the group metadata. The expiry parameters should be set to expire groups once a point has been reach after after which late messages are not expected to arrive. For information about configuring a reaper, see <>. Spring Integration provides an implementation for `ReleaseStrategy`: `SimpleSequenceSizeReleaseStrategy`. This implementation consults the `SEQUENCE_NUMBER` and `SEQUENCE_SIZE` headers of each arriving message to decide when a message group is complete and ready to be aggregated. As shown earlier, it is also the default strategy. NOTE: Before version 5.0, the default release strategy was `SequenceSizeReleaseStrategy`, which does not perform well with large groups. With that strategy, duplicate sequence numbers are detected and rejected. This operation can be expensive. If you are aggregating large groups, you don't need to release partial groups, and you don't need to detect/reject duplicate sequences, consider using the `SimpleSequenceSizeReleaseStrategy` instead - it is much more efficient for these use cases, and is the default since _version 5.0_ when partial group release is not specified. ===== Aggregating Large Groups The 4.3 release changed the default `Collection` for messages in a `SimpleMessageGroup` to `HashSet` (it was previously a `BlockingQueue`). This was expensive when removing individual messages from large groups (an O(n) linear scan was required). Although the hash set is generally much faster to remove, it can be expensive for large messages, because the hash has to be calculated on both inserts and removes. If you have messages that are expensive to hash, consider using some other collection type. As discussed in <<./message-store.adoc#message-group-factory,Using `MessageGroupFactory`>>, a `SimpleMessageGroupFactory` is provided so that you can select the `Collection` that best suits your needs. You can also provide your own factory implementation to create some other `Collection>`. The following example shows how to configure an aggregator with the previous implementation and a `SimpleSequenceSizeReleaseStrategy`: ==== [source, xml] ---- ---- ==== ===== Correlation Strategy The `CorrelationStrategy` interface is defined as follows: ==== [source,java] ---- public interface CorrelationStrategy { Object getCorrelationKey(Message message); } ---- ==== The method returns an `Object` that represents the correlation key used for associating the message with a message group. The key must satisfy the criteria used for a key in a `Map` with respect to the implementation of `equals()` and `hashCode()`. In general, any POJO can implement the correlation logic, and the rules for mapping a message to a method's argument (or arguments) are the same as for a `ServiceActivator` (including support for `@Header` annotations). The method must return a value, and the value must not be `null`. Spring Integration provides an implementation for `CorrelationStrategy`: `HeaderAttributeCorrelationStrategy`. This implementation returns the value of one of the message headers (whose name is specified by a constructor argument) as the correlation key. By default, the correlation strategy is a `HeaderAttributeCorrelationStrategy` that returns the value of the `CORRELATION_ID` header attribute. If you have a custom header name you would like to use for correlation, you can configure it on an instance of `HeaderAttributeCorrelationStrategy` and provide that as a reference for the aggregator's correlation strategy. ===== Lock Registry Changes to groups are thread safe. So, when you send messages for the same correlation ID concurrently, only one of them will be processed in the aggregator, making it effectively as a *single-threaded per message group*. A `LockRegistry` is used to obtain a lock for the resolved correlation ID. A `DefaultLockRegistry` is used by default (in-memory). For synchronizing updates across servers where a shared `MessageGroupStore` is being used, you must configure a shared lock registry. [[aggregator-deadlocks]] ===== Avoiding Deadlocks As discussed above, when message groups are mutated (messages added or released) a lock is held. Consider the following flow: ==== [source] ---- ...->aggregator1-> ... ->aggregator2-> ... ---- ==== If there are multiple threads, **and the aggregators share a common lock registry**, it is possible to get a deadlock. This will cause hung threads and `jstack ` might present a result such as: ==== [source] ---- Found one Java-level deadlock: ============================= ""t2"": waiting for ownable synchronizer 0x000000076c1cbfa0, (a java.util.concurrent.locks.ReentrantLock$NonfairSync), which is held by ""t1"" ""t1"": waiting for ownable synchronizer 0x000000076c1ccc00, (a java.util.concurrent.locks.ReentrantLock$NonfairSync), which is held by ""t2"" ---- ==== There are several ways to avoid this problem: * ensure each aggregator has its own lock registry (this can be a shared registry across application instances but two or more aggregators in the flow must each have a distinct registry) * use an `ExecutorChannel` or `QueueChannel` as the output channel of the aggregator so that the downstream flow runs on a new thread * starting with version 5.1.1, set the `releaseLockBeforeSend` aggregator property to `true` NOTE: This problem can also be caused if, for some reason, the output of a single aggregator is eventually routed back to the same aggregator. Of course, the first solution above does not apply in this case. [[aggregator-java-dsl]] ==== Configuring an Aggregator in Java DSL See <<./dsl.adoc#java-dsl-aggregators,Aggregators and Resequencers>> for how to configure an aggregator in Java DSL. [[aggregator-xml]] ===== Configuring an Aggregator with XML Spring Integration supports the configuration of an aggregator with XML through the `` element. The following example shows an example of an aggregator: ==== [source,xml] ---- auto-startup=""true"" <2> input-channel=""inputChannel"" <3> output-channel=""outputChannel"" <4> discard-channel=""throwAwayChannel"" <5> message-store=""persistentMessageStore"" <6> order=""1"" <7> send-partial-result-on-expiry=""false"" <8> send-timeout=""1000"" <9> correlation-strategy=""correlationStrategyBean"" <10> correlation-strategy-method=""correlate"" <11> correlation-strategy-expression=""headers['foo']"" <12> ref=""aggregatorBean"" <13> method=""aggregate"" <14> release-strategy=""releaseStrategyBean"" <15> release-strategy-method=""release"" <16> release-strategy-expression=""size() == 5"" <17> expire-groups-upon-completion=""false"" <18> empty-group-min-timeout=""60000"" <19> lock-registry=""lockRegistry"" <20> group-timeout=""60000"" <21> group-timeout-expression=""size() ge 2 ? 100 : -1"" <22> expire-groups-upon-timeout=""true"" <23> scheduler=""taskScheduler"" > <24> <25> <26> ---- <1> The id of the aggregator is optional. <2> Lifecycle attribute signaling whether the aggregator should be started during application context startup. Optional (the default is 'true'). <3> The channel from which where aggregator receives messages. Required. <4> The channel to which the aggregator sends the aggregation results. Optional (because incoming messages can themselves specify a reply channel in the 'replyChannel' message header). <5> The channel to which the aggregator sends the messages that timed out (if `send-partial-result-on-expiry` is `false`). Optional. <6> A reference to a `MessageGroupStore` used to store groups of messages under their correlation key until they are complete. Optional. By default, it is a volatile in-memory store. See <<./message-store.adoc#message-store,Message Store>> for more information. <7> The order of this aggregator when more than one handle is subscribed to the same `DirectChannel` (use for load-balancing purposes). Optional. <8> Indicates that expired messages should be aggregated and sent to the 'output-channel' or 'replyChannel' once their containing `MessageGroup` is expired (see https://docs.spring.io/spring-integration/api/org/springframework/integration/store/MessageGroupStore.html#expireMessageGroups-long[`MessageGroupStore.expireMessageGroups(long)`]). One way of expiring a `MessageGroup` is by configuring a `MessageGroupStoreReaper`. However you can alternatively expire `MessageGroup` by calling `MessageGroupStore.expireMessageGroups(timeout)`. You can accomplish that through a Control Bus operation or, if you have a reference to the `MessageGroupStore` instance, by invoking `expireMessageGroups(timeout)`. Otherwise, by itself, this attribute does nothing. It serves only as an indicator of whether to discard or send to the output or reply channel any messages that are still in the `MessageGroup` that is about to be expired. Optional (the default is `false`). NOTE: This attribute might more properly be called `send-partial-result-on-timeout`, because the group may not actually expire if `expire-groups-upon-timeout` is set to `false`. <9> The timeout interval to wait when sending a reply `Message` to the `output-channel` or `discard-channel`. Defaults to `-1`, which results in blocking indefinitely. It is applied only if the output channel has some 'sending' limitations, such as a `QueueChannel` with a fixed 'capacity'. In this case, a `MessageDeliveryException` is thrown. For `AbstractSubscribableChannel` implementations, the `send-timeout` is ignored . For `group-timeout(-expression)`, the `MessageDeliveryException` from the scheduled expire task leads this task to be rescheduled. Optional. <10> A reference to a bean that implements the message correlation (grouping) algorithm. The bean can be an implementation of the `CorrelationStrategy` interface or a POJO. In the latter case, the `correlation-strategy-method` attribute must be defined as well. Optional (by default, the aggregator uses the `IntegrationMessageHeaderAccessor.CORRELATION_ID` header). <11> A method defined on the bean referenced by `correlation-strategy`. It implements the correlation decision algorithm. Optional, with restrictions (`correlation-strategy` must be present). <12> A SpEL expression representing the correlation strategy. Example: `""headers['something']""`. Only one of `correlation-strategy` or `correlation-strategy-expression` is allowed. <13> A reference to a bean defined in the application context. The bean must implement the aggregation logic, as described earlier. Optional (by default, the list of aggregated messages becomes a payload of the output message). <14> A method defined on the bean referenced by the `ref` attribute. It implements the message aggregation algorithm. Optional (it depends on `ref` attribute being defined). <15> A reference to a bean that implements the release strategy. The bean can be an implementation of the `ReleaseStrategy` interface or a POJO. In the latter case, the `release-strategy-method` attribute must be defined as well. Optional (by default, the aggregator uses the `IntegrationMessageHeaderAccessor.SEQUENCE_SIZE` header attribute). <16> A method defined on the bean referenced by the `release-strategy` attribute. It implements the completion decision algorithm. Optional, with restrictions (`release-strategy` must be present). <17> A SpEL expression representing the release strategy. The root object for the expression is a `MessageGroup`. Example: `""size() == 5""`. Only one of `release-strategy` or `release-strategy-expression` is allowed. <18> When set to `true` (the default is `false`), completed groups are removed from the message store, letting subsequent messages with the same correlation form a new group. The default behavior is to send messages with the same correlation as a completed group to the `discard-channel`. <19> Applies only if a `MessageGroupStoreReaper` is configured for the `MessageStore` of the ``. By default, when a `MessageGroupStoreReaper` is configured to expire partial groups, empty groups are also removed. Empty groups exist after a group is normally released. The empty groups enable the detection and discarding of late-arriving messages. If you wish to expire empty groups on a longer schedule than expiring partial groups, set this property. Empty groups are then not removed from the `MessageStore` until they have not been modified for at least this number of milliseconds. Note that the actual time to expire an empty group is also affected by the reaper's `timeout` property, and it could be as much as this value plus the timeout. <20> A reference to a `org.springframework.integration.util.LockRegistry` bean. It used to obtain a `Lock` based on the `groupId` for concurrent operations on the `MessageGroup`. By default, an internal `DefaultLockRegistry` is used. Use of a distributed `LockRegistry`, such as the `ZookeeperLockRegistry`, ensures only one instance of the aggregator can operate on a group concurrently. See <<./redis.adoc#redis-lock-registry,Redis Lock Registry>>, <<./gemfire.adoc#gemfire-lock-registry,Gemfire Lock Registry>>, and <<./zookeeper.adoc#zk-lock-registry,Zookeeper Lock Registry>> for more information. <21> A timeout (in milliseconds) to force the `MessageGroup` complete when the `ReleaseStrategy` does not release the group when the current message arrives. This attribute provides a built-in time-based release strategy for the aggregator when there is a need to emit a partial result (or discard the group) if a new message does not arrive for the `MessageGroup` within the timeout which counts from the time the last message arrived. To set up a timeout which counts from the time the `MessageGroup` was created see `group-timeout-expression` information. When a new message arrives at the aggregator, any existing `ScheduledFuture` for its `MessageGroup` is canceled. If the `ReleaseStrategy` returns `false` (meaning do not release) and `groupTimeout > 0`, a new task is scheduled to expire the group. We do not advise setting this attribute to zero (or a negative value). Doing so effectively disables the aggregator, because every message group is immediately completed. You can, however, conditionally set it to zero (or a negative value) by using an expression. See `group-timeout-expression` for information. The action taken during the completion depends on the `ReleaseStrategy` and the `send-partial-group-on-expiry` attribute. See <> for more information. It is mutually exclusive with 'group-timeout-expression' attribute. <22> The SpEL expression that evaluates to a `groupTimeout` with the `MessageGroup` as the `#root` evaluation context object. Used for scheduling the `MessageGroup` to be forced complete. If the expression evaluates to `null`, the completion is not scheduled. If it evaluates to zero, the group is completed immediately on the current thread. In effect, this provides a dynamic `group-timeout` property. As an example, if you wish to forcibly complete a `MessageGroup` after 10 seconds have elapsed since the time the group was created you might consider using the following SpEL expression: `timestamp + 10000 - T(System).currentTimeMillis()` where `timestamp` is provided by `MessageGroup.getTimestamp()` as the `MessageGroup` here is the `#root` evaluation context object. Bear in mind however that the group creation time might differ from the time of the first arrived message depending on other group expiration properties' configuration. See `group-timeout` for more information. Mutually exclusive with 'group-timeout' attribute. <23> When a group is completed due to a timeout (or by a `MessageGroupStoreReaper`), the group is expired (completely removed) by default. Late arriving messages start a new group. You can set this to `false` to complete the group but have its metadata remain so that late arriving messages are discarded. Empty groups can be expired later using a `MessageGroupStoreReaper` together with the `empty-group-min-timeout` attribute. It defaults to 'true'. <24> A `TaskScheduler` bean reference to schedule the `MessageGroup` to be forced complete if no new message arrives for the `MessageGroup` within the `groupTimeout`. If not provided, the default scheduler (`taskScheduler`) registered in the `ApplicationContext` (`ThreadPoolTaskScheduler`) is used. This attribute does not apply if `group-timeout` or `group-timeout-expression` is not specified. <25> Since version 4.1. It lets a transaction be started for the `forceComplete` operation. It is initiated from a `group-timeout(-expression)` or by a `MessageGroupStoreReaper` and is not applied to the normal `add`, `release`, and `discard` operations. Only this sub-element or `` is allowed. <26> Since _version 4.1_. It allows the configuration of any `Advice` for the `forceComplete` operation. It is initiated from a `group-timeout(-expression)` or by a `MessageGroupStoreReaper` and is not applied to the normal `add`, `release`, and `discard` operations. Only this sub-element or `` is allowed. A transaction `Advice` can also be configured here by using the Spring `tx` namespace. ==== [[aggregator-expiring-groups]] [IMPORTANT] .Expiring Groups ===== There are two attributes related to expiring (completely removing) groups. When a group is expired, there is no record of it, and, if a new message arrives with the same correlation, a new group is started. When a group is completed (without expiry), the empty group remains and late-arriving messages are discarded. Empty groups can be removed later by using a `MessageGroupStoreReaper` in combination with the `empty-group-min-timeout` attribute. `expire-groups-upon-completion` relates to ""`normal`"" completion when the `ReleaseStrategy` releases the group. This defaults to `false`. If a group is not completed normally but is released or discarded because of a timeout, the group is normally expired. Since version 4.1, you can control this behavior by using `expire-groups-upon-timeout`. It defaults to `true` for backwards compatibility. NOTE: When a group is timed out, the `ReleaseStrategy` is given one more opportunity to release the group. If it does so and `expire-groups-upon-timeout` is false, expiration is controlled by `expire-groups-upon-completion`. If the group is not released by the release strategy during timeout, then the expiration is controlled by the `expire-groups-upon-timeout`. Timed-out groups are either discarded or a partial release occurs (based on `send-partial-result-on-expiry`). Since version 5.0, empty groups are also scheduled for removal after `empty-group-min-timeout`. If `expireGroupsUponCompletion == false` and `minimumTimeoutForEmptyGroups > 0`, the task to remove the group is scheduled when normal or partial sequences release happens. Starting with version 5.4, the aggregator (and resequencer) can be configured to expire orphaned groups (groups in a persistent message store that might not otherwise be released). The `expireTimeout` (if greater than `0`) indicates that groups older than this value in the store should be purged. The `purgeOrphanedGroups()` method is called on start up and, together with the provided `expireDuration`, periodically within a scheduled task. This method is also can be called externally at any time. The expiration logic is fully delegated to the `forceComplete(MessageGroup)` functionality according to the provided expiration options mentioned above. Such a periodic purge functionality is useful when a message store is needed to be cleaned up from those old groups which are not going to be released any more with regular message arrival logic. In most cases this happens after an application restart, when using a persistent message group store. The functionality is similar to the `MessageGroupStoreReaper` with a scheduled task, but provides a convenient way to deal with old groups within specific components, when using group timeout instead of a reaper. The `MessageGroupStore` must be provided exclusively for the current correlation endpoint. Otherwise one aggregator may purge groups from another. With the aggregator, groups expired using this technique will either be discarded or released as a partial group, depending on the `expireGroupsUponCompletion` property. ===== We generally recommend using a `ref` attribute if a custom aggregator handler implementation may be referenced in other `` definitions. However, if a custom aggregator implementation is only being used by a single definition of the ``, you can use an inner bean definition (starting with version 1.0.3) to configure the aggregation POJO within the `` element, as the following example shows: ==== [source,xml] ---- ---- ==== NOTE: Using both a `ref` attribute and an inner bean definition in the same `` configuration is not allowed, as it creates an ambiguous condition. In such cases, an Exception is thrown. The following example shows an implementation of the aggregator bean: ==== [source,java] ---- public class PojoAggregator { public Long add(List results) { long total = 0l; for (long partialResult: results) { total += partialResult; } return total; } } ---- ==== An implementation of the completion strategy bean for the preceding example might be as follows: ==== [source,java] ---- public class PojoReleaseStrategy { ... public boolean canRelease(List numbers) { int sum = 0; for (long number: numbers) { sum += number; } return sum >= maxValue; } } ---- ==== NOTE: Wherever it makes sense to do so, the release strategy method and the aggregator method can be combined into a single bean. An implementation of the correlation strategy bean for the example above might be as follows: ==== [source,java] ---- public class PojoCorrelationStrategy { ... public Long groupNumbersByLastDigit(Long number) { return number % 10; } } ---- ==== The aggregator in the preceding example would group numbers by some criterion (in this case, the remainder after dividing by ten) and hold the group until the sum of the numbers provided by the payloads exceeds a certain value. NOTE: Wherever it makes sense to do so, the release strategy method, the correlation strategy method, and the aggregator method can be combined in a single bean. (Actually, all of them or any two of them can be combined.) [[aggregator-spel]] ====== Aggregators and Spring Expression Language (SpEL) Since Spring Integration 2.0, you can handle the various strategies (correlation, release, and aggregation) with https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#expressions[SpEL], which we recommend if the logic behind such a release strategy is relatively simple. Suppose you have a legacy component that was designed to receive an array of objects. We know that the default release strategy assembles all aggregated messages in the `List`. Now we have two problems. First, we need to extract individual messages from the list. Second, we need to extract the payload of each message and assemble the array of objects. The following example solves both problems: ==== [source,java] ---- public String[] processRelease(List> messages){ List stringList = new ArrayList(); for (Message message : messages) { stringList.add(message.getPayload()); } return stringList.toArray(new String[]{}); } ---- ==== However, with SpEL, such a requirement could actually be handled relatively easily with a one-line expression, thus sparing you from writing a custom class and configuring it as a bean. The following example shows how to do so: ==== [source,xml] ---- ---- ==== In the preceding configuration, we use a https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#expressions[collection projection] expression to assemble a new collection from the payloads of all the messages in the list and then transform it to an array, thus achieving the same result as the earlier Java code. You can apply the same expression-based approach when dealing with custom release and correlation strategies. Instead of defining a bean for a custom `CorrelationStrategy` in the `correlation-strategy` attribute, you can implement your simple correlation logic as a SpEL expression and configure it in the `correlation-strategy-expression` attribute, as the following example shows: ==== [source,xml] ---- correlation-strategy-expression=""payload.person.id"" ---- ==== In the preceding example, we assume that the payload has a `person` attribute with an `id`, which is going to be used to correlate messages. Likewise, for the `ReleaseStrategy`, you can implement your release logic as a SpEL expression and configure it in the `release-strategy-expression` attribute. The root object for evaluation context is the `MessageGroup` itself. The `List` of messages can be referenced by using the `message` property of the group within the expression. NOTE: In releases prior to version 5.0, the root object was the collection of `Message`, as the previous example shows: ==== [source,xml] ---- release-strategy-expression=""!messages.?[payload==5].empty"" ---- ==== In the preceding example, the root object of the SpEL evaluation context is the `MessageGroup` itself, and you are stating that, as soon as there is a message with payload of `5` in this group, the group should be released. [[agg-and-group-to]] ====== Aggregator and Group Timeout Starting with version 4.0, two new mutually exclusive attributes have been introduced: `group-timeout` and `group-timeout-expression`. See <>. In some cases, you may need to emit the aggregator result (or discard the group) after a timeout if the `ReleaseStrategy` does not release when the current message arrives. For this purpose, the `groupTimeout` option lets scheduling the `MessageGroup` be forced to complete, as the following example shows: ==== [source,xml] ---- ---- ==== With this example, the normal release is possible if the aggregator receives the last message in sequence as defined by the `release-strategy-expression`. If that specific message does not arrive, the `groupTimeout` forces the group to complete after ten seconds, as long as the group contains at least two Messages. The results of forcing the group to complete depends on the `ReleaseStrategy` and the `send-partial-result-on-expiry`. First, the release strategy is again consulted to see if a normal release is to be made. While the group has not changed, the `ReleaseStrategy` can decide to release the group at this time. If the release strategy still does not release the group, it is expired. If `send-partial-result-on-expiry` is `true`, existing messages in the (partial) `MessageGroup` are released as a normal aggregator reply message to the `output-channel`. Otherwise, it is discarded. There is a difference between `groupTimeout` behavior and `MessageGroupStoreReaper` (see <>). The reaper initiates forced completion for all `MessageGroup` s in the `MessageGroupStore` periodically. The `groupTimeout` does it for each `MessageGroup` individually if a new message does not arrive during the `groupTimeout`. Also, the reaper can be used to remove empty groups (empty groups are retained in order to discard late messages if `expire-groups-upon-completion` is false). Starting with version 5.5, the `groupTimeoutExpression` can be evaluated to a `java.util.Date` instance. This can be useful in cases like determining a scheduled task moment based on the group creation time (`MessageGroup.getTimestamp()`) instead of a current message arrival as it is calculated when `groupTimeoutExpression` is evaluated to `long`: ==== [source,xml] ---- group-timeout-expression=""size() ge 2 ? new java.util.Date(timestamp + 200) : null"" ---- ==== [[aggregator-annotations]] ===== Configuring an Aggregator with Annotations The following example shows an aggregator configured with annotations: ==== [source,java] ---- public class Waiter { ... @Aggregator <1> public Delivery aggregatingMethod(List items) { ... } @ReleaseStrategy <2> public boolean releaseChecker(List> messages) { ... } @CorrelationStrategy <3> public String correlateBy(OrderItem item) { ... } } ---- <1> An annotation indicating that this method should be used as an aggregator. It must be specified if this class is used as an aggregator. <2> An annotation indicating that this method is used as the release strategy of an aggregator. If not present on any method, the aggregator uses the `SimpleSequenceSizeReleaseStrategy`. <3> An annotation indicating that this method should be used as the correlation strategy of an aggregator. If no correlation strategy is indicated, the aggregator uses the `HeaderAttributeCorrelationStrategy` based on `CORRELATION_ID`. ==== All of the configuration options provided by the XML element are also available for the `@Aggregator` annotation. The aggregator can be either referenced explicitly from XML or, if the `@MessageEndpoint` is defined on the class, detected automatically through classpath scanning. Annotation configuration (`@Aggregator` and others) for the Aggregator component covers only simple use cases, where most default options are sufficient. If you need more control over those options when using annotation configuration, consider using a `@Bean` definition for the `AggregatingMessageHandler` and mark its `@Bean` method with `@ServiceActivator`, as the following example shows: ==== [source,java] ---- @ServiceActivator(inputChannel = ""aggregatorChannel"") @Bean public MessageHandler aggregator(MessageGroupStore jdbcMessageGroupStore) { AggregatingMessageHandler aggregator = new AggregatingMessageHandler(new DefaultAggregatingMessageGroupProcessor(), jdbcMessageGroupStore); aggregator.setOutputChannel(resultsChannel()); aggregator.setGroupTimeoutExpression(new ValueExpression<>(500L)); aggregator.setTaskScheduler(this.taskScheduler); return aggregator; } ---- ==== See <> and <<./configuration.adoc#annotations_on_beans,Annotations on `@Bean` Methods>> for more information. NOTE: Starting with version 4.2, the `AggregatorFactoryBean` is available to simplify Java configuration for the `AggregatingMessageHandler`. [[reaper]] ==== Managing State in an Aggregator: `MessageGroupStore` Aggregator (and some other patterns in Spring Integration) is a stateful pattern that requires decisions to be made based on a group of messages that have arrived over a period of time, all with the same correlation key. The design of the interfaces in the stateful patterns (such as `ReleaseStrategy`) is driven by the principle that the components (whether defined by the framework or by a user) should be able to remain stateless. All state is carried by the `MessageGroup` and its management is delegated to the `MessageGroupStore`. The `MessageGroupStore` interface is defined as follows: ==== [source,java] ---- public interface MessageGroupStore { int getMessageCountForAllMessageGroups(); int getMarkedMessageCountForAllMessageGroups(); int getMessageGroupCount(); MessageGroup getMessageGroup(Object groupId); MessageGroup addMessageToGroup(Object groupId, Message message); MessageGroup markMessageGroup(MessageGroup group); MessageGroup removeMessageFromGroup(Object key, Message messageToRemove); MessageGroup markMessageFromGroup(Object key, Message messageToMark); void removeMessageGroup(Object groupId); void registerMessageGroupExpiryCallback(MessageGroupCallback callback); int expireMessageGroups(long timeout); } ---- ==== For more information, see the https://docs.spring.io/spring-integration/api/org/springframework/integration/store/MessageGroupStore.html[Javadoc]. The `MessageGroupStore` accumulates state information in `MessageGroups` while waiting for a release strategy to be triggered, and that event might not ever happen. So, to prevent stale messages from lingering, and for volatile stores to provide a hook for cleaning up when the application shuts down, the `MessageGroupStore` lets you register callbacks to apply to its `MessageGroups` when they expire. The interface is very straightforward, as the following listing shows: ==== [source,java] ---- public interface MessageGroupCallback { void execute(MessageGroupStore messageGroupStore, MessageGroup group); } ---- ==== The callback has direct access to the store and the message group so that it can manage the persistent state (for example, by entirely removing the group from the store). The `MessageGroupStore` maintains a list of these callbacks, which it applies, on demand, to all messages whose timestamps are earlier than a time supplied as a parameter (see the `registerMessageGroupExpiryCallback(..)` and `expireMessageGroups(..)` methods, described earlier). For more detail, see <>. IMPORTANT: It is important not to use the same `MessageGroupStore` instance in different aggregator components, when you intend to rely on the `expireMessageGroups` functionality. Every `AbstractCorrelatingMessageHandler` registers its own `MessageGroupCallback` based on the `forceComplete()` callback. This way each group for expiration may be completed or discarded by the wrong aggregator. Starting with version 5.0.10, a `UniqueExpiryCallback` is used from the `AbstractCorrelatingMessageHandler` for the registration callback in the `MessageGroupStore`. The `MessageGroupStore`, in turn, checks for presence an instance of this class and logs an error with an appropriate message if one is already present in the callbacks set. This way the Framework disallows usage of the `MessageGroupStore` instance in different aggregators/resequencers to avoid the mentioned side effect of expiration the groups not created by the particular correlation handler. You can call the `expireMessageGroups` method with a timeout value. Any message older than the current time minus this value is expired and has the callbacks applied. Thus, it is the user of the store that defines what is meant by message group ""`expiry`"". As a convenience for users, Spring Integration provides a wrapper for the message expiry in the form of a `MessageGroupStoreReaper`, as the following example shows: ==== [source,xml] ---- ---- ==== The reaper is a `Runnable`. In the preceding example, the message group store's expire method is called every ten seconds. The timeout itself is 30 seconds. NOTE: It is important to understand that the 'timeout' property of `MessageGroupStoreReaper` is an approximate value and is impacted by the the rate of the task scheduler, since this property is only checked on the next scheduled execution of the `MessageGroupStoreReaper` task. For example, if the timeout is set for ten minutes but the `MessageGroupStoreReaper` task is scheduled to run every hour and the last execution of the `MessageGroupStoreReaper` task happened one minute before the timeout, the `MessageGroup` does not expire for the next 59 minutes. Consequently, we recommend setting the rate to be at least equal to the value of the timeout or shorter. In addition to the reaper, the expiry callbacks are invoked when the application shuts down through a lifecycle callback in the `AbstractCorrelatingMessageHandler`. The `AbstractCorrelatingMessageHandler` registers its own expiry callback, and this is the link with the boolean flag `send-partial-result-on-expiry` in the XML configuration of the aggregator. If the flag is set to `true`, then, when the expiry callback is invoked, any unmarked messages in groups that are not yet released can be sent on to the output channel. [IMPORTANT] ===== When a shared `MessageStore` is used for different correlation endpoints, you must configure a proper `CorrelationStrategy` to ensure uniqueness for group IDs. Otherwise, unexpected behavior may happen when one correlation endpoint releases or expire messages from others. Messages with the same correlation key are stored in the same message group. Some `MessageStore` implementations allow using the same physical resources, by partitioning the data. For example, the `JdbcMessageStore` has a `region` property, and the `MongoDbMessageStore` has a `collectionName` property. For more information about the `MessageStore` interface and its implementations, see <<./message-store.adoc#message-store,Message Store>>. ===== [[flux-aggregator]] ==== Flux Aggregator In version 5.2, the `FluxAggregatorMessageHandler` component has been introduced. It is based on the Project Reactor `Flux.groupBy()` and `Flux.window()` operators. The incoming messages are emitted into the `FluxSink` initiated by the `Flux.create()` in the constructor of this component. If the `outputChannel` is not provided or it is not an instance of `ReactiveStreamsSubscribableChannel`, the subscription to the main `Flux` is done from the `Lifecycle.start()` implementation. Otherwise it is postponed to the subscription done by the `ReactiveStreamsSubscribableChannel` implementation. The messages are grouped by the `Flux.groupBy()` using a `CorrelationStrategy` for the group key. By default, the `IntegrationMessageHeaderAccessor.CORRELATION_ID` header of the message is consulted. By default every closed window is released as a `Flux` in payload of a message to produce. This message contains all the headers from the first message in the window. This `Flux` in the output message payload must be subscribed and processed downstream. Such a logic can be customized (or superseded) by the `setCombineFunction(Function>, Mono>>)` configuration option of the `FluxAggregatorMessageHandler`. For example, if we would like to have a `List` of payloads in the final message, we can configure a `Flux.collectList()` like this: ==== [source,java] ---- fluxAggregatorMessageHandler.setCombineFunction( (messageFlux) -> messageFlux .map(Message::getPayload) .collectList() .map(GenericMessage::new)); ---- ==== There are several options in the `FluxAggregatorMessageHandler` to select an appropriate window strategy: * `setBoundaryTrigger(Predicate>)` - is propagated to the `Flux.windowUntil()` operator. See its JavaDocs for more information. Has a precedence over all other window options. * `setWindowSize(int)` and `setWindowSizeFunction(Function, Integer>)` - is propagated to the `Flux.window(int)` or `windowTimeout(int, Duration)`. By default a window size is calculated from the first message in group and its `IntegrationMessageHeaderAccessor.SEQUENCE_SIZE` header. * `setWindowTimespan(Duration)` - is propagated to the `Flux.window(Duration)` or `windowTimeout(int, Duration)` depending in the window size configuration. * `setWindowConfigurer(Function>, Flux>>>)` - a function to apply a transformation into the grouped fluxes for any custom window operation not covered by the exposed options. Since this component is a `MessageHandler` implementation it can simply be used as a `@Bean` definition together with a `@ServiceActivator` messaging annotation. With Java DSL it can be used from the `.handle()` EIP-method. The sample below demonstrates how we can register an `IntegrationFlow` at runtime and how a `FluxAggregatorMessageHandler` can be correlated with a splitter upstream: ==== [source,java] ---- IntegrationFlow fluxFlow = (flow) -> flow .split() .channel(MessageChannels.flux()) .handle(new FluxAggregatorMessageHandler()); IntegrationFlowContext.IntegrationFlowRegistration registration = this.integrationFlowContext.registration(fluxFlow) .register(); @SuppressWarnings(""unchecked"") Flux> window = registration.getMessagingTemplate() .convertSendAndReceive(new Integer[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, Flux.class); ---- ==== [[agg-message-group-condition]] ==== Condition on the Message Group Starting with version 5.5, an `AbstractCorrelatingMessageHandler` (including its Java & XML DSLs) exposes a `groupConditionSupplier` option of the `BiFunction, String, String>` implementation. This function is used on each message added to the group and a result condition sentence is stored into the group for future consideration. The `ReleaseStrategy` may consult this condition instead of iterating over all the messages in the group. See `GroupConditionProvider` JavaDocs and <<./message-store.adoc#message-group-condition, Message Group Condition>> for more information. See also <<./file.adoc#file-aggregator, File Aggregator>>.",12407,False,2273.870326403358,median "/*========================== begin_copyright_notice ============================ Copyright (C) 2017-2021 Intel Corporation SPDX-License-Identifier: MIT ============================= end_copyright_notice ===========================*/ #include ""common/LLVMWarningsPush.hpp"" #include #include ""llvm/ADT/StringSwitch.h"" #include ""common/LLVMWarningsPop.hpp"" #include ""Compiler/CISACodeGen/PixelShaderCodeGen.hpp"" #include ""Compiler/CISACodeGen/messageEncoding.hpp"" #include ""common/allocator.h"" #include #include ""common/secure_mem.h"" #include ""Simd32Profitability.hpp"" #include ""EmitVISAPass.hpp"" #include ""AdaptorCommon/API/igc.h"" #include ""Probe/Assertion.h"" /*********************************************************************************** This file contains the code specific to pixel shader ************************************************************************************/ using namespace llvm; using namespace IGC::IGCMD; namespace IGC { CVariable* CPixelShader::GetR1() { return m_R1; } std::vector& CPixelShader::GetR1Lo() { return m_R1Lo; } void CPixelShader::AppendR1Lo(CVariable* var) { m_R1Lo.push_back(var); } CVariable* CPixelShader::GetCoarseR1() { IGC_ASSERT(m_phase == PSPHASE_PIXEL); return m_CoarseR1; } void CPixelShader::AllocatePayload() { if (m_phase == PSPHASE_COARSE) { CreatePassThroughVar(); } switch (m_phase) { case PSPHASE_LEGACY: case PSPHASE_COARSE: AllocatePSPayload(); break; case PSPHASE_PIXEL: AllocatePixelPhasePayload(); break; default: IGC_ASSERT_MESSAGE(0, ""unknown phase""); break; } } void CPixelShader::AllocatePixelPhasePayload() { unsigned int r1Offset = GetDispatchSignature().r1; AllocateInput(m_CoarseR1, r1Offset); for (uint i = 0; i < setup.size(); i++) { if (setup[i]) { uint subRegOffset = 0; // PS uniform inputs are stored in the 3rd subreg if (setup[i]->GetSize() == SIZE_DWORD) { subRegOffset = 3 * SIZE_DWORD; } IGC_ASSERT(m_Signature != nullptr); uint offset = GetDispatchSignature().inputOffset[i]; AllocateInput(setup[i], offset + subRegOffset); } } if (m_ZWDelta) { unsigned int offset = GetDispatchSignature().ZWDelta; AllocateInput(m_ZWDelta, offset); } if (m_SampleOffsetX || m_SampleOffsetY) { unsigned int offset = GetDispatchSignature().pixelOffset; if (m_SampleOffsetX) { AllocateInput(m_SampleOffsetX, offset); } if (m_SampleOffsetY) { AllocateInput(m_SampleOffsetY, offset + SIZE_OWORD); } } for (auto it = m_CoarseInput.begin(), ie = m_CoarseInput.end(); it != ie; ++it) { uint offset = GetDispatchSignature().PSOutputOffset.find(it->first)->second; AllocateInput(it->second, offset); } if (m_CoarseMaskInput) { uint offset = GetDispatchSignature().oMaskOffset; AllocateInput(m_CoarseMaskInput, offset); } } void CPixelShader::AllocatePSPayload() { bool forceLiveOut = false; // In bytes uint offset = 0; // R0 is always allocated as a predefined variable. Increase offset for R0 IGC_ASSERT(m_R0); if (encoder.IsCodePatchCandidate()) { // For the payload section, we need to mark inputs to be outputs // so that inputs will be alive across the entire payload section forceLiveOut = true; encoder.MarkAsPayloadLiveOut(m_R0); } offset += getGRFSize(); if (m_Signature) { GetDispatchSignature().r1 = offset; } { IGC_ASSERT(GetR1()); for (uint i = 0; i < GetR1()->GetNumberInstance(); i++) { AllocateInput(GetR1(), offset, i, forceLiveOut); for (auto R1Lo: GetR1Lo()) { AllocateInput(R1Lo, offset, i, forceLiveOut); } offset += getGRFSize(); } } uint numInstances = m_numberInstance; for (uint i = 0; i < numInstances; i++) { // allocate size for bary if (m_PerspectivePixel) { AllocateInput(m_PerspectivePixel, offset, i, forceLiveOut); offset += m_PerspectivePixel->GetSize(); } if (m_PerspectiveCentroid) { AllocateInput(m_PerspectiveCentroid, offset, i, forceLiveOut); offset += m_PerspectiveCentroid->GetSize(); } if (m_PerspectiveSample) { AllocateInput(m_PerspectiveSample, offset, i, forceLiveOut); offset += m_PerspectiveSample->GetSize(); } if (m_NoPerspectivePixel) { AllocateInput(m_NoPerspectivePixel, offset, i, forceLiveOut); offset += m_NoPerspectivePixel->GetSize(); } if (m_NoPerspectiveCentroid) { AllocateInput(m_NoPerspectiveCentroid, offset, i, forceLiveOut); offset += m_NoPerspectiveCentroid->GetSize(); } if (m_NoPerspectiveSample) { AllocateInput(m_NoPerspectiveSample, offset, i, forceLiveOut); offset += m_NoPerspectiveSample->GetSize(); } // Add support for POSITION_Z if (m_pPositionZPixel) { AllocateInput(m_pPositionZPixel, offset, i, forceLiveOut); offset += m_pPositionZPixel->GetSize(); } // Add support for POSITION_W if (m_pPositionWPixel) { AllocateInput(m_pPositionWPixel, offset, i, forceLiveOut); offset += m_pPositionWPixel->GetSize(); } // Add support for POSITION_XY_OFFSET if (m_pPositionXYOffset) { { AllocateInput(m_pPositionXYOffset, offset, i, forceLiveOut); offset += m_pPositionXYOffset->GetSize(); } } // Add support for input coverage mask if (m_pInputCoverageMask) { AllocateInput(m_pInputCoverageMask, offset, i, forceLiveOut); offset += m_pInputCoverageMask->GetSize(); } { if (m_pCPSRequestedSizeX || m_pCPSRequestedSizeY) { if (m_pCPSRequestedSizeX) { AllocateInput(m_pCPSRequestedSizeX, offset, i, forceLiveOut); } if (m_pCPSRequestedSizeY) { AllocateInput(m_pCPSRequestedSizeY, offset + SIZE_OWORD, i, forceLiveOut); } offset += getGRFSize(); } if (m_ZWDelta && i == numInstances - 1) { AllocateInput(m_ZWDelta, offset, 0, forceLiveOut); if (m_Signature) { GetDispatchSignature().ZWDelta = offset; } offset += getGRFSize(); } if (m_SampleOffsetX || m_SampleOffsetY) { if (m_SampleOffsetX) { AllocateInput(m_SampleOffsetX, offset, i, forceLiveOut); } if (m_SampleOffsetY) { AllocateInput(m_SampleOffsetY, offset + SIZE_OWORD, i, forceLiveOut); } if (m_Signature) { GetDispatchSignature().pixelOffset = offset; } offset += getGRFSize(); } } } IGC_ASSERT(offset % getGRFSize() == 0); // need to return the starting grf for constant to client ProgramOutput()->m_startReg = offset / getGRFSize(); // allocate space for NOS constants and pushed constants AllocateConstants3DShader(offset); // Allocate size for attributes coming from VS IGC_ASSERT(offset % getGRFSize() == 0); unsigned int payloadEnd = offset; for (uint i = 0; i < setup.size(); i++) { if (setup[i] && setup[i]->GetAlias() == NULL) { uint subRegOffset = 0; // PS uniform (constant interpolation) inputs if (setup[i]->GetSize() == SIZE_DWORD) { { subRegOffset = 3 * SIZE_DWORD; } } AllocateInput(setup[i], offset + subRegOffset, 0, forceLiveOut); if (m_Signature) { GetDispatchSignature().inputOffset[i] = offset; } payloadEnd = offset + setup[i]->GetSize(); } { offset += 4 * SIZE_DWORD; } } offset = payloadEnd; // For code patching, we preallocate live-out of payload into physical registers. // The preallocation must be aligned across contexts to ensure it is patchable. if (encoder.IsCodePatchCandidate()) { if (encoder.HasPrevKernel()) { // Get previous context's PayloadEnd to ensure it is patchable offset = encoder.GetPayloadEnd(); } else { encoder.SetPayloadEnd(payloadEnd); } } if (offset % getGRFSize() != 0) { offset += (getGRFSize() - (offset % getGRFSize())); } // This is the preallocation for payload live-outs. for (auto& var : payloadLiveOutSetup) { IGC_ASSERT(offset% getGRFSize() == 0); AllocateInput(var, offset, 0, true); offset += var->GetSize(); } // This is the preallocation for temp variables in payload sections for (auto& var : payloadTempSetup) { AllocateInput(var, offset); offset += var->GetSize(); } // When preallocation failed (exceeding the total number of physical registers), early exit and give up this compilation._ ProgramOutput()->m_scratchSpaceUsedBySpills = offset >= encoder.GetVISAKernel()->getNumRegTotal() * getGRFSize(); if (ProgramOutput()->m_scratchSpaceUsedBySpills) { return; } offset = payloadEnd; // create output registers for coarse phase for (const auto& it : m_CoarseOutput) { CVariable* output = it.second; offset = iSTD::Align(offset, (size_t) 1 << output->GetAlign()); AllocateOutput(output, offset); if (m_Signature) { GetDispatchSignature().PSOutputOffset[it.first] = offset; } offset += output->GetSize(); } if (m_CoarseoMask) { offset = iSTD::Align(offset, (size_t) 1 << m_CoarseoMask->GetAlign()); AllocateOutput(m_CoarseoMask, offset); if (m_Signature) { GetDispatchSignature().oMaskOffset = offset; GetDispatchSignature().CoarseMask = true; } offset += m_CoarseoMask->GetSize(); } ProgramOutput()->m_scratchSpaceUsedBySpills = (offset >= encoder.GetVISAKernel()->getNumRegTotal() * getGRFSize()); } PSSignature::DispatchSignature& CPixelShader::GetDispatchSignature() { switch (m_dispatchSize) { case SIMDMode::SIMD8: return m_Signature->dispatchSign[0]; case SIMDMode::SIMD16: return m_Signature->dispatchSign[1]; case SIMDMode::SIMD32: return m_Signature->dispatchSign[2]; default: IGC_ASSERT_MESSAGE(0, ""bad dispatch size""); break; } return m_Signature->dispatchSign[0]; } CVariable* CPixelShader::GetBaryReg(e_interpolation mode) { uint numInstances = m_numberInstance; uint numElements = 2 * numLanes(m_SIMDSize); CVariable* baryReg = 0; switch (mode) { case EINTERPOLATION_LINEAR: if (!m_PerspectivePixel) { m_PerspectivePixel = GetNewVariable(numElements, ISA_TYPE_F, EALIGN_GRF, false, numInstances, ""PerspectivePixel""); } baryReg = m_PerspectivePixel; break; case EINTERPOLATION_LINEARCENTROID: if (!m_PerspectiveCentroid) { m_PerspectiveCentroid = GetNewVariable( numElements, ISA_TYPE_F, EALIGN_GRF, false, numInstances, ""LinearCentroid""); } baryReg = m_PerspectiveCentroid; break; case EINTERPOLATION_LINEARSAMPLE: if (!m_PerspectiveSample) { m_PerspectiveSample = GetNewVariable( numElements, ISA_TYPE_F, EALIGN_GRF, false, numInstances, ""LinearSample""); } baryReg = m_PerspectiveSample; break; case EINTERPOLATION_LINEARNOPERSPECTIVE: if (!m_NoPerspectivePixel) { m_NoPerspectivePixel = GetNewVariable( numElements, ISA_TYPE_F, EALIGN_GRF, false, numInstances, ""LinearNoPerspective""); } baryReg = m_NoPerspectivePixel; break; case EINTERPOLATION_LINEARNOPERSPECTIVECENTROID: if (!m_NoPerspectiveCentroid) { m_NoPerspectiveCentroid = GetNewVariable( numElements, ISA_TYPE_F, EALIGN_GRF, false, numInstances, ""NoPerspectiveCentroid""); } baryReg = m_NoPerspectiveCentroid; break; case EINTERPOLATION_LINEARNOPERSPECTIVESAMPLE: if (!m_NoPerspectiveSample) { m_NoPerspectiveSample = GetNewVariable( numElements, ISA_TYPE_F, EALIGN_GRF, false, numInstances, ""NoPerspectiveSample""); } baryReg = m_NoPerspectiveSample; break; default: IGC_ASSERT(0); } return baryReg; } CVariable* CPixelShader::GetBaryRegLoweredHalf(e_interpolation mode) { IGC_ASSERT(IsInterpolationLinear(mode)); const char* const name = mode == EINTERPOLATION_LINEAR ? ""PerspectivePixelLoweredHalf"" : mode == EINTERPOLATION_LINEARCENTROID ? ""PerspectiveCentroidLoweredHalf"" : mode == EINTERPOLATION_LINEARSAMPLE ? ""PerspectiveSampleLoweredHalf"" : mode == EINTERPOLATION_LINEARNOPERSPECTIVE ? ""NoPerspectivePixelLoweredHalf"" : mode == EINTERPOLATION_LINEARNOPERSPECTIVECENTROID ? ""NoPerspectiveCentroidLoweredHalf"" : mode == EINTERPOLATION_LINEARNOPERSPECTIVESAMPLE ? ""NoPerspectiveSampleLoweredHalf"" : """"; if (!m_BaryRegLoweredHalf[mode]) { m_BaryRegLoweredHalf[mode] = GetNewVariable( 2 * numLanes(m_SIMDSize), ISA_TYPE_HF, EALIGN_GRF, false, m_numberInstance, name); if (encoder.IsCodePatchCandidate()) { AddPatchTempSetup(m_BaryRegLoweredHalf[mode]); } } return m_BaryRegLoweredHalf[mode]; } CVariable* CPixelShader::GetBaryRegLoweredFloat(e_interpolation mode) { IGC_ASSERT(IsInterpolationLinear(mode)); const char* const name = mode == EINTERPOLATION_LINEAR ? ""PerspectivePixelLoweredFloat"" : mode == EINTERPOLATION_LINEARCENTROID ? ""PerspectiveCentroidLoweredFloat"" : mode == EINTERPOLATION_LINEARSAMPLE ? ""PerspectiveSampleLoweredFloat"" : mode == EINTERPOLATION_LINEARNOPERSPECTIVE ? ""NoPerspectivePixelLoweredFloat"" : mode == EINTERPOLATION_LINEARNOPERSPECTIVECENTROID ? ""NoPerspectiveCentroidLoweredFloat"" : mode == EINTERPOLATION_LINEARNOPERSPECTIVESAMPLE ? ""NoPerspectiveSampleLoweredFloat"" : """"; if (!m_BaryRegLoweredFloat[mode]) { m_BaryRegLoweredFloat[mode] = GetNewVariable( 2 * numLanes(m_SIMDSize), ISA_TYPE_F, EALIGN_GRF, false, m_numberInstance, name); if (encoder.IsCodePatchCandidate()) { AddPatchTempSetup(m_BaryRegLoweredFloat[mode]); } } return m_BaryRegLoweredFloat[mode]; } CVariable* CPixelShader::GetInputDelta(uint index, bool loweredInput) { CVariable* inputVar = setup[index]; if (inputVar == nullptr) { if (loweredInput) { if (index % 2 == 0) { inputVar = GetNewVariable(8, ISA_TYPE_F, EALIGN_GRF, true, CName::NONE); setup[index + 1] = GetNewAlias(inputVar, ISA_TYPE_F, 16, 4); } else { inputVar = GetNewAlias(GetInputDelta(index - 1), ISA_TYPE_F, 16, 4); } } else { inputVar = GetNewVariable(4, ISA_TYPE_F, EALIGN_OWORD, true, CName::NONE); } setup[index] = inputVar; } return inputVar; } CVariable* CPixelShader::GetInputDeltaLowered(uint index) { CVariable* inputVar = setupLowered[index]; if (inputVar == nullptr) { IGC_ASSERT(LowerPSInput()); if (index % 2 == 0) { inputVar = GetNewVariable(8, ISA_TYPE_HF, EALIGN_OWORD, true, CName::NONE); } else { if (setupLowered[index - 1]) { inputVar = GetNewAlias(setupLowered[index - 1], ISA_TYPE_HF, 8, 4); } else { inputVar = GetNewVariable(4, ISA_TYPE_HF, EALIGN_OWORD, true, CName::NONE); } } setupLowered[index] = inputVar; } return inputVar; } CVariable* CPixelShader::GetZWDelta() { if (!m_ZWDelta) { uint numLanes = getGRFSize() / SIZE_DWORD ; // single GRF m_ZWDelta = GetNewVariable(numLanes, ISA_TYPE_F, EALIGN_GRF, false, 1, ""ZWDelta""); } return m_ZWDelta; } CVariable* CPixelShader::GetPositionZ() { uint16_t numberInstance, numberLanes; { numberLanes = numLanes(m_SIMDSize); numberInstance = m_numberInstance; } if (!m_pPositionZPixel) { m_pPositionZPixel = GetNewVariable(numberLanes, ISA_TYPE_F, EALIGN_GRF, false, numberInstance, ""PosZPixel""); } return m_pPositionZPixel; } CVariable* CPixelShader::GetPositionW() { uint16_t numberInstance, numberLanes; { numberLanes = numLanes(m_SIMDSize); numberInstance = m_numberInstance; } if (!m_pPositionWPixel) { m_pPositionWPixel = GetNewVariable(numberLanes, ISA_TYPE_F, EALIGN_GRF, false, numberInstance, ""PosWPixel""); } return m_pPositionWPixel; } CVariable* CPixelShader::GetPositionXYOffset() { if (!m_pPositionXYOffset) { m_pPositionXYOffset = GetNewVariable(32, ISA_TYPE_B, EALIGN_GRF, false, m_numberInstance, ""PosXYOff""); } return m_pPositionXYOffset; } CVariable* CPixelShader::GetInputCoverageMask() { uint16_t numberInstance, numberLanes; { numberLanes = numLanes(m_SIMDSize); numberInstance = m_numberInstance; } if (!m_pInputCoverageMask) { m_pInputCoverageMask = GetNewVariable( numberLanes, ISA_TYPE_F, EALIGN_GRF, false, numberInstance, ""InputCoverageMask""); } return m_pInputCoverageMask; } CVariable* CPixelShader::GetSampleOffsetX() { if (!m_SampleOffsetX) { m_SampleOffsetX = GetNewVariable(16, ISA_TYPE_UB, EALIGN_OWORD, true, ""SmplOffX""); } return m_SampleOffsetX; } CVariable* CPixelShader::GetSampleOffsetY() { if (!m_SampleOffsetY) { m_SampleOffsetY = GetNewVariable(16, ISA_TYPE_UB, EALIGN_OWORD, true, ""SmplOffY""); } return m_SampleOffsetY; } CVariable* CPixelShader::GetCPSRequestedSizeX() { if (!m_pCPSRequestedSizeX) { m_pCPSRequestedSizeX = GetNewVariable( numLanes(m_SIMDSize) / 4, ISA_TYPE_F, EALIGN_OWORD, false, m_numberInstance, ""CPSReqSizeX""); } return m_pCPSRequestedSizeX; } CVariable* CPixelShader::GetCPSRequestedSizeY() { if (!m_pCPSRequestedSizeY) { m_pCPSRequestedSizeY = GetNewVariable( numLanes(m_SIMDSize) / 4, ISA_TYPE_F, EALIGN_OWORD, false, m_numberInstance, ""CPSReqSizeY""); } return m_pCPSRequestedSizeY; } CPixelShader::CPixelShader(llvm::Function* pFunc, CShaderProgram* pProgram) : CShader(pFunc, pProgram) { m_RenderTargetMask = 0; m_HasoDepth = false; m_HasoStencil = false; m_HasoMask = false; m_isPerSample = false; m_HasInputCoverageMask = false; m_HasPullBary = false; m_HasCoarseSize = false; m_HasDouble = false; m_hasDualBlendSource = false; m_HasDiscard = false; m_IsLastPhase = false; m_phase = PSPHASE_LEGACY; m_Signature = nullptr; m_samplerCount = 0; m_ModeUsedHalf.reset(); m_ModeUsedFloat.reset(); setupLowered.clear(); loweredSetupIndexes.clear(); m_BaryRegLoweredHalf.fill(nullptr); m_BaryRegLoweredFloat.fill(nullptr); Function* coarsePhase = nullptr; Function* pixelPhase = nullptr; NamedMDNode* coarseNode = pFunc->getParent()->getNamedMetadata(NAMED_METADATA_COARSE_PHASE); NamedMDNode* pixelNode = pFunc->getParent()->getNamedMetadata(NAMED_METADATA_PIXEL_PHASE); if (coarseNode) { coarsePhase = llvm::mdconst::dyn_extract(coarseNode->getOperand(0)->getOperand(0)); } if (pixelNode) { pixelPhase = llvm::mdconst::dyn_extract(pixelNode->getOperand(0)->getOperand(0)); } if (pFunc == coarsePhase) { m_phase = PSPHASE_COARSE; } if (coarsePhase && pixelPhase) { if (pFunc == pixelPhase) { m_phase = PSPHASE_PIXEL; m_IsLastPhase = true; } } else { m_IsLastPhase = true; } } CPixelShader::~CPixelShader() { } void CPixelShader::InitEncoder(SIMDMode simdMode, bool canAbortOnSpill, ShaderDispatchMode shaderMode) { m_R1 = NULL; m_PerspectiveBaryPlanes = nullptr; m_NonPerspectiveBaryPlanes = nullptr; m_PerspectivePixel = NULL; m_PerspectiveCentroid = NULL; m_PerspectiveSample = NULL; m_NoPerspectivePixel = NULL; m_NoPerspectiveCentroid = NULL; m_NoPerspectiveSample = NULL; m_BaryRegLoweredHalf.fill(nullptr); m_BaryRegLoweredFloat.fill(nullptr); m_KillPixelMask = NULL; m_HasDiscard = false; m_pPositionZPixel = NULL; m_pPositionWPixel = NULL; m_pPositionXYOffset = NULL; m_pInputCoverageMask = NULL; m_pCPSRequestedSizeX = NULL; m_pCPSRequestedSizeY = NULL; m_PixelPhasePayload = nullptr; m_PixelPhaseCounter = nullptr; m_SampleOffsetX = nullptr; m_SampleOffsetY = nullptr; m_ZWDelta = nullptr; m_hasEOT = false; m_NeedPSSync = false; m_CoarseoMask = nullptr; m_CoarseMaskInput = nullptr; m_CoarseR1 = nullptr; m_CoarseOutput.clear(); m_CoarseInput.clear(); rtWriteList.clear(); setupLowered.clear(); loweredSetupIndexes.clear(); m_ModeUsedHalf.reset(); m_ModeUsedFloat.reset(); CShader::InitEncoder(simdMode, canAbortOnSpill, shaderMode); } void CShaderProgram::FillProgram(SPixelShaderKernelProgram* pKernelProgram) { const unsigned int InstCacheSize = 0xC000; CPixelShader* simd8Shader = static_cast(GetShader(SIMDMode::SIMD8)); CPixelShader* simd16Shader = static_cast(GetShader(SIMDMode::SIMD16)); CPixelShader* simd32Shader = static_cast(GetShader(SIMDMode::SIMD32)); CPixelShader* pShader = nullptr; if (simd32Shader) { const unsigned kernelSize = simd32Shader->m_simdProgram.m_programSize; const bool forceSIMD32 = (this->GetContext()->getCompilerOption().forcePixelShaderSIMDMode & FLAG_PS_SIMD_MODE_FORCE_SIMD32) != 0; if ((!simd8Shader && !simd16Shader) || (kernelSize > 0 && (kernelSize < InstCacheSize || forceSIMD32))) { pKernelProgram->simd32 = *simd32Shader->ProgramOutput(); pShader = simd32Shader; GetContext()->SetSIMDInfo(SIMD_SELECTED, SIMDMode::SIMD32, ShaderDispatchMode::NOT_APPLICABLE); } else if (kernelSize > 0 && (kernelSize < InstCacheSize)) { GetContext()->SetSIMDInfo(SIMD_SKIP_PERF, SIMDMode::SIMD32, ShaderDispatchMode::NOT_APPLICABLE); } } if (simd16Shader) { if (!simd8Shader || (simd16Shader->m_simdProgram.m_programSize > 0)) { pKernelProgram->simd16 = *simd16Shader->ProgramOutput(); pShader = simd16Shader; GetContext()->SetSIMDInfo(SIMD_SELECTED, SIMDMode::SIMD16, ShaderDispatchMode::NOT_APPLICABLE); } } { if (simd8Shader && simd8Shader->m_simdProgram.m_programSize > 0) { pKernelProgram->simd8 = *simd8Shader->ProgramOutput(); pShader = simd8Shader; GetContext()->SetSIMDInfo(SIMD_SELECTED, SIMDMode::SIMD8, ShaderDispatchMode::NOT_APPLICABLE); } } if (pShader) { pShader->FillProgram(pKernelProgram); } pKernelProgram->SIMDInfo = GetContext()->GetSIMDInfo(); } void CPixelShader::FillProgram(SPixelShaderKernelProgram* pKernelProgram) { const PixelShaderInfo& psInfo = GetContext()->getModuleMetaData()->psInfo; pKernelProgram->blendToFillEnabled = psInfo.blendToFillEnabled; pKernelProgram->forceEarlyZ = psInfo.forceEarlyZ; pKernelProgram->isCoarsePS = m_phase == PSPHASE_COARSE; pKernelProgram->hasCoarsePixelSize = m_HasCoarseSize; pKernelProgram->hasSampleOffset = m_SampleOffsetX || m_SampleOffsetY; pKernelProgram->hasZWDelta = m_ZWDelta; pKernelProgram->needPerspectiveBaryPlane = m_PerspectiveBaryPlanes ? true : false;; pKernelProgram->needNonPerspectiveBaryPlane = m_NonPerspectiveBaryPlanes ? true : false;; pKernelProgram->ConstantBufferLoaded = m_constantBufferLoaded; pKernelProgram->UavLoaded = m_uavLoaded; for (int i = 0; i < 4; i++) { pKernelProgram->ShaderResourceLoaded[i] = m_shaderResourceLoaded[i]; } pKernelProgram->RenderTargetLoaded = m_renderTargetLoaded; pKernelProgram->hasControlFlow = m_numBlocks > 1 ? true : false; pKernelProgram->MaxNumberOfThreads = m_Platform->getMaxPixelShaderThreads() / GetShaderThreadUsageRate(); pKernelProgram->needPerspectiveBary = m_PerspectivePixel ? true : false; pKernelProgram->needPerspectiveCentroidBary = m_PerspectiveCentroid ? true : false; pKernelProgram->needPerspectiveSampleBary = m_PerspectiveSample ? true : false; pKernelProgram->needNonPerspectiveBary = m_NoPerspectivePixel ? true : false; pKernelProgram->needNonPerspectiveCentroidBary = m_NoPerspectiveCentroid ? true : false; pKernelProgram->needNonPerspectiveSampleBary = m_NoPerspectiveSample ? true : false; pKernelProgram->killPixel = m_HasDiscard; pKernelProgram->needSourceDepth = m_pPositionZPixel != nullptr; pKernelProgram->needSourceW = m_pPositionWPixel != nullptr; pKernelProgram->outputDepth = m_HasoDepth; pKernelProgram->oMask = m_HasoMask; pKernelProgram->outputStencil = m_HasoStencil; pKernelProgram->sampleCmpToDiscardOptimizationPossible = GetContext()->m_instrTypes.sampleCmpToDiscardOptimizationPossible; pKernelProgram->sampleCmpToDiscardOptimizationSlot = GetContext()->m_instrTypes.sampleCmpToDiscardOptimizationSlot; pKernelProgram->needPSSync = m_NeedPSSync; pKernelProgram->hasInputCoverageMask = m_HasInputCoverageMask; pKernelProgram->hasPullBary = m_HasPullBary; pKernelProgram->isPerSample = IsPerSample(); if (NamedMDNode * primIdNod = entry->getParent()->getNamedMetadata(""PrimIdLocation"")) { pKernelProgram->primIdLocation = int_cast( mdconst::dyn_extract(primIdNod->getOperand(0)->getOperand(0))->getZExtValue()); pKernelProgram->hasPrimID = true; } if (NamedMDNode* PointCoordNod = entry->getParent()->getNamedMetadata(""PointCoordLocation"")) { pKernelProgram->pointCoordLocation = int_cast( mdconst::dyn_extract(PointCoordNod->getOperand(0)->getOperand(0))->getZExtValue()); pKernelProgram->hasPointCoord = true; } pKernelProgram->posXYOffsetEnable = m_pPositionXYOffset ? true : false; pKernelProgram->VectorMask = m_VectorMask; pKernelProgram->samplerCount = GetSamplerCount(m_samplerCount); pKernelProgram->renderTargetMask = m_RenderTargetMask; pKernelProgram->constantInterpolationEnableMask = m_ConstantInterpolationMask; pKernelProgram->NOSBufferSize = m_NOSBufferSize / getMinPushConstantBufferAlignmentInBytes(); pKernelProgram->isMessageTargetDataCacheDataPort = isMessageTargetDataCacheDataPort; CreateGatherMap(); CreateConstantBufferOutput(pKernelProgram); pKernelProgram->bindingTableEntryCount = this->GetMaxUsedBindingTableEntryCount(); pKernelProgram->BindingTableEntryBitmap = this->GetBindingTableEntryBitmap(); // PS packed attributes for (uint attribute = 0; attribute <= m_MaxSetupIndex / 4; ++attribute) { pKernelProgram->attributeActiveComponent[attribute] = GetActiveComponents(attribute); const bool useComponent = pKernelProgram->attributeActiveComponent[attribute] != USC::GFX3DSTATE_SF_ATTRIBUTE_ACTIVE_COMPONENT_DISABLED; if (useComponent) { pKernelProgram->nbOfSFOutput = attribute + 1; } } for (unsigned i = 0; i < USC::NUM_PSHADER_OUTPUT_REGISTERS; i++) { pKernelProgram->OutputUseMask[i] = (unsigned char)psInfo.colorOutputMask[i]; } } void CPixelShader::PreCompile() { CreateImplicitArgs(); CodeGenContext* ctx = GetContext(); const uint8_t numberInstance = m_numberInstance; const bool isR1Available = true; if (isR1Available) { m_R1 = GetNewVariable(getGRFSize() / SIZE_DWORD, ISA_TYPE_D, EALIGN_GRF, false, numberInstance, ""R1""); } // make sure the return block is properly set if (ctx->getModule()->getNamedMetadata(""KillPixel"")) { m_HasDiscard = true; } setup.resize(4 * g_c_Max_PS_attributes, nullptr); if (LowerPSInput()) { setupLowered.resize(4 * g_c_Max_PS_attributes, nullptr); } } void CPixelShader::ParseShaderSpecificOpcode(llvm::Instruction* inst) { // temporary workaround to disable SIMD16 when double are present if (inst->getType()->isDoubleTy()) { m_HasDouble = true; } if (GenIntrinsicInst * genIntr = dyn_cast(inst)) { uint setupIndex; switch (genIntr->getIntrinsicID()) { case GenISAIntrinsic::GenISA_RenderTargetRead: m_NeedPSSync = true; if (GetPhase() == PSPHASE_LEGACY) { m_isPerSample = true; } break; case GenISAIntrinsic::GenISA_uavSerializeAll: case GenISAIntrinsic::GenISA_uavSerializeOnResID: m_NeedPSSync = true; break; case GenISAIntrinsic::GenISA_RTDualBlendSource: m_hasDualBlendSource = true; AddRenderTarget( cast(genIntr)->getRTIndexImm()); break; case GenISAIntrinsic::GenISA_RTWrite: { RTWritIntrinsic* rt = cast(genIntr); if (rt->getRTIndexImm() != -1) { AddRenderTarget(rt->getRTIndexImm()); } if (rt->hasStencil()) { OutputStencil(); } break; } case GenISAIntrinsic::GenISA_DCL_ShaderInputVec: case GenISAIntrinsic::GenISA_DCL_inputVec: { IGC_ASSERT(llvm::isa(inst->getOperand(0))); IGC_ASSERT(llvm::isa(inst->getOperand(1))); setupIndex = int_cast(llvm::cast(inst->getOperand(0))->getZExtValue()); m_MaxSetupIndex = std::max(setupIndex, m_MaxSetupIndex); // attribute packing m_SetupIndicesUsed.insert(setupIndex); e_interpolation mode = static_cast(llvm::cast(inst->getOperand(1))->getZExtValue()); if (mode != EINTERPOLATION_CONSTANT) { { if (inst->getType()->isHalfTy()) { loweredSetupIndexes.insert(setupIndex); m_ModeUsedHalf.set(mode); } else { m_ModeUsedFloat.set(mode); } } } break; } case GenISAIntrinsic::GenISA_PullSampleIndexBarys: case GenISAIntrinsic::GenISA_PullSnappedBarys: case GenISAIntrinsic::GenISA_PullCentroidBarys: m_HasPullBary = true; break; case GenISAIntrinsic::GenISA_Interpolate: IGC_ASSERT(llvm::isa(inst->getOperand(0))); setupIndex = int_cast(llvm::cast(inst->getOperand(0))->getZExtValue()); m_MaxSetupIndex = std::max(setupIndex, m_MaxSetupIndex); // attribute packing m_SetupIndicesUsed.insert(setupIndex); break; default: break; } } } void CPixelShader::AddRenderTarget(uint RTIndex) { m_RenderTargetMask |= 1 << RTIndex; } void CPixelShader::DeclareSGV(uint usage) { switch (usage) { case POSITION_X: case POSITION_Y: break; case POSITION_Z: break; case POSITION_W: break; case VFACE: break; case INPUT_COVERAGE_MASK: m_HasInputCoverageMask = true; break; case SAMPLEINDEX: m_isPerSample = true; break; case REQUESTED_COARSE_SIZE_X: case REQUESTED_COARSE_SIZE_Y: m_HasCoarseSize = true; break; default: break; // nothing to do } } void CPixelShader::PullPixelPhasePayload() { CVariable* payload = nullptr; bool oMask = false; if (GetDispatchSignature().CoarseMask) { payload = GetCoarseMask(); oMask = true; } else { payload = GetNewVariable(8, ISA_TYPE_D, EALIGN_GRF, CName::NONE); } uint messageDescriptor = PIPullPixelPayload( m_SIMDSize == SIMDMode::SIMD8 ? EU_PI_MESSAGE_SIMD8 : EU_PI_MESSAGE_SIMD16, m_PixelPhasePayload->GetSize() / getGRFSize(), payload->GetSize() / getGRFSize(), false, false, false, false, false, oMask); CVariable* desc = ImmToVariable(messageDescriptor, ISA_TYPE_UD); // save the current phase counter as it is needed by the RT write m_CurrentPhaseCounter = GetNewVariable(1, ISA_TYPE_UD, EALIGN_DWORD, true, ""CurrPhaseCounter""); encoder.SetSrcRegion(0, 0, 1, 0); encoder.Shl(m_CurrentPhaseCounter, m_PixelPhaseCounter, ImmToVariable(0x10, ISA_TYPE_UW)); encoder.Push(); CVariable* nextPhase = GetNewVariable(1, ISA_TYPE_UW, EALIGN_DWORD, true, ""NextPhase""); encoder.SetSrcRegion(0, 0, 1, 0); encoder.Shl(nextPhase, m_PixelPhaseCounter, ImmToVariable(8, ISA_TYPE_D)); encoder.Push(); CVariable* a0 = GetNewVariable(1, ISA_TYPE_UD, EALIGN_DWORD, true, CName::NONE); encoder.Or(a0, nextPhase, desc); encoder.Push(); encoder.SetNoMask(); encoder.Send(m_PixelPhasePayload, payload, EU_GEN7_MESSAGE_TARGET_PIXEL_INTERPOLATOR, a0); encoder.Push(); CVariable* mask = BitCast(m_PixelPhasePayload, ISA_TYPE_UW); CVariable* f0 = GetNewVariable(numLanes(m_SIMDSize), ISA_TYPE_BOOL, EALIGN_DWORD, true, CName::NONE); encoder.SetSrcSubReg(0, 14); encoder.SetSrcRegion(0, 0, 1, 0); encoder.Cmp(EPREDICATE_EQ, f0, mask, ImmToVariable(0, ISA_TYPE_UW)); encoder.Push(); m_epilogueLabel = encoder.GetNewLabelID(""epilogue""); encoder.Jump(f0, m_epilogueLabel); encoder.Push(); // override the execution mask in sr0.2 encoder.SetSrcSubReg(0, 14); encoder.SetDstSubReg(2); encoder.SetSrcRegion(0, 0, 1, 0); encoder.Cast(GetSR0(), mask); encoder.Push(); } void CPixelShader::AddPrologue() { if (m_phase == PSPHASE_PIXEL) { uint responseLength = 2; m_CoarseR1 = GetR1(); m_PixelPhasePayload = GetNewVariable(responseLength * (getGRFSize() >> 2), ISA_TYPE_D, EALIGN_GRF, ""PixelPhasePayload""); m_PixelPhaseCounter = GetNewAlias(m_PixelPhasePayload, ISA_TYPE_UW, 0, 1); m_CoarseParentIndex = GetNewAlias(m_PixelPhasePayload, ISA_TYPE_UW, getGRFSize(), numLanes(m_SIMDSize)); m_R1 = GetNewAlias(m_PixelPhasePayload, ISA_TYPE_D, 0, getGRFSize() / SIZE_DWORD); encoder.SetNoMask(); encoder.SetSimdSize(SIMDMode::SIMD1); encoder.Copy(m_PixelPhaseCounter, ImmToVariable(0, ISA_TYPE_UW)); encoder.Push(); m_pixelPhaseLabel = encoder.GetNewLabelID(""pixel_phase""); encoder.Label(m_pixelPhaseLabel); encoder.Push(); PullPixelPhasePayload(); } { emitPSInputLowering(); } } void CPixelShader::PreAnalysisPass() { m_VectorMask = m_CG->NeedVMask(); CShader::PreAnalysisPass(); } void CPixelShader::AddEpilogue(llvm::ReturnInst* ret) { if (!IsLastPhase() && m_KillPixelMask) { if (!m_CoarseoMask) { m_CoarseoMask = GetNewVariable( numLanes(m_SIMDSize), ISA_TYPE_UD, EALIGN_GRF, ""CoarseOMask""); encoder.Copy(m_CoarseoMask, ImmToVariable(0xFFFFFFFF, ISA_TYPE_UD)); encoder.Push(); } encoder.SetPredicate(m_KillPixelMask); encoder.Copy(m_CoarseoMask, ImmToVariable(0x0, ISA_TYPE_UD)); encoder.Push(); } if (m_phase == PSPHASE_PIXEL) { encoder.Label(m_epilogueLabel); encoder.Push(); // next phase index is in the first dword of the payload CVariable* flag = GetNewVariable( numLanes(m_SIMDSize), ISA_TYPE_BOOL, EALIGN_BYTE, true, CName::NONE); encoder.SetSrcRegion(0, 0, 1, 0); encoder.Cmp(EPREDICATE_NE, flag, m_PixelPhaseCounter, ImmToVariable(0, ISA_TYPE_UW)); encoder.Push(); encoder.Jump(flag, m_pixelPhaseLabel); encoder.Push(); const bool isPerCoarse = true; EOTRenderTarget(GetR1(), isPerCoarse); m_hasEOT = true; } if (IsLastPhase()) { CShader::AddEpilogue(ret); } } void CPixelShader::AddCoarseOutput(CVariable* output, unsigned int index) { IGC_ASSERT(m_CoarseOutput.find(index) == m_CoarseOutput.end()); m_CoarseOutput[index] = output; } CVariable* CPixelShader::GetCoarseInput(unsigned int index, uint16_t vectorSize, VISA_Type type) { auto it = m_CoarseInput.find(index); CVariable* coarseInput = nullptr; if (it == m_CoarseInput.end()) { coarseInput = GetNewVariable( numLanes(m_SIMDSize) * vectorSize, type, EALIGN_GRF, ""CoarseInput""); m_CoarseInput[index] = coarseInput; } else { coarseInput = it->second; } return coarseInput; } void CPixelShader::SetCoarseoMask(CVariable* oMask) { m_CoarseoMask = oMask; } CVariable* CPixelShader::GetCoarseMask() { if (m_CoarseMaskInput == nullptr) { m_CoarseMaskInput = GetNewVariable( numLanes(m_SIMDSize), ISA_TYPE_F, EALIGN_GRF, ""CoarseMaskInput""); } return m_CoarseMaskInput; } CVariable* CPixelShader::GetCoarseParentIndex() { return m_CoarseParentIndex; } CVariable* CPixelShader::GetCurrentPhaseCounter() { return m_CurrentPhaseCounter; } bool CPixelShader::CompileSIMDSize(SIMDMode simdMode, EmitPass& EP, llvm::Function& F) { if (!CompileSIMDSizeInCommon(simdMode)) return false; CodeGenContext* ctx = GetContext(); if (!ctx->m_retryManager.IsFirstTry()) { ctx->ClearSIMDInfo(simdMode, EP.m_ShaderDispatchMode); ctx->SetSIMDInfo(SIMD_RETRY, simdMode, EP.m_ShaderDispatchMode); } bool forceSIMD32 = (ctx->getCompilerOption().forcePixelShaderSIMDMode & FLAG_PS_SIMD_MODE_FORCE_SIMD32) != 0; bool forceSIMD16 = (ctx->getCompilerOption().forcePixelShaderSIMDMode & FLAG_PS_SIMD_MODE_FORCE_SIMD16) != 0; // For staged compilation, we try to avoid duplicated compilation for the same SIMD mode if ((simdMode == SIMDMode::SIMD8 && AvoidDupStage2(8 , ctx->m_CgFlag, ctx->m_StagingCtx)) || (simdMode == SIMDMode::SIMD16 && AvoidDupStage2(16, ctx->m_CgFlag, ctx->m_StagingCtx))) { return false; } if (ctx->PsHighSimdDisable) { if (simdMode == SIMDMode::SIMD32) return false; } if (m_HasoStencil && !ctx->platform.supportsStencil(simdMode)) { ctx->SetSIMDInfo(SIMD_SKIP_HW, simdMode, EP.m_ShaderDispatchMode); return false; } if (m_HasDouble && simdMode != SIMDMode::SIMD8) { ctx->SetSIMDInfo(SIMD_SKIP_HW, simdMode, EP.m_ShaderDispatchMode); return false; } if (m_hasDualBlendSource && simdMode != SIMDMode::SIMD8 && (m_phase == PSPHASE_PIXEL || ((m_phase != PSPHASE_LEGACY) && (ctx->platform.getWATable().Wa_1409392000 || ctx->platform.getPlatformInfo().eProductFamily == IGFX_ICELAKE)))) { // Spec restriction CPS multi-phase cannot use SIMD16 with dual source blending ctx->SetSIMDInfo(SIMD_SKIP_HW, simdMode, EP.m_ShaderDispatchMode); return false; } if (m_phase != PSPHASE_LEGACY && simdMode == SIMDMode::SIMD32) { ctx->SetSIMDInfo(SIMD_SKIP_HW, simdMode, EP.m_ShaderDispatchMode); return false; } if (GetContext()->platform.hasFusedEU() && simdMode == SIMDMode::SIMD32 && IsPerSample() && !IsStage1(ctx)) { //Fused SIMD32 not enabled when dispatch rate is per sample ctx->SetSIMDInfo(SIMD_SKIP_HW, simdMode, EP.m_ShaderDispatchMode); return false; } if (simdMode == SIMDMode::SIMD16 && EP.m_ShaderDispatchMode == ShaderDispatchMode::NOT_APPLICABLE) { if (IsStage1BestPerf(ctx->m_CgFlag, ctx->m_StagingCtx)) { return true; } if (DoSimd16Stage2(ctx->m_StagingCtx)) { return true; } if (IGC_IS_FLAG_ENABLED(ForceBestSIMD)) { return true; } if (forceSIMD16) { return true; } CShader* simd8Program = m_parent->GetShader(SIMDMode::SIMD8); if (simd8Program != nullptr && simd8Program->ProgramOutput()->m_scratchSpaceUsedBySpills > 0) { ctx->SetSIMDInfo(SIMD_SKIP_REGPRES, simdMode, EP.m_ShaderDispatchMode); return false; } } if (simdMode == SIMDMode::SIMD32) { if (DoSimd32Stage2(ctx->m_StagingCtx)) { return true; } if (forceSIMD32) { return true; } CShader* simd16Program = m_parent->GetShader(SIMDMode::SIMD16); if ((simd16Program == nullptr || simd16Program->ProgramOutput()->m_programBin == 0 || simd16Program->ProgramOutput()->m_scratchSpaceUsedBySpills > 0)) { ctx->SetSIMDInfo(SIMD_SKIP_REGPRES, simdMode, EP.m_ShaderDispatchMode); return false; } const PixelShaderInfo& psInfo = ctx->getModuleMetaData()->psInfo; // Disable simd32 compilation on platforms that do not support per-pixel // dispatch with num samples == 16. if (psInfo.NumSamples == 16 && !ctx->platform.supportSimd32PerPixelPSWithNumSamples16() && !IsPerSample()) { return false; } if (psInfo.ForceEnableSimd32) // UMD forced compilation of simd32. { return true; } if (!ctx->platform.enablePSsimd32()) { ctx->SetSIMDInfo(SIMD_SKIP_HW, simdMode, EP.m_ShaderDispatchMode); return false; } if (iSTD::BitCount(m_RenderTargetMask) > 1) { // don't compile SIMD32 for MRT as we may trash the render cache ctx->SetSIMDInfo(SIMD_SKIP_PERF, simdMode, EP.m_ShaderDispatchMode); return false; } Simd32ProfitabilityAnalysis& PA = EP.getAnalysis(); if (PA.isSimd32Profitable()) { return true; } else { ctx->SetSIMDInfo(SIMD_SKIP_PERF, simdMode, EP.m_ShaderDispatchMode); } if (simd16Program && static_cast(simd16Program)->m_sendStallCycle == 0) { // simd16 doesn't have any latency issue, no need to try simd32 ctx->SetSIMDInfo(SIMD_SKIP_STALL, simdMode, EP.m_ShaderDispatchMode); return false; } if (ctx->platform.psSimd32SkipStallHeuristic() && ctx->m_DriverInfo.AlwaysEnableSimd32()) { return true; } if (simd16Program) { uint sendStallCycle = static_cast(simd16Program)->m_sendStallCycle; uint staticCycle = static_cast(simd16Program)->m_staticCycle; if (sendStallCycle / (float)staticCycle > 0.4) { return true; } else { ctx->SetSIMDInfo(SIMD_SKIP_STALL, simdMode, EP.m_ShaderDispatchMode); } } return false; } return true; } void linkProgram(const SProgramOutput& cps, const SProgramOutput& ps, SProgramOutput& linked) { linked.m_unpaddedProgramSize = cps.m_unpaddedProgramSize + ps.m_unpaddedProgramSize; linked.m_scratchSpaceUsedByShader = cps.m_scratchSpaceUsedByShader + ps.m_scratchSpaceUsedByShader; linked.m_scratchSpaceUsedBySpills = cps.m_scratchSpaceUsedBySpills + ps.m_scratchSpaceUsedBySpills; linked.m_scratchSpaceUsedByGtpin = cps.m_scratchSpaceUsedByGtpin + ps.m_scratchSpaceUsedByGtpin; linked.m_programSize = iSTD::Align(linked.m_unpaddedProgramSize, 64); linked.m_programBin = IGC::aligned_malloc(linked.m_programSize, 16); // Copy coarse phase memcpy_s(linked.m_programBin, cps.m_unpaddedProgramSize, cps.m_programBin, cps.m_unpaddedProgramSize); // Copy pixel phase memcpy_s((char*)linked.m_programBin + cps.m_unpaddedProgramSize, ps.m_unpaddedProgramSize, ps.m_programBin, ps.m_unpaddedProgramSize); memset((char*)linked.m_programBin + linked.m_unpaddedProgramSize, 0, linked.m_programSize - linked.m_unpaddedProgramSize); } void linkCPS(SPixelShaderKernelProgram* output, SPixelShaderKernelProgram& linked, unsigned int numberPhases) { SPixelShaderKernelProgram CoarsePhaseOutput = output[0]; SPixelShaderKernelProgram PixelPhaseOutput = output[1]; linked = output[0]; if (CoarsePhaseOutput.simd16.m_scratchSpaceUsedBySpills == 0 && CoarsePhaseOutput.simd16.m_programBin != nullptr && PixelPhaseOutput.simd16.m_scratchSpaceUsedBySpills == 0 && PixelPhaseOutput.simd16.m_programBin != nullptr) { linkProgram(CoarsePhaseOutput.simd16, PixelPhaseOutput.simd16, linked.simd16); } else { linked.simd16.m_programBin = nullptr; linked.simd16.m_programSize = 0; } linkProgram(CoarsePhaseOutput.simd8, PixelPhaseOutput.simd8, linked.simd8); linked.hasPullBary = true; linked.renderTargetMask = (CoarsePhaseOutput.renderTargetMask || PixelPhaseOutput.renderTargetMask); IGC_ASSERT_MESSAGE(numberPhases == 2, ""maximum number of phases is 2""); } void CodeGen(PixelShaderContext* ctx) { Function* coarsePhase = nullptr; Function* pixelPhase = nullptr; NamedMDNode* coarseNode = nullptr; NamedMDNode* pixelNode = nullptr; MetaDataUtils* pMdUtils = nullptr; if (!HasSavedIR(ctx)) { coarseNode = ctx->getModule()->getNamedMetadata(NAMED_METADATA_COARSE_PHASE); pixelNode = ctx->getModule()->getNamedMetadata(NAMED_METADATA_PIXEL_PHASE); if (coarseNode) { coarsePhase = mdconst::dyn_extract(coarseNode->getOperand(0)->getOperand(0)); } if (pixelNode) { pixelPhase = mdconst::dyn_extract(pixelNode->getOperand(0)->getOperand(0)); } pMdUtils = ctx->getMetaDataUtils(); } bool codegenDone = false; CShaderProgram::KernelShaderMap coarseShaders; CShaderProgram::KernelShaderMap pixelShaders; if (coarsePhase && pixelPhase) { // Cancelling staged compilation for multi stage PS. ctx->m_CgFlag = FLAG_CG_ALL_SIMDS; //Multi stage PS, need to do separate compiler and link them unsigned int numStage = 2; PSSignature signature; FunctionInfoMetaDataHandle coarseFI, pixelFI; coarseFI = pMdUtils->getFunctionsInfoItem(coarsePhase); pixelFI = pMdUtils->getFunctionsInfoItem(pixelPhase); for (unsigned int i = 0; i < numStage; i++) { Function* phaseFunc = (i == 0) ? coarsePhase : pixelPhase; FunctionInfoMetaDataHandle phaseFI = (i == 0) ? coarseFI : pixelFI; CShaderProgram::KernelShaderMap& shaders = (i == 0) ? coarseShaders : pixelShaders; pMdUtils->clearFunctionsInfo(); pMdUtils->setFunctionsInfoItem(phaseFunc, phaseFI); pMdUtils->save(phaseFunc->getContext()); CodeGen(ctx, shaders, &signature); // Read the phase function from metadata again as it could be changed in the PushAnalysis pass if (i == 0) { coarseNode = ctx->getModule()->getNamedMetadata(NAMED_METADATA_COARSE_PHASE); } else { pixelNode = ctx->getModule()->getNamedMetadata(NAMED_METADATA_PIXEL_PHASE); } } codegenDone = true; for (unsigned int i = 0; i < numStage; i++) { Function* phaseFunc = (i == 0) ? mdconst::dyn_extract(coarseNode->getOperand(0)->getOperand(0)) : mdconst::dyn_extract(pixelNode->getOperand(0)->getOperand(0)); CShaderProgram::KernelShaderMap& shaders = (i == 0) ? coarseShaders : pixelShaders; CPixelShader* simd8Shader = static_cast(shaders[phaseFunc]->GetShader(SIMDMode::SIMD8)); CPixelShader* simd16Shader = static_cast(shaders[phaseFunc]->GetShader(SIMDMode::SIMD16)); CPixelShader* simd32Shader = static_cast(shaders[phaseFunc]->GetShader(SIMDMode::SIMD32)); if (!((simd8Shader && simd8Shader->ProgramOutput()->m_programBin) || (simd16Shader && simd16Shader->ProgramOutput()->m_programBin) || (simd32Shader && simd32Shader->ProgramOutput()->m_programBin) )) { shaders[phaseFunc]->DeleteShader(SIMDMode::SIMD8); shaders[phaseFunc]->DeleteShader(SIMDMode::SIMD16); shaders[phaseFunc]->DeleteShader(SIMDMode::SIMD32); if (i == 0) { delete shaders[coarsePhase]; coarsePhase = nullptr; } else { delete shaders[pixelPhase]; pixelPhase = nullptr; } } } if (coarsePhase && pixelPhase) { SPixelShaderKernelProgram outputs[2]; memset(&outputs, 0, 2 * sizeof(SPixelShaderKernelProgram)); for (unsigned int i = 0; i < numStage; i++) { Function* phaseFunc = (i == 0) ? mdconst::dyn_extract(coarseNode->getOperand(0)->getOperand(0)) : mdconst::dyn_extract(pixelNode->getOperand(0)->getOperand(0)); CShaderProgram::KernelShaderMap& shaders = (i == 0) ? coarseShaders : pixelShaders; shaders[phaseFunc]->FillProgram(&outputs[i]); COMPILER_SHADER_STATS_PRINT(shaders[phaseFunc]->m_shaderStats, ShaderType::PIXEL_SHADER, ctx->hash, """"); COMPILER_SHADER_STATS_SUM(ctx->m_sumShaderStats, shaders[phaseFunc]->m_shaderStats, ShaderType::PIXEL_SHADER); COMPILER_SHADER_STATS_DEL(shaders[phaseFunc]->m_shaderStats); delete shaders[phaseFunc]; } linkCPS(outputs, ctx->programOutput, numStage); // Kernels allocated in CISABuilder.cpp (Compile()) // are freed in CompilerOutputOGL.hpp (DeleteShaderCompilerOutputOGL()) // in case of CPS multistage PS they are separated. // Need to free original kernels here as DeleteShaderCompilerOutputOGL() // will clear new allocations for separated phases in this case. for (unsigned int i = 0; i < numStage; i++) { outputs[i].simd8.Destroy(); outputs[i].simd16.Destroy(); outputs[i].simd32.Destroy(); } } } if (!(coarsePhase && pixelPhase)) { CShaderProgram::KernelShaderMap shaders; Function* pFunc = nullptr; if (!codegenDone) { // Single PS CodeGen(ctx, shaders); pFunc = getUniqueEntryFunc(ctx->getMetaDataUtils(), ctx->getModuleMetaData()); } else { shaders = coarsePhase ? coarseShaders : pixelShaders; pFunc = coarsePhase ? coarsePhase : pixelPhase; } // gather data to send back to the driver shaders[pFunc]->FillProgram(&ctx->programOutput); COMPILER_SHADER_STATS_PRINT(shaders[pFunc]->m_shaderStats, ShaderType::PIXEL_SHADER, ctx->hash, """"); COMPILER_SHADER_STATS_SUM(ctx->m_sumShaderStats, shaders[pFunc]->m_shaderStats, ShaderType::PIXEL_SHADER); COMPILER_SHADER_STATS_DEL(shaders[pFunc]->m_shaderStats); delete shaders[pFunc]; } } void CPixelShader::CreatePassThroughVar() { CodeGenContext* ctx = GetContext(); NamedMDNode* pixelNode = ctx->getModule()->getNamedMetadata(""pixel_phase""); if (!pixelNode) { // if there is no pixel phase we have nothing to do return; } IGC_ASSERT(nullptr != GetR1()); encoder.MarkAsOutput(GetR1()); Function* pixelPhase = mdconst::dyn_extract(pixelNode->getOperand(0)->getOperand(0)); for (auto BB = pixelPhase->begin(), BE = pixelPhase->end(); BB != BE; ++BB) { llvm::BasicBlock* pLLVMBB = &(*BB); llvm::BasicBlock::InstListType& instructionList = pLLVMBB->getInstList(); for (auto I = instructionList.begin(), E = instructionList.end(); I != E; ++I) { if (GenIntrinsicInst * intr = dyn_cast(I)) { GenISAIntrinsic::ID IID = intr->getIntrinsicID(); if (IID == GenISAIntrinsic::GenISA_DCL_inputVec) { unsigned int setupIndex = (uint)llvm::cast(intr->getOperand(0))->getZExtValue(); CVariable* input = GetInputDelta(setupIndex); encoder.MarkAsOutput(input); } else if (IID == GenISAIntrinsic::GenISA_SampleOffsetX) { CVariable* offset = GetSampleOffsetX(); encoder.MarkAsOutput(offset); } else if (IID == GenISAIntrinsic::GenISA_SampleOffsetY) { CVariable* offset = GetSampleOffsetY(); encoder.MarkAsOutput(offset); } else if (IID == GenISAIntrinsic::GenISA_DCL_SystemValue) { SGVUsage usage = (SGVUsage)llvm::cast(intr->getOperand(0))->getZExtValue(); if (usage == POSITION_Z || usage == POSITION_W) { CVariable* deltas = GetZWDelta(); encoder.MarkAsOutput(deltas); } } } } } GetDispatchSignature().inputOffset.resize(setup.size()); } void CPixelShader::ExtractGlobalVariables() { llvm::Module* module = GetContext()->getModule(); llvm::GlobalVariable* pGlobal = module->getGlobalVariable(""SamplerCount""); if (pGlobal) { auto samplerCount = int_cast(llvm::cast(pGlobal->getInitializer())->getZExtValue()); m_samplerCount = samplerCount; } } bool CPixelShader::IsReturnBlock(llvm::BasicBlock* bb) { return llvm::isa(bb->getTerminator()); } bool CPixelShader::IsLastRTWrite(llvm::GenIntrinsicInst* inst) { bool isLastRT; isLastRT = llvm::isa(inst->getNextNode()); return isLastRT && IsLastPhase() && GetPhase() != PSPHASE_PIXEL; } bool CPixelShader::LowerPSInput() { return (m_SIMDSize == SIMDMode::SIMD16 || !m_Platform->supportMixMode()); } bool CPixelShader::IsInterpolationLinear(e_interpolation mode) { return mode == EINTERPOLATION_LINEAR || mode == EINTERPOLATION_LINEARCENTROID || mode == EINTERPOLATION_LINEARSAMPLE || mode == EINTERPOLATION_LINEARNOPERSPECTIVE || mode == EINTERPOLATION_LINEARNOPERSPECTIVECENTROID || mode == EINTERPOLATION_LINEARNOPERSPECTIVESAMPLE; } void CPixelShader::emitPSInputLowering() { auto iterSetupIndex = loweredSetupIndexes.begin(); auto iterSetupIndexEnd = loweredSetupIndexes.end(); if (LowerPSInput()) { for (; iterSetupIndex != iterSetupIndexEnd; ++iterSetupIndex) { bool combineTwoDelta = false; auto nextElemt = iterSetupIndex; nextElemt++; if (nextElemt != iterSetupIndexEnd && *iterSetupIndex % 2 == 0 && *iterSetupIndex + 1 == *nextElemt) { combineTwoDelta = true; } unsigned int index = *iterSetupIndex; CVariable* inputVar = GetInputDelta(index, combineTwoDelta); CVariable* inputVarLowered = GetInputDeltaLowered(index); if (encoder.IsCodePatchCandidate()) { encoder.SetPayloadSectionAsPrimary(); AddPatchTempSetup(inputVarLowered); } encoder.SetSrcRegion(0, 1, 1, 0); encoder.SetUniformSIMDSize(combineTwoDelta ? SIMDMode::SIMD8 : SIMDMode::SIMD4); encoder.SetNoMask(); encoder.Cast(inputVarLowered, inputVar); encoder.Push(); if (encoder.IsCodePatchCandidate()) { encoder.SetPayloadSectionAsSecondary(); } if (combineTwoDelta) { ++iterSetupIndex; } } for (uint i = EINTERPOLATION_LINEAR; i < NUMBER_EINTERPOLATION; ++i) { if (m_ModeUsedHalf.test(i)) { CVariable* baryVar = GetBaryReg((e_interpolation)i); CVariable* baryVarLowered = GetBaryRegLoweredHalf((e_interpolation)i); if (encoder.IsCodePatchCandidate()) { encoder.SetPayloadSectionAsPrimary(); } for (uint8_t i = 0; i < m_numberInstance; ++i) { encoder.SetSecondHalf(i == 1); // mov SIMD8 U1/barry(0, 0) in to tmpU(0, 0) // mov (8) r1.0<1>:hf r2.0<8;8,1>:f {Align1, Q1, NoMask} // #??:$27:%30 encoder.SetSimdSize(SIMDMode::SIMD8); encoder.SetNoMask(); encoder.Cast(baryVarLowered, baryVar); encoder.Push(); if (m_SIMDSize == SIMDMode::SIMD16) { // mov SIMD8 U2/barry(2, 0) in to tmpU(0, 8) // mov (8) r1.8<1>:hf r4.0<8;8,1>:f {Align1, Q1, NoMask} // #??:$28:%31 encoder.SetSrcSubVar(0, 2); encoder.SetDstSubReg(8); encoder.SetSimdSize(SIMDMode::SIMD8); encoder.SetNoMask(); encoder.Cast(baryVarLowered, baryVar); encoder.Push(); } // mov SIMD8 V1/barry(1, 0) in to tmpV(0, 0) // mov (8) r12.0<1>:hf r3.0<8;8,1>:f {Align1, Q1, NoMask} // #??:$29:%32 encoder.SetSrcSubVar(0, 1); encoder.SetSimdSize(SIMDMode::SIMD8); encoder.SetNoMask(); encoder.SetDstSubReg(numLanes(m_SIMDSize)); encoder.Cast(baryVarLowered, baryVar); encoder.Push(); if (m_SIMDSize == SIMDMode::SIMD16) { // mov SIMD8 V1/barry(3, 0) in to tmpV(0, 0) // mov (8) r12.8<1>:hf r5.0<8;8,1>:f {Align1, Q1, NoMask} // #??:$30:%33 encoder.SetSrcSubVar(0, 3); encoder.SetDstSubReg(8); encoder.SetSimdSize(SIMDMode::SIMD8); encoder.SetNoMask(); encoder.SetDstSubVar(1); encoder.Cast(baryVarLowered, baryVar); encoder.Push(); } encoder.SetSecondHalf(false); } if (encoder.IsCodePatchCandidate()) { encoder.SetPayloadSectionAsSecondary(); } } } } } void CPixelShader::MarkConstantInterpolation(unsigned int index) { m_ConstantInterpolationMask |= BIT(index / 4); } // Take PS attribute and return active components within, encoded as HW expects. USC::GFX3DSTATE_SF_ATTRIBUTE_ACTIVE_COMPONENT CPixelShader::GetActiveComponents(uint attribute) const { USC::GFX3DSTATE_SF_ATTRIBUTE_ACTIVE_COMPONENT result = USC::GFX3DSTATE_SF_ATTRIBUTE_ACTIVE_COMPONENT_DISABLED; for (auto it = m_SetupIndicesUsed.lower_bound(attribute * 4); it != m_SetupIndicesUsed.end(); ++it) { if (attribute != (*it / 4)) break; switch (*it % 4) { case 0: case 1: result = USC::GFX3DSTATE_SF_ATTRIBUTE_ACTIVE_COMPONENT_XY; break; case 2: result = USC::GFX3DSTATE_SF_ATTRIBUTE_ACTIVE_COMPONENT_XYZ; break; case 3: result = USC::GFX3DSTATE_SF_ATTRIBUTE_ACTIVE_COMPONENT_XYZW; break; } } return result; } // this method must be run only after CShader::PreAnalysisPass() was run void CPixelShader::MapPushedInputs() { // first gather setup index info for (auto I = pushInfo.inputs.begin(), E = pushInfo.inputs.end(); I != E; I++) { m_SetupIndicesUsed.insert(I->second.index); m_MaxSetupIndex = std::max(I->second.index, m_MaxSetupIndex); } // then map using proper indexing for (auto I = pushInfo.inputs.begin(), E = pushInfo.inputs.end(); I != E; I++) { // We need to map the value associated with the value pushed to a physical register if (I->second.interpolationMode == EINTERPOLATION_CONSTANT) { this->MarkConstantInterpolation(I->second.index); } CVariable* var = GetSymbol(m_argListCache[I->second.argIndex]); AddSetup(getSetupIndex(I->second.index), var); } } int CPixelShader::getSetupIndex(uint inputIndex) { { return inputIndex; } } } // namespace IGC ",16268,True,2807.8266639444328,median "[[cluster-nodes-stats]] === Nodes stats API ++++ Nodes stats ++++ Returns cluster nodes statistics. [[cluster-nodes-stats-api-request]] ==== {api-request-title} `GET /_nodes/stats` + `GET /_nodes//stats` + `GET /_nodes/stats/` + `GET /_nodes//stats/` + `GET /_nodes/stats//` + `GET /_nodes//stats//` [[cluster-nodes-stats-api-desc]] ==== {api-description-title} You can use the cluster nodes stats API to retrieve statistics for nodes in a cluster. All the nodes selective options are explained <>. By default, all stats are returned. You can limit the returned information by using metrics. [[cluster-nodes-stats-api-path-params]] ==== {api-path-parms-title} ``:: (Optional, string) Limits the information returned to the specific metrics. A comma-separated list of the following options: + -- `adaptive_selection`:: Statistics about <>. `breaker`:: Statistics about the field data circuit breaker. `discovery`:: Statistics about the discovery. `fs`:: File system information, data path, free disk space, read/write stats. `http`:: HTTP connection information. `indexing_pressure`:: Statistics about the node's indexing load and related rejections. `indices`:: Indices stats about size, document count, indexing and deletion times, search times, field cache size, merges and flushes. `ingest`:: Statistics about ingest preprocessing. `jvm`:: JVM stats, memory pool information, garbage collection, buffer pools, number of loaded/unloaded classes. `os`:: Operating system stats, load average, mem, swap. `process`:: Process statistics, memory consumption, cpu usage, open file descriptors. `thread_pool`:: Statistics about each thread pool, including current size, queue and rejected tasks. `transport`:: Transport statistics about sent and received bytes in cluster communication. -- ``:: (Optional, string) Limit the information returned for `indices` metric to the specific index metrics. It can be used only if `indices` (or `all`) metric is specified. Supported metrics are: + -- * `completion` * `docs` * `fielddata` * `flush` * `get` * `indexing` * `merge` * `query_cache` * `recovery` * `refresh` * `request_cache` * `search` * `segments` * `store` * `translog` * `warmer` -- include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=node-id] [[cluster-nodes-stats-api-query-params]] ==== {api-query-parms-title} include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=completion-fields] include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=fielddata-fields] include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=fields] include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=groups] include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=level] `types`:: (Optional, string) A comma-separated list of document types for the `indexing` index metric. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=timeoutparms] include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=include-segment-file-sizes] [role=""child_attributes""] [[cluster-nodes-stats-api-response-body]] ==== {api-response-body-title} `_nodes`:: (object) Contains statistics about the number of nodes selected by the request. + .Properties of `_nodes` [%collapsible%open] ==== `total`:: (integer) Total number of nodes selected by the request. `successful`:: (integer) Number of nodes that responded successfully to the request. `failed`:: (integer) Number of nodes that rejected the request or failed to respond. If this value is not `0`, a reason for the rejection or failure is included in the response. ==== `cluster_name`:: (string) Name of the cluster. Based on the <> setting. `nodes`:: (object) Contains statistics for the nodes selected by the request. + .Properties of `nodes` [%collapsible%open] ==== ``:: (object) Contains statistics for the node. + .Properties of `` [%collapsible%open] ===== `timestamp`:: (integer) Time the node stats were collected for this response. Recorded in milliseconds since the {wikipedia}/Unix_time[Unix Epoch]. `name`:: (string) Human-readable identifier for the node. Based on the <> setting. `transport_address`:: (string) Host and port for the <>, used for internal communication between nodes in a cluster. `host`:: (string) Network host for the node, based on the <> setting. `ip`:: (string) IP address and port for the node. `roles`:: (array of strings) Roles assigned to the node. See <>. `attributes`:: (object) Contains a list of attributes for the node. [[cluster-nodes-stats-api-response-body-indices]] `indices`:: (object) Contains statistics about indices with shards assigned to the node. + .Properties of `indices` [%collapsible%open] ====== `docs`:: (object) Contains statistics about documents across all primary shards assigned to the node. + .Properties of `docs` [%collapsible%open] ======= `count`:: (integer) include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=docs-count] `deleted`:: (integer) include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=docs-deleted] ======= `store`:: (object) Contains statistics about the size of shards assigned to the node. + .Properties of `store` [%collapsible%open] ======= `size`:: (<>) Total size of all shards assigned to the node. `size_in_bytes`:: (integer) Total size, in bytes, of all shards assigned to the node. `reserved`:: (<>) A prediction of how much larger the shard stores on this node will eventually grow due to ongoing peer recoveries, restoring snapshots, and similar activities. A value of `-1b` indicates that this is not available. `reserved_in_bytes`:: (integer) A prediction, in bytes, of how much larger the shard stores on this node will eventually grow due to ongoing peer recoveries, restoring snapshots, and similar activities. A value of `-1` indicates that this is not available. ======= `indexing`:: (object) Contains statistics about indexing operations for the node. + .Properties of `indexing` [%collapsible%open] ======= `index_total`:: (integer) Total number of indexing operations. `index_time`:: (<>) Total time spent performing indexing operations. `index_time_in_millis`:: (integer) Total time in milliseconds spent performing indexing operations. `index_current`:: (integer) Number of indexing operations currently running. `index_failed`:: (integer) Number of failed indexing operations. `delete_total`:: (integer) Total number of deletion operations. `delete_time`:: (<>) Time spent performing deletion operations. `delete_time_in_millis`:: (integer) Time in milliseconds spent performing deletion operations. `delete_current`:: (integer) Number of deletion operations currently running. `noop_update_total`:: (integer) Total number of noop operations. `is_throttled`:: (Boolean) Number of times operations were throttled. `throttle_time`:: (<>) Total time spent throttling operations. `throttle_time_in_millis`:: (integer) Total time in milliseconds spent throttling operations. ======= `get`:: (object) Contains statistics about get operations for the node. + .Properties of `get` [%collapsible%open] ======= `total`:: (integer) Total number of get operations. `getTime`:: (<>) Time spent performing get operations. `time_in_millis`:: (integer) Time in milliseconds spent performing get operations. `exists_total`:: (integer) Total number of successful get operations. `exists_time`:: (<>) Time spent performing successful get operations. `exists_time_in_millis`:: (integer) Time in milliseconds spent performing successful get operations. `missing_total`:: (integer) Total number of failed get operations. `missing_time`:: (<>) Time spent performing failed get operations. `missing_time_in_millis`:: (integer) Time in milliseconds spent performing failed get operations. `current`:: (integer) Number of get operations currently running. ======= `search`:: (object) Contains statistics about search operations for the node. + .Properties of `search` [%collapsible%open] ======= `open_contexts`:: (integer) Number of open search contexts. `query_total`:: (integer) Total number of query operations. `query_time`:: (<>) Time spent performing query operations. `query_time_in_millis`:: (integer) Time in milliseconds spent performing query operations. `query_current`:: (integer) Number of query operations currently running. `fetch_total`:: (integer) Total number of fetch operations. `fetch_time`:: (<>) Time spent performing fetch operations. `fetch_time_in_millis`:: (integer) Time in milliseconds spent performing fetch operations. `fetch_current`:: (integer) Number of fetch operations currently running. `scroll_total`:: (integer) Total number of scroll operations. `scroll_time`:: (<>) Time spent performing scroll operations. `scroll_time_in_millis`:: (integer) Time in milliseconds spent performing scroll operations. `scroll_current`:: (integer) Number of scroll operations currently running. `suggest_total`:: (integer) Total number of suggest operations. `suggest_time`:: (<>) Time spent performing suggest operations. `suggest_time_in_millis`:: (integer) Time in milliseconds spent performing suggest operations. `suggest_current`:: (integer) Number of suggest operations currently running. ======= `merges`:: (object) Contains statistics about merge operations for the node. + .Properties of `merges` [%collapsible%open] ======= `current`:: (integer) Number of merge operations currently running. `current_docs`:: (integer) Number of document merges currently running. `current_size`:: (<>) Memory used performing current document merges. `current_size_in_bytes`:: (integer) Memory, in bytes, used performing current document merges. `total`:: (integer) Total number of merge operations. `total_time`:: (<>) Total time spent performing merge operations. `total_time_in_millis`:: (integer) Total time in milliseconds spent performing merge operations. `total_docs`:: (integer) Total number of merged documents. `total_size`:: (<>) Total size of document merges. `total_size_in_bytes`:: (integer) Total size of document merges in bytes. `total_stopped_time`:: (<>) Total time spent stopping merge operations. `total_stopped_time_in_millis`:: (integer) Total time in milliseconds spent stopping merge operations. `total_throttled_time`:: (<>) Total time spent throttling merge operations. `total_throttled_time_in_millis`:: (integer) Total time in milliseconds spent throttling merge operations. `total_auto_throttle`:: (<>) Size of automatically throttled merge operations. `total_auto_throttle_in_bytes`:: (integer) Size, in bytes, of automatically throttled merge operations. ======= `refresh`:: (object) Contains statistics about refresh operations for the node. + .Properties of `refresh` [%collapsible%open] ======= `total`:: (integer) Total number of refresh operations. `total_time`:: (<>) Total time spent performing refresh operations. `total_time_in_millis`:: (integer) Total time in milliseconds spent performing refresh operations. `external_total`:: (integer) Total number of external refresh operations. `external_total_time`:: (<>) Total time spent performing external operations. `external_total_time_in_millis`:: (integer) Total time in milliseconds spent performing external operations. `listeners`:: (integer) Number of refresh listeners. ======= `flush`:: (object) Contains statistics about flush operations for the node. + .Properties of `flush` [%collapsible%open] ======= `total`:: (integer) Number of flush operations. `periodic`:: (integer) Number of flush periodic operations. `total_time`:: (<>) Total time spent performing flush operations. `total_time_in_millis`:: (integer) Total time in milliseconds spent performing flush operations. ======= `warmer`:: (object) Contains statistics about index warming operations for the node. + .Properties of `warmer` [%collapsible%open] ======= `current`:: (integer) Number of active index warmers. `total`:: (integer) Total number of index warmers. `total_time`:: (<>) Total time spent performing index warming operations. `total_time_in_millis`:: (integer) Total time in milliseconds spent performing index warming operations. ======= `query_cache`:: (object) Contains statistics about the query cache across all shards assigned to the node. + .Properties of `query_cache` [%collapsible%open] ======= `memory_size`:: (<>) Total amount of memory used for the query cache across all shards assigned to the node. `memory_size_in_bytes`:: (integer) Total amount of memory, in bytes, used for the query cache across all shards assigned to the node. `total_count`:: (integer) Total count of hits, misses, and cached queries in the query cache. `hit_count`:: (integer) Number of query cache hits. `miss_count`:: (integer) Number of query cache misses. `cache_size`:: (integer) Size, in bytes, of the query cache. `cache_count`:: (integer) Count of queries in the query cache. `evictions`:: (integer) Number of query cache evictions. ======= `fielddata`:: (object) Contains statistics about the field data cache across all shards assigned to the node. + .Properties of `fielddata` [%collapsible%open] ======= `memory_size`:: (<>) Total amount of memory used for the field data cache across all shards assigned to the node. `memory_size_in_bytes`:: (integer) Total amount of memory, in bytes, used for the field data cache across all shards assigned to the node. `evictions`:: (integer) Number of fielddata evictions. ======= `completion`:: (object) Contains statistics about completions across all shards assigned to the node. + .Properties of `completion` [%collapsible%open] ======= `size`:: (<>) Total amount of memory used for completion across all shards assigned to the node. `size_in_bytes`:: (integer) Total amount of memory, in bytes, used for completion across all shards assigned to the node. ======= `segments`:: (object) Contains statistics about segments across all shards assigned to the node. + .Properties of `segments` [%collapsible%open] ======= `count`:: (integer) Number of segments. `memory`:: (<>) Total amount of memory used for segments across all shards assigned to the node. `memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for segments across all shards assigned to the node. `terms_memory`:: (<>) Total amount of memory used for terms across all shards assigned to the node. `terms_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for terms across all shards assigned to the node. `stored_fields_memory`:: (<>) Total amount of memory used for stored fields across all shards assigned to the node. `stored_fields_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for stored fields across all shards assigned to the node. `term_vectors_memory`:: (<>) Total amount of memory used for term vectors across all shards assigned to the node. `term_vectors_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for term vectors across all shards assigned to the node. `norms_memory`:: (<>) Total amount of memory used for normalization factors across all shards assigned to the node. `norms_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for normalization factors across all shards assigned to the node. `points_memory`:: (<>) Total amount of memory used for points across all shards assigned to the node. `points_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for points across all shards assigned to the node. `doc_values_memory`:: (<>) Total amount of memory used for doc values across all shards assigned to the node. `doc_values_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for doc values across all shards assigned to the node. `index_writer_memory`:: (<>) Total amount of memory used by all index writers across all shards assigned to the node. `index_writer_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used by all index writers across all shards assigned to the node. `version_map_memory`:: (<>) Total amount of memory used by all version maps across all shards assigned to the node. `version_map_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used by all version maps across all shards assigned to the node. `fixed_bit_set`:: (<>) Total amount of memory used by fixed bit sets across all shards assigned to the node. + Fixed bit sets are used for nested object field types and type filters for <> fields. `fixed_bit_set_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used by fixed bit sets across all shards assigned to the node. + Fixed bit sets are used for nested object field types and type filters for <> fields. `max_unsafe_auto_id_timestamp`:: (integer) Time of the most recently retried indexing request. Recorded in milliseconds since the {wikipedia}/Unix_time[Unix Epoch]. `file_sizes`:: (object) Contains statistics about the size of the segment file. + .Properties of `file_sizes` [%collapsible%open] ======== `size`:: (<>) Size of the segment file. `size_in_bytes`:: (integer) Size, in bytes, of the segment file. `description`:: (string) Description of the segment file. ======== ======= `translog`:: (object) Contains statistics about transaction log operations for the node. + .Properties of `translog` [%collapsible%open] ======= `operations`:: (integer) Number of transaction log operations. `size`:: (<>) Size of the transaction log. `size_in_bytes`:: (integer) Size, in bytes, of the transaction log. `uncommitted_operations`:: (integer) Number of uncommitted transaction log operations. `uncommitted_size`:: (<>) Size of uncommitted transaction log operations. `uncommitted_size_in_bytes`:: (integer) Size, in bytes, of uncommitted transaction log operations. `earliest_last_modified_age`:: (integer) Earliest last modified age for the transaction log. ======= `request_cache`:: (object) Contains statistics about the request cache across all shards assigned to the node. + .Properties of `request_cache` [%collapsible%open] ======= `memory_size`:: (<>) Memory used by the request cache. `memory_size_in_bytes`:: (integer) Memory, in bytes, used by the request cache. `evictions`:: (integer) Number of request cache operations. `hit_count`:: (integer) Number of request cache hits. `miss_count`:: (integer) Number of request cache misses. ======= `recovery`:: (object) Contains statistics about recovery operations for the node. + .Properties of `recovery` [%collapsible%open] ======= `current_as_source`:: (integer) Number of recoveries that used an index shard as a source. `current_as_target`:: (integer) Number of recoveries that used an index shard as a target. `throttle_time`:: (<>) Time by which recovery operations were delayed due to throttling. `throttle_time_in_millis`:: (integer) Time in milliseconds recovery operations were delayed due to throttling. ======= ====== [[cluster-nodes-stats-api-response-body-os]] `os`:: (object) Contains statistics about the operating system for the node. + .Properties of `os` [%collapsible%open] ====== `timestamp`:: (integer) Last time the operating system statistics were refreshed. Recorded in milliseconds since the {wikipedia}/Unix_time[Unix Epoch]. `cpu`:: (object) Contains statistics about CPU usage for the node. + .Properties of `cpu` [%collapsible%open] ======= `percent`:: (integer) Recent CPU usage for the whole system, or `-1` if not supported. `load_average`:: (object) Contains statistics about load averages on the system. + .Properties of `load_average` [%collapsible%open] ======== `1m`:: (float) One-minute load average on the system (field is not present if one-minute load average is not available). `5m`:: (float) Five-minute load average on the system (field is not present if five-minute load average is not available). `15m`:: (float) Fifteen-minute load average on the system (field is not present if fifteen-minute load average is not available). ======== ======= `mem`:: (object) Contains statistics about memory usage for the node. + .Properties of `mem` [%collapsible%open] ======= `total`:: (<>) Total amount of physical memory. `total_in_bytes`:: (integer) Total amount of physical memory in bytes. `free`:: (<>) Amount of free physical memory. `free_in_bytes`:: (integer) Amount of free physical memory in bytes. `used`:: (<>) Amount of used physical memory. `used_in_bytes`:: (integer) Amount of used physical memory in bytes. `free_percent`:: (integer) Percentage of free memory. `used_percent`:: (integer) Percentage of used memory. ======= `swap`:: (object) Contains statistics about swap space for the node. + .Properties of `swap` [%collapsible%open] ======= `total`:: (<>) Total amount of swap space. `total_in_bytes`:: (integer) Total amount of swap space in bytes. `free`:: (<>) Amount of free swap space. `free_in_bytes`:: (integer) Amount of free swap space in bytes. `used`:: (<>) Amount of used swap space. `used_in_bytes`:: (integer) Amount of used swap space in bytes. ======= `cgroup` (Linux only):: (object) Contains cgroup statistics for the node. + NOTE: For the cgroup stats to be visible, cgroups must be compiled into the kernel, the `cpu` and `cpuacct` cgroup subsystems must be configured and stats must be readable from `/sys/fs/cgroup/cpu` and `/sys/fs/cgroup/cpuacct`. + .Properties of `cgroup` [%collapsible%open] ======= `cpuacct` (Linux only):: (object) Contains statistics about `cpuacct` control group for the node. + .Properties of `cpuacct` [%collapsible%open] ======== `control_group` (Linux only):: (string) The `cpuacct` control group to which the {es} process belongs. `usage_nanos` (Linux only):: (integer) The total CPU time (in nanoseconds) consumed by all tasks in the same cgroup as the {es} process. ======== `cpu` (Linux only):: (object) Contains statistics about `cpu` control group for the node. + .Properties of `cpu` [%collapsible%open] ======== `control_group` (Linux only):: (string) The `cpu` control group to which the {es} process belongs. `cfs_period_micros` (Linux only):: (integer) The period of time (in microseconds) for how regularly all tasks in the same cgroup as the {es} process should have their access to CPU resources reallocated. `cfs_quota_micros` (Linux only):: (integer) The total amount of time (in microseconds) for which all tasks in the same cgroup as the {es} process can run during one period `cfs_period_micros`. `stat` (Linux only):: (object) Contains CPU statistics for the node. + .Properties of `stat` [%collapsible%open] ========= `number_of_elapsed_periods` (Linux only):: (integer) The number of reporting periods (as specified by `cfs_period_micros`) that have elapsed. `number_of_times_throttled` (Linux only):: (integer) The number of times all tasks in the same cgroup as the {es} process have been throttled. `time_throttled_nanos` (Linux only):: (integer) The total amount of time (in nanoseconds) for which all tasks in the same cgroup as the {es} process have been throttled. ========= ======== `memory` (Linux only):: (object) Contains statistics about the `memory` control group for the node. + .Properties of `memory` [%collapsible%open] ======== `control_group` (Linux only):: (string) The `memory` control group to which the {es} process belongs. `limit_in_bytes` (Linux only):: (string) The maximum amount of user memory (including file cache) allowed for all tasks in the same cgroup as the {es} process. This value can be too big to store in a `long`, so is returned as a string so that the value returned can exactly match what the underlying operating system interface returns. Any value that is too large to parse into a `long` almost certainly means no limit has been set for the cgroup. `usage_in_bytes` (Linux only):: (string) The total current memory usage by processes in the cgroup (in bytes) by all tasks in the same cgroup as the {es} process. This value is stored as a string for consistency with `limit_in_bytes`. ======== ======= ====== [[cluster-nodes-stats-api-response-body-process]] `process`:: (object) Contains process statistics for the node. + .Properties of `process` [%collapsible%open] ====== `timestamp`:: (integer) Last time the statistics were refreshed. Recorded in milliseconds since the {wikipedia}/Unix_time[Unix Epoch]. `open_file_descriptors`:: (integer) Number of opened file descriptors associated with the current or `-1` if not supported. `max_file_descriptors`:: (integer) Maximum number of file descriptors allowed on the system, or `-1` if not supported. `cpu`:: (object) Contains CPU statistics for the node. + .Properties of `cpu` [%collapsible%open] ======= `percent`:: (integer) CPU usage in percent, or `-1` if not known at the time the stats are computed. `total`:: (<>) CPU time used by the process on which the Java virtual machine is running. `total_in_millis`:: (integer) CPU time (in milliseconds) used by the process on which the Java virtual machine is running, or `-1` if not supported. ======= `mem`:: (object) Contains virtual memory statistics for the node. + .Properties of `mem` [%collapsible%open] ======= `total_virtual`:: (<>) Size of virtual memory that is guaranteed to be available to the running process. `total_virtual_in_bytes`:: (integer) Size in bytes of virtual memory that is guaranteed to be available to the running process. ======= ====== [[cluster-nodes-stats-api-response-body-jvm]] `jvm`:: (object) Contains Java Virtual Machine (JVM) statistics for the node. + .Properties of `jvm` [%collapsible%open] ====== `timestamp`:: (integer) Last time JVM statistics were refreshed. `uptime`:: (<>) JVM uptime. `uptime_in_millis`:: (integer) JVM uptime in milliseconds. `mem`:: (object) Contains JVM memory usage statistics for the node. + .Properties of `mem` [%collapsible%open] ======= `heap_used`:: (<>) Memory currently in use by the heap. `heap_used_in_bytes`:: (integer) Memory, in bytes, currently in use by the heap. `heap_used_percent`:: (integer) Percentage of memory currently in use by the heap. `heap_committed`:: (<>) Amount of memory available for use by the heap. `heap_committed_in_bytes`:: (integer) Amount of memory, in bytes, available for use by the heap. `heap_max`:: (<>) Maximum amount of memory available for use by the heap. `heap_max_in_bytes`:: (integer) Maximum amount of memory, in bytes, available for use by the heap. `non_heap_used`:: (<>) Non-heap memory used. `non_heap_used_in_bytes`:: (integer) Non-heap memory used, in bytes. `non_heap_committed`:: (<>) Amount of non-heap memory available. `non_heap_committed_in_bytes`:: (integer) Amount of non-heap memory available, in bytes. `pools`:: (object) Contains statistics about heap memory usage for the node. + .Properties of `pools` [%collapsible%open] ======== `young`:: (object) Contains statistics about memory usage by the young generation heap for the node. + .Properties of `young` [%collapsible%open] ========= `used`:: (<>) Memory used by the young generation heap. `used_in_bytes`:: (integer) Memory, in bytes, used by the young generation heap. `max`:: (<>) Maximum amount of memory available for use by the young generation heap. `max_in_bytes`:: (integer) Maximum amount of memory, in bytes, available for use by the young generation heap. `peak_used`:: (<>) Largest amount of memory historically used by the young generation heap. `peak_used_in_bytes`:: (integer) Largest amount of memory, in bytes, historically used by the young generation heap. `peak_max`:: (<>) Largest amount of memory historically used by the young generation heap. `peak_max_in_bytes`:: (integer) Largest amount of memory, in bytes, historically used by the young generation heap. ========= `survivor`:: (object) Contains statistics about memory usage by the survivor space for the node. + .Properties of `survivor` [%collapsible%open] ========= `used`:: (<>) Memory used by the survivor space. `used_in_bytes`:: (integer) Memory, in bytes, used by the survivor space. `max`:: (<>) Maximum amount of memory available for use by the survivor space. `max_in_bytes`:: (integer) Maximum amount of memory, in bytes, available for use by the survivor space. `peak_used`:: (<>) Largest amount of memory historically used by the survivor space. `peak_used_in_bytes`:: (integer) Largest amount of memory, in bytes, historically used by the survivor space. `peak_max`:: (<>) Largest amount of memory historically used by the survivor space. `peak_max_in_bytes`:: (integer) Largest amount of memory, in bytes, historically used by the survivor space. ========= `old`:: (object) Contains statistics about memory usage by the old generation heap for the node. + .Properties of `old` [%collapsible%open] ========= `used`:: (<>) Memory used by the old generation heap. `used_in_bytes`:: (integer) Memory, in bytes, used by the old generation heap. `max`:: (<>) Maximum amount of memory available for use by the old generation heap. `max_in_bytes`:: (integer) Maximum amount of memory, in bytes, available for use by the old generation heap. `peak_used`:: (<>) Largest amount of memory historically used by the old generation heap. `peak_used_in_bytes`:: (integer) Largest amount of memory, in bytes, historically used by the old generation heap. `peak_max`:: (<>) Highest memory limit historically available for use by the old generation heap. `peak_max_in_bytes`:: (integer) Highest memory limit, in bytes, historically available for use by the old generation heap. ========= ======== ======= `threads`:: (object) Contains statistics about JVM thread usage for the node. + .Properties of `threads` [%collapsible%open] ======= `count`:: (integer) Number of active threads in use by JVM. `peak_count`:: (integer) Highest number of threads used by JVM. ======= `gc`:: (object) Contains statistics about JVM garbage collectors for the node. + .Properties of `gc` [%collapsible%open] ======= `collectors`:: (object) Contains statistics about JVM garbage collectors for the node. + .Properties of `collectors` [%collapsible%open] ======== `young`:: (object) Contains statistics about JVM garbage collectors that collect young generation objects for the node. + .Properties of `young` [%collapsible%open] ========= `collection_count`:: (integer) Number of JVM garbage collectors that collect young generation objects. `collection_time`:: (<>) Total time spent by JVM collecting young generation objects. `collection_time_in_millis`:: (integer) Total time in milliseconds spent by JVM collecting young generation objects. ========= `old`:: (object) Contains statistics about JVM garbage collectors that collect old generation objects for the node. + .Properties of `old` [%collapsible%open] ========= `collection_count`:: (integer) Number of JVM garbage collectors that collect old generation objects. `collection_time`:: (<>) Total time spent by JVM collecting old generation objects. `collection_time_in_millis`:: (integer) Total time in milliseconds spent by JVM collecting old generation objects. ========= ======== ======= `buffer_pools`:: (object) Contains statistics about JVM buffer pools for the node. + .Properties of `buffer_pools` [%collapsible%open] ======= `mapped`:: (object) Contains statistics about mapped JVM buffer pools for the node. + .Properties of `mapped` [%collapsible%open] ======== `count`:: (integer) Number of mapped buffer pools. `used`:: (<>) Size of mapped buffer pools. `used_in_bytes`:: (integer) Size, in bytes, of mapped buffer pools. `total_capacity`:: (<>) Total capacity of mapped buffer pools. `total_capacity_in_bytes`:: (integer) Total capacity, in bytes, of mapped buffer pools. ======== `direct`:: (object) Contains statistics about direct JVM buffer pools for the node. + .Properties of `direct` [%collapsible%open] ======== `count`:: (integer) Number of direct buffer pools. `used`:: (<>) Size of direct buffer pools. `used_in_bytes`:: (integer) Size, in bytes, of direct buffer pools. `total_capacity`:: (<>) Total capacity of direct buffer pools. `total_capacity_in_bytes`:: (integer) Total capacity, in bytes, of direct buffer pools. ======== ======= `classes`:: (object) Contains statistics about classes loaded by JVM for the node. + .Properties of `classes` [%collapsible%open] ======= `current_loaded_count`:: (integer) Number of classes currently loaded by JVM. `total_loaded_count`:: (integer) Total number of classes loaded since the JVM started. `total_unloaded_count`:: (integer) Total number of classes unloaded since the JVM started. ======= ====== [[cluster-nodes-stats-api-response-body-threadpool]] `thread_pool`:: (object) Contains thread pool statistics for the node + .Properties of `thread_pool` [%collapsible%open] ====== ``:: (object) Contains statistics about the thread pool for the node. + .Properties of `` [%collapsible%open] ======= `threads`:: (integer) Number of threads in the thread pool. `queue`:: (integer) Number of tasks in queue for the thread pool. `active`:: (integer) Number of active threads in the thread pool. `rejected`:: (integer) Number of tasks rejected by the thread pool executor. `largest`:: (integer) Highest number of active threads in the thread pool. `completed`:: (integer) Number of tasks completed by the thread pool executor. ======= ====== [[cluster-nodes-stats-api-response-body-fs]] `fs`:: (object) Contains file store statistics for the node. + .Properties of `fs` [%collapsible%open] ====== `timestamp`:: (integer) Last time the file stores statistics were refreshed. Recorded in milliseconds since the {wikipedia}/Unix_time[Unix Epoch]. `total`:: (object) Contains statistics for all file stores of the node. + .Properties of `total` [%collapsible%open] ======= `total`:: (<>) Total size of all file stores. `total_in_bytes`:: (integer) Total size (in bytes) of all file stores. `free`:: (<>) Total unallocated disk space in all file stores. `free_in_bytes`:: (integer) Total number of unallocated bytes in all file stores. `available`:: (<>) Total disk space available to this Java virtual machine on all file stores. Depending on OS or process level restrictions, this might appear less than `free`. This is the actual amount of free disk space the {es} node can utilise. `available_in_bytes`:: (integer) Total number of bytes available to this Java virtual machine on all file stores. Depending on OS or process level restrictions, this might appear less than `free_in_bytes`. This is the actual amount of free disk space the {es} node can utilise. ======= [[cluster-nodes-stats-fs-data]] `data`:: (array of objects) List of all file stores. + .Properties of `data` [%collapsible%open] ======= `path`:: (string) Path to the file store. `mount`:: (string) Mount point of the file store (ex: /dev/sda2). `type`:: (string) Type of the file store (ex: ext4). `total`:: (<>) Total size of the file store. `total_in_bytes`:: (integer) Total size (in bytes) of the file store. `free`:: (<>) Total amount of unallocated disk space in the file store. `free_in_bytes`:: (integer) Total number of unallocated bytes in the file store. `available`:: (<>) Total amount of disk space available to this Java virtual machine on this file store. `available_in_bytes`:: (integer) Total number of bytes available to this Java virtual machine on this file store. ======= `io_stats` (Linux only):: (objects) Contains I/O statistics for the node. + .Properties of `io_stats` [%collapsible%open] ======= `devices` (Linux only):: (array) Array of disk metrics for each device that is backing an {es} data path. These disk metrics are probed periodically and averages between the last probe and the current probe are computed. + .Properties of `devices` [%collapsible%open] ======== `device_name` (Linux only):: (string) The Linux device name. `operations` (Linux only):: (integer) The total number of read and write operations for the device completed since starting {es}. `read_operations` (Linux only):: (integer) The total number of read operations for the device completed since starting {es}. `write_operations` (Linux only):: (integer) The total number of write operations for the device completed since starting {es}. `read_kilobytes` (Linux only):: (integer) The total number of kilobytes read for the device since starting {es}. `write_kilobytes` (Linux only):: (integer) The total number of kilobytes written for the device since starting {es}. ======== `operations` (Linux only):: (integer) The total number of read and write operations across all devices used by {es} completed since starting {es}. `read_operations` (Linux only):: (integer) The total number of read operations for across all devices used by {es} completed since starting {es}. `write_operations` (Linux only):: (integer) The total number of write operations across all devices used by {es} completed since starting {es}. `read_kilobytes` (Linux only):: (integer) The total number of kilobytes read across all devices used by {es} since starting {es}. `write_kilobytes` (Linux only):: (integer) The total number of kilobytes written across all devices used by {es} since starting {es}. ======= ====== [[cluster-nodes-stats-api-response-body-transport]] `transport`:: (object) Contains transport statistics for the node. + .Properties of `transport` [%collapsible%open] ====== `server_open`:: (integer) Current number of inbound TCP connections used for internal communication between nodes. `total_outbound_connections`:: (integer) The cumulative number of outbound transport connections that this node has opened since it started. Each transport connection may comprise multiple TCP connections but is only counted once in this statistic. Transport connections are typically <> so this statistic should remain constant in a stable cluster. `rx_count`:: (integer) Total number of RX (receive) packets received by the node during internal cluster communication. `rx_size`:: (<>) Size of RX packets received by the node during internal cluster communication. `rx_size_in_bytes`:: (integer) Size, in bytes, of RX packets received by the node during internal cluster communication. `tx_count`:: (integer) Total number of TX (transmit) packets sent by the node during internal cluster communication. `tx_size`:: (<>) Size of TX packets sent by the node during internal cluster communication. `tx_size_in_bytes`:: (integer) Size, in bytes, of TX packets sent by the node during internal cluster communication. ====== [[cluster-nodes-stats-api-response-body-http]] `http`:: (object) Contains http statistics for the node. + .Properties of `http` [%collapsible%open] ====== `current_open`:: (integer) Current number of open HTTP connections for the node. `total_opened`:: (integer) Total number of HTTP connections opened for the node. ====== [[cluster-nodes-stats-api-response-body-breakers]] `breakers`:: (object) Contains circuit breaker statistics for the node. + .Properties of `breakers` [%collapsible%open] ====== ``:: (object) Contains statistics for the circuit breaker. + .Properties of `` [%collapsible%open] ======= `limit_size_in_bytes`:: (integer) Memory limit, in bytes, for the circuit breaker. `limit_size`:: (<>) Memory limit for the circuit breaker. `estimated_size_in_bytes`:: (integer) Estimated memory used, in bytes, for the operation. `estimated_size`:: (<>) Estimated memory used for the operation. `overhead`:: (float) A constant that all estimates for the circuit breaker are multiplied with to calculate a final estimate. `tripped`:: (integer) Total number of times the circuit breaker has been triggered and prevented an out of memory error. ======= ====== [[cluster-nodes-stats-api-response-body-script]] `script`:: (object) Contains script statistics for the node. + .Properties of `script` [%collapsible%open] ====== `compilations`:: (integer) Total number of inline script compilations performed by the node. `cache_evictions`:: (integer) Total number of times the script cache has evicted old data. `compilation_limit_triggered`:: (integer) Total number of times the <> circuit breaker has limited inline script compilations. ====== [[cluster-nodes-stats-api-response-body-discovery]] `discovery`:: (object) Contains node discovery statistics for the node. + .Properties of `discovery` [%collapsible%open] ====== `cluster_state_queue`:: (object) Contains statistics for the cluster state queue of the node. + .Properties of `cluster_state_queue` [%collapsible%open] ======= `total`:: (integer) Total number of cluster states in queue. `pending`:: (integer) Number of pending cluster states in queue. `committed`:: (integer) Number of committed cluster states in queue. ======= `published_cluster_states`:: (object) Contains statistics for the published cluster states of the node. + .Properties of `published_cluster_states` [%collapsible%open] ======= `full_states`:: (integer) Number of published cluster states. `incompatible_diffs`:: (integer) Number of incompatible differences between published cluster states. `compatible_diffs`:: (integer) Number of compatible differences between published cluster states. ======= ====== [[cluster-nodes-stats-api-response-body-ingest]] `ingest`:: (object) Contains ingest statistics for the node. + .Properties of `ingest` [%collapsible%open] ====== `total`:: (object) Contains statistics about ingest operations for the node. + .Properties of `total` [%collapsible%open] ======= `count`:: (integer) Total number of documents ingested during the lifetime of this node. `time`:: (<>) Total time spent preprocessing ingest documents during the lifetime of this node. `time_in_millis`:: (integer) Total time, in milliseconds, spent preprocessing ingest documents during the lifetime of this node. `current`:: (integer) Total number of documents currently being ingested. `failed`:: (integer) Total number of failed ingest operations during the lifetime of this node. ======= `pipelines`:: (object) Contains statistics about ingest pipelines for the node. + .Properties of `pipelines` [%collapsible%open] ======= ``:: (object) Contains statistics about the ingest pipeline. + .Properties of `` [%collapsible%open] ======== `count`:: (integer) Number of documents preprocessed by the ingest pipeline. `time`:: (<>) Total time spent preprocessing documents in the ingest pipeline. `time_in_millis`:: (integer) Total time, in milliseconds, spent preprocessing documents in the ingest pipeline. `failed`:: (integer) Total number of failed operations for the ingest pipeline. `processors`:: (array of objects) Contains statistics for the ingest processors for the ingest pipeline. + .Properties of `processors` [%collapsible%open] ========= ``:: (object) Contains statistics for the ingest processor. + .Properties of `` [%collapsible%open] ========== `count`:: (integer) Number of documents transformed by the processor. `time`:: (<>) Time spent by the processor transforming documents. `time_in_millis`:: (integer) Time, in milliseconds, spent by the processor transforming documents. `current`:: (integer) Number of documents currently being transformed by the processor. `failed`:: (integer) Number of failed operations for the processor. ========== ========= ======== ======= ====== [[cluster-nodes-stats-api-response-body-indexing-pressure]] `indexing_pressure`:: (object) Contains <> statistics for the node. + .Properties of `indexing_pressure` [%collapsible%open] ====== `memory`:: (object) Contains statistics for memory consumption from indexing load. + .Properties of `` [%collapsible%open] ======= `current`:: (object) Contains statistics for current indexing load. + .Properties of `` [%collapsible%open] ======== `combined_coordinating_and_primary`:: (<>) Memory consumed by indexing requests in the coordinating or primary stage. This value is not the sum of coordinating and primary as a node can reuse the coordinating memory if the primary stage is executed locally. `combined_coordinating_and_primary_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the coordinating or primary stage. This value is not the sum of coordinating and primary as a node can reuse the coordinating memory if the primary stage is executed locally. `coordinating`:: (<>) Memory consumed by indexing requests in the coordinating stage. `coordinating_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the coordinating stage. `primary`:: (<>) Memory consumed by indexing requests in the primary stage. `primary_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the primary stage. `replica`:: (<>) Memory consumed by indexing requests in the replica stage. `replica_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the replica stage. `all`:: (<>) Memory consumed by indexing requests in the coordinating, primary, or replica stage. `all_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the coordinating, primary, or replica stage. ======== `total`:: (object) Contains statistics for the cumulative indexing load since the node started. + .Properties of `` [%collapsible%open] ======== `combined_coordinating_and_primary`:: (<>) Memory consumed by indexing requests in the coordinating or primary stage. This value is not the sum of coordinating and primary as a node can reuse the coordinating memory if the primary stage is executed locally. `combined_coordinating_and_primary_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the coordinating or primary stage. This value is not the sum of coordinating and primary as a node can reuse the coordinating memory if the primary stage is executed locally. `coordinating`:: (<>) Memory consumed by indexing requests in the coordinating stage. `coordinating_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the coordinating stage. `primary`:: (<>) Memory consumed by indexing requests in the primary stage. `primary_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the primary stage. `replica`:: (<>) Memory consumed by indexing requests in the replica stage. `replica_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the replica stage. `all`:: (<>) Memory consumed by indexing requests in the coordinating, primary, or replica stage. `all_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the coordinating, primary, or replica stage. `coordinating_rejections`:: (integer) Number of indexing requests rejected in the coordinating stage. `primary_rejections`:: (integer) Number of indexing requests rejected in the primary stage. `replica_rejections`:: (integer) Number of indexing requests rejected in the replica stage. ======== `limit`:: (<>) Configured memory limit for the indexing requests. Replica requests have an automatic limit that is 1.5x this value. `limit_in_bytes`:: (integer) Configured memory limit, in bytes, for the indexing requests. Replica requests have an automatic limit that is 1.5x this value. ======= ====== [[cluster-nodes-stats-api-response-body-adaptive-selection]] `adaptive_selection`:: (object) Contains adaptive selection statistics for the node. + .Properties of `adaptive_selection` [%collapsible%open] ====== `outgoing_searches`:: (integer) The number of outstanding search requests from the node these stats are for to the keyed node. `avg_queue_size`:: (integer) The exponentially weighted moving average queue size of search requests on the keyed node. `avg_service_time`:: (<>) The exponentially weighted moving average service time of search requests on the keyed node. `avg_service_time_ns`:: (integer) The exponentially weighted moving average service time, in nanoseconds, of search requests on the keyed node. `avg_response_time`:: (<>) The exponentially weighted moving average response time of search requests on the keyed node. `avg_response_time_ns`:: (integer) The exponentially weighted moving average response time, in nanoseconds, of search requests on the keyed node. `rank`:: (string) The rank of this node; used for shard selection when routing search requests. ====== ===== ==== [[cluster-nodes-stats-api-example]] ==== {api-examples-title} [source,console] -------------------------------------------------- # return just indices GET /_nodes/stats/indices # return just os and process GET /_nodes/stats/os,process # return just process for node with IP address 10.0.0.1 GET /_nodes/10.0.0.1/stats/process -------------------------------------------------- All stats can be explicitly requested via `/_nodes/stats/_all` or `/_nodes/stats?metric=_all`. You can get information about indices stats on `node`, `indices`, or `shards` level. [source,console] -------------------------------------------------- # Fielddata summarized by node GET /_nodes/stats/indices/fielddata?fields=field1,field2 # Fielddata summarized by node and index GET /_nodes/stats/indices/fielddata?level=indices&fields=field1,field2 # Fielddata summarized by node, index, and shard GET /_nodes/stats/indices/fielddata?level=shards&fields=field1,field2 # You can use wildcards for field names GET /_nodes/stats/indices/fielddata?fields=field* -------------------------------------------------- You can get statistics about search groups for searches executed on this node. [source,console] -------------------------------------------------- # All groups with all stats GET /_nodes/stats?groups=_all # Some groups from just the indices stats GET /_nodes/stats/indices?groups=foo,bar -------------------------------------------------- [[cluster-nodes-stats-ingest-ex]] ===== Retrieve ingest statistics only To return only ingest-related node statistics, set the `` path parameter to `ingest` and use the <> query parameter. [source,console] -------------------------------------------------- GET /_nodes/stats/ingest?filter_path=nodes.*.ingest -------------------------------------------------- You can use the `metric` and `filter_path` query parameters to get the same response. [source,console] -------------------------------------------------- GET /_nodes/stats?metric=ingest&filter_path=nodes.*.ingest -------------------------------------------------- To further refine the response, change the `filter_path` value. For example, the following request only returns ingest pipeline statistics. [source,console] -------------------------------------------------- GET /_nodes/stats?metric=ingest&filter_path=nodes.*.ingest.pipelines -------------------------------------------------- ",12278,True,2572.0395518376185,median "[[box-component]] = Box Component :docTitle: Box :artifactId: camel-box :description: Upload, download and manage files, folders, groups, collaborations, etc. on box.com. :since: 2.14 :supportLevel: Stable :component-header: Both producer and consumer are supported include::{cq-version}@camel-quarkus:ROOT:partial$reference/components/box.adoc[opts=optional] *Since Camel {since}* *{component-header}* The Box component provides access to all of the Box.com APIs accessible using https://github.com/box/box-java-sdk/[https://github.com/box/box-java-sdk]. It allows producing messages to upload and download files, create, edit, and manage folders, etc. It also supports APIs that allow polling for updates to user accounts and even changes to enterprise accounts, etc. Box.com requires the use of OAuth2.0 for all client application authentication. In order to use camel-box with your account, you'll need to create a new application within Box.com at https://developer.box.com/[https://developer.box.com]. The Box application's client id and secret will allow access to Box APIs which require a current user. A user access token is generated and managed by the API for an end user. Maven users will need to add the following dependency to their pom.xml for this component: [source,xml] ---- org.apache.camel camel-box ${camel-version} ---- == Connection Authentication Types The Box component supports three different types of authenticated connections. === Standard Authentication *Standard Authentication* uses the *OAuth 2.0 three-legged authentication process* to authenticate its connections with Box.com. This type of authentication enables Box *managed users* and *external users* to access, edit, and save their Box content through the Box component. === App Enterprise Authentication *App Enterprise Authentication* uses the *OAuth 2.0 with JSON Web Tokens (JWT)* to authenticate its connections as a *Service Account* for a *Box Application*. This type of authentication enables a service account to access, edit, and save the Box content of its *Box Application* through the Box component. === App User Authentication *App User Authentication* uses the *OAuth 2.0 with JSON Web Tokens (JWT)* to authenticate its connections as an *App User* for a *Box Application*. This type of authentication enables app users to access, edit, and save their Box content in its *Box Application* through the Box component. == Box Options // component options: START The Box component supports 19 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *clientId* (common) | Box application client ID | | String | *configuration* (common) | To use the shared configuration | | BoxConfiguration | *enterpriseId* (common) | The enterprise ID to use for an App Enterprise. | | String | *userId* (common) | The user ID to use for an App User. | | String | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *autowiredEnabled* (advanced) | Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc. | true | boolean | *httpParams* (advanced) | Custom HTTP params for settings like proxy host | | Map | *authenticationType* (authentication) | The type of authentication for connection. Types of Authentication: STANDARD_AUTHENTICATION - OAuth 2.0 (3-legged) SERVER_AUTHENTICATION - OAuth 2.0 with JSON Web Tokens | APP_USER_AUTHENTICATION | String | *accessTokenCache* (security) | Custom Access Token Cache for storing and retrieving access tokens. | | IAccessTokenCache | *clientSecret* (security) | Box application client secret | | String | *encryptionAlgorithm* (security) | The type of encryption algorithm for JWT. Supported Algorithms: RSA_SHA_256 RSA_SHA_384 RSA_SHA_512. There are 3 enums and the value can be one of: RSA_SHA_256, RSA_SHA_384, RSA_SHA_512 | RSA_SHA_256 | EncryptionAlgorithm | *maxCacheEntries* (security) | The maximum number of access tokens in cache. | 100 | int | *privateKeyFile* (security) | The private key for generating the JWT signature. | | String | *privateKeyPassword* (security) | The password for the private key. | | String | *publicKeyId* (security) | The ID for public key for validating the JWT signature. | | String | *sslContextParameters* (security) | To configure security using SSLContextParameters. | | SSLContextParameters | *userName* (security) | Box user name, MUST be provided | | String | *userPassword* (security) | Box user password, MUST be provided if authSecureStorage is not set, or returns null on first call | | String |=== // component options: END // endpoint options: START The Box endpoint is configured using URI syntax: ---- box:apiName/methodName ---- with the following path and query parameters: === Path Parameters (2 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *apiName* | *Required* What kind of operation to perform. There are 10 enums and the value can be one of: COLLABORATIONS, COMMENTS, EVENT_LOGS, FILES, FOLDERS, GROUPS, EVENTS, SEARCH, TASKS, USERS | | BoxApiName | *methodName* | *Required* What sub operation to use for the selected operation | | String |=== === Query Parameters (19 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *clientId* (common) | Box application client ID | | String | *enterpriseId* (common) | The enterprise ID to use for an App Enterprise. | | String | *inBody* (common) | Sets the name of a parameter to be passed in the exchange In Body | | String | *userId* (common) | The user ID to use for an App User. | | String | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | | ExceptionHandler | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. There are 3 enums and the value can be one of: InOnly, InOut, InOptionalOut | | ExchangePattern | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *httpParams* (advanced) | Custom HTTP params for settings like proxy host | | Map | *authenticationType* (authentication) | The type of authentication for connection. Types of Authentication: STANDARD_AUTHENTICATION - OAuth 2.0 (3-legged) SERVER_AUTHENTICATION - OAuth 2.0 with JSON Web Tokens | APP_USER_AUTHENTICATION | String | *accessTokenCache* (security) | Custom Access Token Cache for storing and retrieving access tokens. | | IAccessTokenCache | *clientSecret* (security) | Box application client secret | | String | *encryptionAlgorithm* (security) | The type of encryption algorithm for JWT. Supported Algorithms: RSA_SHA_256 RSA_SHA_384 RSA_SHA_512. There are 3 enums and the value can be one of: RSA_SHA_256, RSA_SHA_384, RSA_SHA_512 | RSA_SHA_256 | EncryptionAlgorithm | *maxCacheEntries* (security) | The maximum number of access tokens in cache. | 100 | int | *privateKeyFile* (security) | The private key for generating the JWT signature. | | String | *privateKeyPassword* (security) | The password for the private key. | | String | *publicKeyId* (security) | The ID for public key for validating the JWT signature. | | String | *sslContextParameters* (security) | To configure security using SSLContextParameters. | | SSLContextParameters | *userName* (security) | Box user name, MUST be provided | | String | *userPassword* (security) | Box user password, MUST be provided if authSecureStorage is not set, or returns null on first call | | String |=== === API Parameters (10 APIs): The Box endpoint is an API based component and has additional parameters based on which API name and API method is used. The API name and API method is located in the endpoint URI as the apiName/methodName path parameters: ---- box:apiName/methodName ---- There are 10 API names as listed in the table below: [width=""100%"",cols=""2,2,6"",options=""header""] |=== | API Name | Type | Description | *collaborations* | Producer | Provides operations to manage Box collaborations | *comments* | Producer | Provides operations to manage Box comments | *event-logs* | Producer | Provides operations to read Box enterprise (admin) event logs | *events* | Consumer | Provides operations to manage Box events | *files* | Producer | Provides operations to manage Box files | *folders* | Producer | Provides operations to manage Box folders | *groups* | Producer | Provides operations to manage Box groups | *search* | Producer | Provides operations to manage Box searches | *tasks* | Producer | Provides operations to manage Box tasks | *users* | Producer | Provides operations to manage Box users |=== Each API is documented in the following sections to come. ==== API: collaborations *Only producer is supported* The collaborations API has 6 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.BoxCollaboration addFolderCollaboration(String folderId, com.box.sdk.BoxCollaborator collaborator, com.box.sdk.BoxCollaboration.Role role); com.box.sdk.BoxCollaboration addFolderCollaborationByEmail(String folderId, String email, com.box.sdk.BoxCollaboration.Role role); void deleteCollaboration(String collaborationId); com.box.sdk.BoxCollaboration.Info getCollaborationInfo(String collaborationId); java.util.Collection getFolderCollaborations(String folderId); com.box.sdk.BoxCollaboration updateCollaborationInfo(String collaborationId, com.box.sdk.BoxCollaboration.Info info); ---- The collaborations API is defined in the syntax as follows: ---- box:collaborations/methodName?[parameters] ---- The 6 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *addFolderCollaboration* | add | Add a collaboration to this folder | *addFolderCollaborationByEmail* | addByEmail | Add a collaboration to this folder | *deleteCollaboration* | delete | Delete collaboration | *getCollaborationInfo* | info | Get collaboration information | *getFolderCollaborations* | collaborations | Get information about all of the collaborations for folder | *updateCollaborationInfo* | updateInfo | Update collaboration information |=== The collaborations API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | addFolderCollaboration | *collaborator* | The collaborator to add | BoxCollaborator | addFolderCollaboration | *folderId* | The id of folder to add collaboration to | String | addFolderCollaboration | *role* | The role of the collaborator | Role | addFolderCollaborationByEmail | *email* | The email address of the collaborator to add | String | addFolderCollaborationByEmail | *folderId* | The id of folder to add collaboration to | String | addFolderCollaborationByEmail | *role* | The role of the collaborator | Role | deleteCollaboration | *collaborationId* | The id of comment to change | String | getCollaborationInfo | *collaborationId* | The id of collaboration | String | getFolderCollaborations | *folderId* | The id of folder to get collaborations information on | String | updateCollaborationInfo | *collaborationId* | The id of collaboration | String | updateCollaborationInfo | *info* | Collaboration information to update | Info |=== In addition to the parameters above, the collaborations API can also use from the 19 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: comments *Only producer is supported* The comments API has 6 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.BoxFile addFileComment(String fileId, String message); com.box.sdk.BoxComment changeCommentMessage(String commentId, String message); void deleteComment(String commentId); com.box.sdk.BoxComment.Info getCommentInfo(String commentId); java.util.List getFileComments(String fileId); com.box.sdk.BoxComment replyToComment(String commentId, String message); ---- The comments API is defined in the syntax as follows: ---- box:comments/methodName?[parameters] ---- The 6 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *addFileComment* | add | Add comment to file | *changeCommentMessage* | updateMessage | Change comment message | *deleteComment* | delete | Delete comment | *getCommentInfo* | info | Get comment information | *getFileComments* | comments | Get a list of any comments on this file | *replyToComment* | reply | Reply to a comment |=== The comments API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | addFileComment | *fileId* | The id of file | String | addFileComment | *message* | The comment's message | String | changeCommentMessage | *commentId* | The id of comment to change | String | changeCommentMessage | *message* | The new message for the comment | String | deleteComment | *commentId* | The id of comment to delete | String | getCommentInfo | *commentId* | The id of comment | String | getFileComments | *fileId* | The id of file | String | replyToComment | *commentId* | The id of comment to reply to | String | replyToComment | *message* | The message for the reply | String |=== In addition to the parameters above, the comments API can also use from the 19 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: event-logs *Only producer is supported* The event-logs API has 1 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- java.util.List getEnterpriseEvents(String position, java.util.Date after, java.util.Date before, com.box.sdk.BoxEvent.Type[] types); ---- The event-logs API is defined in the syntax as follows: ---- box:event-logs/methodName?[parameters] ---- The 1 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *getEnterpriseEvents* | events | Create an event stream with optional starting initial position and add listener that will be notified when an event is received |=== The event-logs API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | getEnterpriseEvents | *after* | The lower bound on the timestamp of the events returned | Date | getEnterpriseEvents | *before* | The upper bound on the timestamp of the events returned | Date | getEnterpriseEvents | *position* | *Optional* The starting position of the event stream. May be null in which case all events within bounds returned. | String | getEnterpriseEvents | *types* | *Optional* An optional list of event types to filter by | Type[] |=== In addition to the parameters above, the event-logs API can also use from the 19 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: events *Only consumer is supported* The events API has 1 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- void listen(com.box.sdk.EventListener listener, Long startingPosition); ---- The events API is defined in the syntax as follows: ---- box:events/methodName?[parameters] ---- The 1 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *listen* | | Create an event stream with optional starting initial position and add listener that will be notified when an event is received |=== The events API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | listen | *startingPosition* | *Optional* The starting position of the event stream | Long |=== In addition to the parameters above, the events API can also use from the 19 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: files *Only producer is supported* The files API has 22 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- void checkUpload(String fileName, String parentFolderId, Long size); com.box.sdk.BoxFile copyFile(String fileId, String destinationFolderId, String newName); com.box.sdk.Metadata createFileMetadata(String fileId, com.box.sdk.Metadata metadata, String typeName); com.box.sdk.BoxSharedLink createFileSharedLink(String fileId, com.box.sdk.BoxSharedLink.Access access, java.util.Date unshareDate, com.box.sdk.BoxSharedLink.Permissions permissions); void deleteFile(String fileId); void deleteFileMetadata(String fileId); void deleteFileVersion(String fileId, Integer version); java.io.OutputStream downloadFile(String fileId, java.io.OutputStream output, Long rangeStart, Long rangeEnd, com.box.sdk.ProgressListener listener); java.io.OutputStream downloadPreviousFileVersion(String fileId, Integer version, java.io.OutputStream output, com.box.sdk.ProgressListener listener); java.net.URL getDownloadURL(String fileId); com.box.sdk.BoxFile.Info getFileInfo(String fileId, String[] fields); com.box.sdk.Metadata getFileMetadata(String fileId, String typeName); java.net.URL getFilePreviewLink(String fileId); byte[] getFileThumbnail(String fileId, com.box.sdk.BoxFile.ThumbnailFileType fileType, Integer minWidth, Integer minHeight, Integer maxWidth, Integer maxHeight); java.util.Collection getFileVersions(String fileId); com.box.sdk.BoxFile moveFile(String fileId, String destinationFolderId, String newName); com.box.sdk.BoxFileVersion promoteFileVersion(String fileId, Integer version); com.box.sdk.BoxFile renameFile(String fileId, String newFileName); com.box.sdk.BoxFile updateFileInfo(String fileId, com.box.sdk.BoxFile.Info info); com.box.sdk.Metadata updateFileMetadata(String fileId, com.box.sdk.Metadata metadata); com.box.sdk.BoxFile uploadFile(String parentFolderId, java.io.InputStream content, String fileName, java.util.Date created, java.util.Date modified, Long size, Boolean check, com.box.sdk.ProgressListener listener); com.box.sdk.BoxFile uploadNewFileVersion(String fileId, java.io.InputStream fileContent, java.util.Date modified, Long fileSize, com.box.sdk.ProgressListener listener); ---- The files API is defined in the syntax as follows: ---- box:files/methodName?[parameters] ---- The 22 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *checkUpload* | canUpload | Does a pre-verification before upload, to check if the filename already exists or if there is permission to upload | *copyFile* | copy | Copy file to destination folder while optionally giving it a new name | *createFileMetadata* | createMetadata | Create metadata for file in either the global properties template or the specified template type | *createFileSharedLink* | link | Create a shared link to file | *deleteFile* | delete | Delete the file | *deleteFileMetadata* | deleteMetadata | Delete the file properties metadata | *deleteFileVersion* | deleteVersion | Delete a file version | *downloadFile* | download | Download a file | *downloadPreviousFileVersion* | downloadVersion | Download a previous version of file | *getDownloadURL* | url | Get an expiring URL for downloading a file directly from Box | *getFileInfo* | info | Get file information | *getFileMetadata* | metadata | Gets the file properties metadata | *getFilePreviewLink* | | Get an expiring URL for creating an embedded preview session | *getFileThumbnail* | thumbnail | Retrieves a thumbnail, or smaller image representation, of this file | *getFileVersions* | versions | Get any previous versions of file | *moveFile* | move | Move file to destination folder while optionally giving it a new name | *promoteFileVersion* | promoteVersion | Promote a previous version of file | *renameFile* | rename | Rename file giving it the name newName | *updateFileInfo* | updateInfo | Update file information | *updateFileMetadata* | updateMetadata | Update the file properties metadata | *uploadFile* | upload | Upload a new file to parent folder | *uploadNewFileVersion* | uploadVersion | Upload a new version of file |=== The files API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | checkUpload | *fileName* | The name to give the uploaded file | String | checkUpload | *parentFolderId* | The id of parent folder | String | checkUpload | *size* | *Optional* The size of the file's content used for monitoring the upload's progress | Long | copyFile | *destinationFolderId* | The id of the destination folder | String | copyFile | *fileId* | The id of file to copy | String | copyFile | *newName* | *Optional* The new name for copied file; if newName is null, the copied file has same name as the original. | String | createFileMetadata | *fileId* | The id of the file to create metadata for | String | createFileMetadata | *metadata* | The new metadata values | Metadata | createFileMetadata | *typeName* | *Optional* The metadata template type name; if null the global properties template type is used. | String | createFileSharedLink | *access* | The access level of the shared link | Access | createFileSharedLink | *fileId* | The id of the file to create shared link on | String | createFileSharedLink | *permissions* | *Optional* The permissions of the created link; if permissions is null then the created shared link is create with default permissions. | Permissions | createFileSharedLink | *unshareDate* | *Optional* The date and time at which time the created shared link will expire; if unsharedDate is null then a non-expiring link is created. | Date | deleteFile | *fileId* | The id of file to delete | String | deleteFileMetadata | *fileId* | The id of file to delete | String | deleteFileVersion | *fileId* | The id of file with version to delete | String | deleteFileVersion | *version* | The version of file to delete; initial version of file has value of 0, second version of file is 1 and so on. | Integer | downloadFile | *fileId* | The id of file | String | downloadFile | *listener* | *Optional* A listener for monitoring the download's progress; if null the download's progress will not be monitored. | ProgressListener | downloadFile | *output* | The stream to which the file contents will be written | OutputStream | downloadFile | *rangeEnd* | *Optional* The byte offset in file at which to stop the download; if null the entire contents of file will be downloaded. | Long | downloadFile | *rangeStart* | *Optional* The byte offset in file at which to start the download; if null the entire contents of file will be downloaded. | Long | downloadPreviousFileVersion | *fileId* | The id of file | String | downloadPreviousFileVersion | *listener* | *Optional* A listener for monitoring the download's progress; if null the download's progress will not be monitored. | ProgressListener | downloadPreviousFileVersion | *output* | The stream to which the version contents will be written | OutputStream | downloadPreviousFileVersion | *version* | The version of file to download; initial version of file has value of 0, second version of file is 1 and so on. | Integer | getDownloadURL | *fileId* | The id of file | String | getFileInfo | *fields* | *Optional* The information fields to retrieve; if null all information fields are retrieved. | String[] | getFileInfo | *fileId* | The id of file | String | getFileMetadata | *fileId* | The id of the file to retrieve metadata for | String | getFileMetadata | *typeName* | *Optional* The metadata template type name; if null the global properties template type is used. | String | getFilePreviewLink | *fileId* | The id of the file to get preview link on | String | getFileThumbnail | *fileId* | The id of the file to get thumbnail | String | getFileThumbnail | *fileType* | Either PNG of JPG | ThumbnailFileType | getFileThumbnail | *maxHeight* | Maximum height | Integer | getFileThumbnail | *maxWidth* | Maximum width | Integer | getFileThumbnail | *minHeight* | Minimum height | Integer | getFileThumbnail | *minWidth* | Minimum width | Integer | getFileVersions | *fileId* | The id of file | String | moveFile | *destinationFolderId* | The id of the destination folder | String | moveFile | *fileId* | The id of file to move | String | moveFile | *newName* | *Optional* The new name of moved file; if newName is null, the moved file has same name as the original. | String | promoteFileVersion | *fileId* | The id of file | String | promoteFileVersion | *version* | The version of file to promote; initial version of file has value of 0, second version of file is 1 and so on. | Integer | renameFile | *fileId* | The id of file to rename | String | renameFile | *newFileName* | The new name of file | String | updateFileInfo | *fileId* | The id of file to update | String | updateFileInfo | *info* | The updated information | Info | updateFileMetadata | *fileId* | The id of file to delete | String | updateFileMetadata | *metadata* | The new metadata values | Metadata | uploadFile | *check* | *Optional* If the file name is already used, call the uploadNewVersion instead. | Boolean | uploadFile | *content* | A stream containing contents of the file to upload | InputStream | uploadFile | *created* | *Optional* The content created date that will be given to the uploaded file | Date | uploadFile | *fileName* | The name to give the uploaded file | String | uploadFile | *listener* | *Optional* A listener for monitoring the upload's progress | ProgressListener | uploadFile | *modified* | *Optional* The content modified date that will be given to the uploaded file | Date | uploadFile | *parentFolderId* | The id of parent folder | String | uploadFile | *size* | *Optional* The size of the file's content used for monitoring the upload's progress | Long | uploadNewFileVersion | *fileContent* | A stream containing contents of the file to upload | InputStream | uploadNewFileVersion | *fileId* | The id of file | String | uploadNewFileVersion | *fileSize* | *Optional* The size of the file's content used for monitoring the upload's progress | Long | uploadNewFileVersion | *listener* | *Optional* A listener for monitoring the upload's progress | ProgressListener | uploadNewFileVersion | *modified* | *Optional* The content modified date that will be given to the uploaded file | Date |=== In addition to the parameters above, the files API can also use from the 19 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: folders *Only producer is supported* The folders API has 10 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.BoxFolder copyFolder(String folderId, String destinationFolderId, String newName); com.box.sdk.BoxFolder createFolder(String parentFolderId, String folderName); com.box.sdk.BoxFolder createFolder(String parentFolderId, String[] path); com.box.sdk.BoxSharedLink createFolderSharedLink(String folderId, com.box.sdk.BoxSharedLink.Access access, java.util.Date unshareDate, com.box.sdk.BoxSharedLink.Permissions permissions); void deleteFolder(String folderId); com.box.sdk.BoxFolder getFolder(String[] path); com.box.sdk.BoxFolder.Info getFolderInfo(String folderId, String[] fields); java.util.Collection getFolderItems(String folderId, Long offset, Long limit, String[] fields); com.box.sdk.BoxFolder moveFolder(String folderId, String destinationFolderId, String newName); com.box.sdk.BoxFolder renameFolder(String folderId, String newFolderName); com.box.sdk.BoxFolder updateFolderInfo(String folderId, com.box.sdk.BoxFolder.Info info); ---- The folders API is defined in the syntax as follows: ---- box:folders/methodName?[parameters] ---- The 10 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *copyFolder* | copy | Copy folder to destination folder while optionally giving it a new name | *createFolder* | create | Create a folder specified by path from parent folder with given parentFolderId, creating intermediate directories as required | *createFolderSharedLink* | link | Create a shared link to folder | *deleteFolder* | delete | Delete folder | *getFolder* | folder | Return the Box folder referenced by path | *getFolderInfo* | info | Get folder information | *getFolderItems* | items | Returns a specific range of child items in folder and specifies which fields of each item to retrieve | *moveFolder* | move | Move folder to destination folder while optionally giving it a new name | *renameFolder* | rename | Rename folder giving it the name newName | *updateFolderInfo* | updateInfo | Update folder information |=== The folders API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | copyFolder | *destinationFolderId* | The id of the destination folder | String | copyFolder | *folderId* | The id of folder to copy | String | copyFolder | *newName* | *Optional* The new name for copied folder; if newName is null, the copied folder has same name as the original. | String | createFolder | *folderName* | The name of created folder | String | createFolder | *parentFolderId* | The id of parent folder | String | createFolder | *path* | Sequence of Box folder names from parent folder to returned folder | String[] | createFolderSharedLink | *access* | The access level of the shared link | Access | createFolderSharedLink | *folderId* | The id of folder to create shared link on | String | createFolderSharedLink | *permissions* | The permissions of the created link; if permissions is null then the created shared link is create with default permissions. | Permissions | createFolderSharedLink | *unshareDate* | The date and time at which time the created shared link will expire; if unsharedDate is null then a non-expiring link is created. | Date | deleteFolder | *folderId* | The id of folder to delete | String | getFolder | *path* | Sequence of Box folder names from root folder to returned folder | String[] | getFolderInfo | *fields* | *Optional* The information fields to retrieve; if null all information fields are retrieved. | String[] | getFolderInfo | *folderId* | The id of folder | String | getFolderItems | *fields* | *Optional* The item fields to retrieve for each child item; if null all item fields are retrieved. | String[] | getFolderItems | *folderId* | The id of folder | String | getFolderItems | *limit* | *Optional* The maximum number of children to retrieve after the offset; if null all child items are retrieved. | Long | getFolderItems | *offset* | *Optional* The index of first child item to retrieve; if null all child items are retrieved. | Long | moveFolder | *destinationFolderId* | The id of the destination folder | String | moveFolder | *folderId* | The id of folder to move | String | moveFolder | *newName* | *Optional* The new name of moved folder; if newName is null, the moved folder has same name as the original. | String | renameFolder | *folderId* | The id of folder to rename | String | renameFolder | *newFolderName* | The new name of folder | String | updateFolderInfo | *folderId* | The id of folder to update | String | updateFolderInfo | *info* | The updated information | Info |=== In addition to the parameters above, the folders API can also use from the 19 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: groups *Only producer is supported* The groups API has 9 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.BoxGroupMembership addGroupMembership(String groupId, String userId, com.box.sdk.BoxGroupMembership.Role role); com.box.sdk.BoxGroup createGroup(String name, String provenance, String externalSyncIdentifier, String description, String invitabilityLevel, String memberViewabilityLevel); void deleteGroup(String groupId); void deleteGroupMembership(String groupMembershipId); com.box.sdk.BoxGroup.Info getGroupInfo(String groupId); com.box.sdk.BoxGroupMembership.Info getGroupMembershipInfo(String groupMembershipId); java.util.Collection getGroupMemberships(String groupId); com.box.sdk.BoxGroup updateGroupInfo(String groupId, com.box.sdk.BoxGroup.Info groupInfo); com.box.sdk.BoxGroupMembership updateGroupMembershipInfo(String groupMembershipId, com.box.sdk.BoxGroupMembership.Info info); ---- The groups API is defined in the syntax as follows: ---- box:groups/methodName?[parameters] ---- The 9 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *addGroupMembership* | addMembership | Add a member to group with the specified role | *createGroup* | create | Create a new group with a specified name and optional additional parameters | *deleteGroup* | delete | Delete group | *deleteGroupMembership* | deleteMembership | Delete group membership | *getGroupInfo* | info | Get group information | *getGroupMembershipInfo* | membershipInfo | Get group membership information | *getGroupMemberships* | memberships | Get information about all of the group memberships for this group | *updateGroupInfo* | | Update group information | *updateGroupMembershipInfo* | updateMembershipInfo | Update group membership information |=== The groups API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | addGroupMembership | *groupId* | The id of group | String | addGroupMembership | *role* | *Optional* The role of the user in this group. Can be null to assign the default role. | Role | addGroupMembership | *userId* | The id of user to be added to group | String | createGroup | *description* | *Optional* The description of the new group | String | createGroup | *externalSyncIdentifier* | *Optional* The external_sync_identifier of the new group | String | createGroup | *invitabilityLevel* | *Optional* The invitibility_level of the new group | String | createGroup | *memberViewabilityLevel* | *Optional* The member_viewability_level of the new group | String | createGroup | *name* | The name of the new group | String | createGroup | *provenance* | *Optional* The provenance of the new group | String | deleteGroup | *groupId* | The id of group to delete | String | deleteGroupMembership | *groupMembershipId* | The id of group membership to delete | String | getGroupInfo | *groupId* | The id of group | String | getGroupMembershipInfo | *groupMembershipId* | The id of group membership | String | getGroupMemberships | *groupId* | The id of group | String | updateGroupInfo | *groupId* | The id of group to update | String | updateGroupInfo | *groupInfo* | The updated information | Info | updateGroupMembershipInfo | *groupMembershipId* | The id of group membership to update | String | updateGroupMembershipInfo | *info* | The updated information | Info |=== In addition to the parameters above, the groups API can also use from the 19 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: search *Only producer is supported* The search API has 1 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- java.util.Collection searchFolder(String folderId, String query); ---- The search API is defined in the syntax as follows: ---- box:search/methodName?[parameters] ---- The 1 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *searchFolder* | search | Search folder and all descendant folders using the given query |=== The search API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | searchFolder | *folderId* | The id of folder searched | String | searchFolder | *query* | The search query | String |=== In addition to the parameters above, the search API can also use from the 19 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: tasks *Only producer is supported* The tasks API has 9 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.BoxTask addAssignmentToTask(String taskId, com.box.sdk.BoxUser assignTo); com.box.sdk.BoxTask addFileTask(String fileId, com.box.sdk.BoxTask.Action action, java.util.Date dueAt, String message); void deleteTask(String taskId); void deleteTaskAssignment(String taskAssignmentId); java.util.List getFileTasks(String fileId); com.box.sdk.BoxTaskAssignment.Info getTaskAssignmentInfo(String taskAssignmentId); java.util.List getTaskAssignments(String taskId); com.box.sdk.BoxTask.Info getTaskInfo(String taskId); com.box.sdk.BoxTask updateTaskInfo(String taskId, com.box.sdk.BoxTask.Info info); ---- The tasks API is defined in the syntax as follows: ---- box:tasks/methodName?[parameters] ---- The 9 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *addAssignmentToTask* | addAssignment | Add assignment for task | *addFileTask* | add | Add task to file | *deleteTask* | delete | Delete task | *deleteTaskAssignment* | deleteAssignment | Delete task assignment | *getFileTasks* | tasks | Get a list of any tasks on file | *getTaskAssignmentInfo* | assignmentInfo | Get task assignment information | *getTaskAssignments* | assignments | Get a list of any assignments for task | *getTaskInfo* | info | Get task information | *updateTaskInfo* | updateInfo | Update task information |=== The tasks API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | addAssignmentToTask | *assignTo* | The user to assign to task | BoxUser | addAssignmentToTask | *taskId* | The id of task to add assignment for | String | addFileTask | *action* | The action the task assignee will be prompted to do | Action | addFileTask | *dueAt* | The day at which this task is due | Date | addFileTask | *fileId* | The id of file to add task to | String | addFileTask | *message* | *Optional* An optional message to include with the task | String | deleteTask | *taskId* | The id of task to delete | String | deleteTaskAssignment | *taskAssignmentId* | The id of task assignment to delete | String | getFileTasks | *fileId* | The id of file | String | getTaskAssignmentInfo | *taskAssignmentId* | The id of task assignment | String | getTaskAssignments | *taskId* | The id of task | String | getTaskInfo | *taskId* | The id of task | String | updateTaskInfo | *info* | The updated information | Info | updateTaskInfo | *taskId* | The id of task | String |=== In addition to the parameters above, the tasks API can also use from the 19 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: users *Only producer is supported* The users API has 10 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.EmailAlias addUserEmailAlias(String userId, String email); com.box.sdk.BoxUser createAppUser(String name, com.box.sdk.CreateUserParams params); com.box.sdk.BoxUser createEnterpriseUser(String login, String name, com.box.sdk.CreateUserParams params); void deleteUser(String userId, boolean notifyUser, boolean force); void deleteUserEmailAlias(String userId, String emailAliasId); java.util.List getAllEnterpriseOrExternalUsers(String filterTerm, String[] fields); java.util.Collection getUserEmailAlias(String userId); com.box.sdk.BoxUser.Info getUserInfo(String userId); com.box.sdk.BoxFolder.Info moveFolderToUser(String userId, String sourceUserId); com.box.sdk.BoxUser updateUserInfo(String userId, com.box.sdk.BoxUser.Info info); ---- The users API is defined in the syntax as follows: ---- box:users/methodName?[parameters] ---- The 10 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *addUserEmailAlias* | addEmailAlias | Add a new email alias to user's account | *createAppUser* | create | Provision a new app user in an enterprise with additional user information using Box Developer Edition | *createEnterpriseUser* | create | Provision a new user in an enterprise with additional user information | *deleteUser* | delete | Delete user from an enterprise account | *deleteUserEmailAlias* | deleteEmailAlias | Delete an email alias from user's account | *getAllEnterpriseOrExternalUsers* | users | Get any managed users that match the filter term as well as any external users that match the filter term | *getUserEmailAlias* | emailAlias | Get a collection of all the email aliases for user | *getUserInfo* | info | Get user information | *moveFolderToUser* | | Move root folder for specified user to current user | *updateUserInfo* | updateInfo | Update user information |=== The users API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | addUserEmailAlias | *email* | The email address to add as an alias | String | addUserEmailAlias | *userId* | The id of user | String | createAppUser | *name* | The name of the user | String | createAppUser | *params* | *Optional* Additional user information | CreateUserParams | createEnterpriseUser | *login* | The email address the user will use to login | String | createEnterpriseUser | *name* | The name of the user | String | createEnterpriseUser | *params* | *Optional* Additional user information | CreateUserParams | deleteUser | *force* | Whether or not this user should be deleted even if they still own files | Boolean | deleteUser | *notifyUser* | Whether or not to send an email notification to the user that their account has been deleted | Boolean | deleteUser | *userId* | The id of user to delete | String | deleteUserEmailAlias | *emailAliasId* | The id of the email alias to delete | String | deleteUserEmailAlias | *userId* | The id of user | String | getAllEnterpriseOrExternalUsers | *fields* | *Optional* The fields to retrieve. Leave this out for the standard fields. | String[] | getAllEnterpriseOrExternalUsers | *filterTerm* | *Optional* The filter term to lookup users by (login for external, login or name for managed); if null all managed users are returned. | String | getUserEmailAlias | *userId* | The id of user | String | getUserInfo | *userId* | The id of user | String | moveFolderToUser | *sourceUserId* | The user id of the user whose files will be the source for this operation | String | moveFolderToUser | *userId* | The id of user | String | updateUserInfo | *info* | The updated information | Info | updateUserInfo | *userId* | The id of user to update | String |=== In addition to the parameters above, the users API can also use from the 19 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. // endpoint options: END == Samples The following route uploads new files to the user's root folder: [source,java] ---- from(""file:..."") .to(""box://files/upload/inBody=fileUploadRequest""); ---- The following route polls user's account for updates: [source,java] ---- from(""box://events/listen?startingPosition=-1"") .to(""bean:blah""); ---- The following route uses a producer with dynamic header options. The *fileId* property has the Box file id and the *output* property has the output stream of the file contents, so they are assigned to the *CamelBox.fileId* header and *CamelBox.output* header respectively as follows: [source,java] ---- from(""direct:foo"") .setHeader(""CamelBox.fileId"", header(""fileId"")) .setHeader(""CamelBox.output"", header(""output"")) .to(""box://files/download"") .to(""file://...""); ---- === More information See more details at the Box API reference: https://developer.box.com/reference include::{page-component-version}@camel-spring-boot::page$box-starter.adoc[] ",12296,True,2584.5840731776234,median "/* * Copyright (C) 2018 The Android Open Source Project * * 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. */ /* * JS BINDINGS DESIGN * ------------------ * * The purpose of filament-js is to offer a first-class JavaScript interface to the core Filament * classes: Engine, Renderer, Texture, etc. * * Emscripten offers two ways to binding JavaScript to C++: embind and WebIDL. We chose embind. * * With WebIDL, we would need to author WebIDL files and generate opaque C++ from the IDL, which * complicates the build process and ultimately results in the same amount of code. Using embind is * more direct and controllable. * * For nested classes, we use $ as the separator character because embind does not support nested * classes and it would transform dot separators into $ anyway. By using $, we at least make * this explicit rather than mysterious. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define STBI_NO_STDIO #define STBI_ONLY_PNG #include using namespace emscripten; using namespace filament; using namespace filamesh; using namespace geometry; using namespace gltfio; using namespace image; // Many methods require a thin layer of C++ glue which is elegantly expressed with a lambda. // However, passing a bare lambda into embind's daisy chain requires a cast to a function pointer. #define EMBIND_LAMBDA(retval, arglist, impl) (retval (*) arglist) [] arglist impl // Builder functions that return ""this"" have verbose binding declarations, this macro reduces // the amount of boilerplate. #define BUILDER_FUNCTION(name, btype, arglist, impl) \\ function(name, EMBIND_LAMBDA(btype*, arglist, impl), allow_raw_pointers()) // Explicit instantiation of emscripten::internal::raw_destructor is required for binding classes // that have non-public destructors. #define BIND(T) template<> void raw_destructor(T* ptr) {} namespace emscripten { namespace internal { BIND(Animator) BIND(AssetLoader) BIND(Camera) BIND(Engine) BIND(FilamentAsset) BIND(IndexBuffer) BIND(IndirectLight) BIND(LightManager) BIND(Material) BIND(MaterialInstance) BIND(RenderableManager) BIND(Renderer) BIND(RenderTarget) BIND(Scene) BIND(Skybox) BIND(SwapChain) BIND(Texture) BIND(TransformManager) BIND(utils::Entity) BIND(utils::EntityManager) BIND(VertexBuffer) BIND(View) } } #undef BIND namespace { // For convenience, declare terse private aliases to nested types. This lets us avoid extremely // verbose binding declarations. using IblBuilder = IndirectLight::Builder; using IndexBuilder = IndexBuffer::Builder; using LightBuilder = LightManager::Builder; using MatBuilder = Material::Builder; using RenderableBuilder = RenderableManager::Builder; using RenderTargetBuilder = RenderTarget::Builder; using SkyBuilder = Skybox::Builder; using SurfaceBuilder = SurfaceOrientation::Builder; using TexBuilder = Texture::Builder; using VertexBuilder = VertexBuffer::Builder; // We avoid directly exposing backend::BufferDescriptor because embind does not support move // semantics and void* doesn't make sense to JavaScript anyway. This little wrapper class is exposed // to JavaScript as ""driver$BufferDescriptor"", but clients will normally use our ""Filament.Buffer"" // helper function (implemented in utilities.js) struct BufferDescriptor { BufferDescriptor() {} // This form is used when JavaScript sends a buffer into WASM. BufferDescriptor(val arrdata) { auto byteLength = arrdata[""byteLength""].as(); this->bd.reset(new backend::BufferDescriptor(malloc(byteLength), byteLength, [](void* buffer, size_t size, void* user) { free(buffer); })); } // This form is used when WASM needs to return a buffer to JavaScript. BufferDescriptor(uint8_t* data, uint32_t size) { this->bd.reset(new backend::BufferDescriptor(data, size)); } val getBytes() { unsigned char *byteBuffer = (unsigned char*) bd->buffer; size_t bufferLength = bd->size; return val(typed_memory_view(bufferLength, byteBuffer)); } // In order to match its JavaScript counterpart, the Buffer wrapper needs to use reference // counting, and the easiest way to achieve that is with shared_ptr. std::shared_ptr bd; }; // Exposed to JavaScript as ""driver$PixelBufferDescriptor"", but clients will normally use the // PixelBuffer or CompressedPixelBuffer helper functions (implemented in utilities.js) struct PixelBufferDescriptor { PixelBufferDescriptor(val arrdata, backend::PixelDataFormat fmt, backend::PixelDataType dtype) { auto byteLength = arrdata[""byteLength""].as(); this->pbd.reset(new backend::PixelBufferDescriptor(malloc(byteLength), byteLength, fmt, dtype, [](void* buffer, size_t size, void* user) { free(buffer); })); } // Note that embind allows overloading based on number of arguments, but not on types. // It's fine to have two constructors but they can't both have the same number of arguments. PixelBufferDescriptor(val arrdata, backend::CompressedPixelDataType cdtype, int imageSize, bool compressed) { auto byteLength = arrdata[""byteLength""].as(); assert(compressed == true); // For compressed cubemaps, the image size should be one-sixth the size of the entire blob. assert(imageSize == byteLength || imageSize == byteLength / 6); this->pbd.reset(new backend::PixelBufferDescriptor(malloc(byteLength), byteLength, cdtype, imageSize, [](void* buffer, size_t size, void* user) { free(buffer); })); } val getBytes() { unsigned char *byteBuffer = (unsigned char*) pbd->buffer; size_t bufferLength = pbd->size; return val(typed_memory_view(bufferLength, byteBuffer)); }; // In order to match its JavaScript counterpart, the Buffer wrapper needs to use reference // counting, and the easiest way to achieve that is with shared_ptr. std::shared_ptr pbd; }; // Small structure whose sole purpose is to return decoded image data to JavaScript. struct DecodedPng { int width; int height; int encoded_ncomp; int decoded_ncomp; BufferDescriptor decoded_data; }; // JavaScript clients should call [createTextureFromPng] rather than calling this directly. DecodedPng decodePng(BufferDescriptor encoded_data, int requested_ncomp) { DecodedPng result; stbi_uc* decoded_data = stbi_load_from_memory( (stbi_uc const *) encoded_data.bd->buffer, encoded_data.bd->size, &result.width, &result.height, &result.encoded_ncomp, requested_ncomp); const uint32_t decoded_size = result.width * result.height * requested_ncomp; result.decoded_data = BufferDescriptor(decoded_data, decoded_size); result.decoded_data.bd->setCallback([](void* buffer, size_t size, void* user) { stbi_image_free(buffer); }); result.decoded_ncomp = requested_ncomp; return result; } } // anonymous namespace EMSCRIPTEN_BINDINGS(jsbindings) { // MATH TYPES // ---------- // Individual JavaScript objects for math types would be too heavy, so instead we simply accept // array-like data using embind's ""value_array"" feature. We do not expose all our math functions // under the assumption that JS clients will use glMatrix or something similar for math. value_array(""float2"") .element(&filament::math::float2::x) .element(&filament::math::float2::y); value_array(""float3"") .element(&filament::math::float3::x) .element(&filament::math::float3::y) .element(&filament::math::float3::z); value_array(""float4"") .element(&filament::math::float4::x) .element(&filament::math::float4::y) .element(&filament::math::float4::z) .element(&filament::math::float4::w); value_array(""quat"") .element(&filament::math::quat::x) .element(&filament::math::quat::y) .element(&filament::math::quat::z) .element(&filament::math::quat::w); value_array(""Viewport"") .element(&Viewport::left) .element(&Viewport::bottom) .element(&Viewport::width) .element(&Viewport::height); value_array(""KtxBlobIndex"") .element(&KtxBlobIndex::mipLevel) .element(&KtxBlobIndex::arrayIndex) .element(&KtxBlobIndex::cubeFace); value_object(""Box"") .field(""center"", &Box::center) .field(""halfExtent"", &Box::halfExtent); value_object(""Aabb"") .field(""min"", &filament::Aabb::min) .field(""max"", &filament::Aabb::max); // In JavaScript, a flat contiguous representation is best for matrices (see gl-matrix) so we // need to define a small wrapper here. struct flatmat4 { filament::math::mat4f m; float& operator[](int i) { return m[i / 4][i % 4]; } }; value_array(""mat4"") .element(index< 0>()).element(index< 1>()).element(index< 2>()).element(index< 3>()) .element(index< 4>()).element(index< 5>()).element(index< 6>()).element(index< 7>()) .element(index< 8>()).element(index< 9>()).element(index<10>()).element(index<11>()) .element(index<12>()).element(index<13>()).element(index<14>()).element(index<15>()); struct flatmat3 { filament::math::mat3f m; float& operator[](int i) { return m[i / 3][i % 3]; } }; value_array(""mat3"") .element(index<0>()).element(index<1>()).element(index<2>()) .element(index<3>()).element(index<4>()).element(index<5>()) .element(index<6>()).element(index<7>()).element(index<8>()); value_object(""RenderableManager$Bone"") .field(""unitQuaternion"", &RenderableManager::Bone::unitQuaternion) .field(""translation"", &RenderableManager::Bone::translation); // CORE FILAMENT CLASSES // --------------------- /// Engine ::core class:: Central manager and resource owner. class_(""Engine"") .class_function(""_create"", (Engine* (*)()) [] { return Engine::create(); }, allow_raw_pointers()) /// destroy ::static method:: Destroys an engine instance and cleans up resources. /// engine ::argument:: the instance to destroy .class_function(""destroy"", (void (*)(Engine*)) [] (Engine* engine) { Engine::destroy(&engine); }, allow_raw_pointers()) .function(""execute"", &Engine::execute) /// getTransformManager ::method:: /// ::retval:: an instance of [TransformManager] .function(""getTransformManager"", EMBIND_LAMBDA(TransformManager*, (Engine* engine), { return &engine->getTransformManager(); }), allow_raw_pointers()) /// getLightManager ::method:: /// ::retval:: an instance of [LightManager] .function(""getLightManager"", EMBIND_LAMBDA(LightManager*, (Engine* engine), { return &engine->getLightManager(); }), allow_raw_pointers()) /// getRenderableManager ::method:: /// ::retval:: an instance of [RenderableManager] .function(""getRenderableManager"", EMBIND_LAMBDA(RenderableManager*, (Engine* engine), { return &engine->getRenderableManager(); }), allow_raw_pointers()) /// createSwapChain ::method:: /// ::retval:: an instance of [SwapChain] .function(""createSwapChain"", (SwapChain* (*)(Engine*)) [] (Engine* engine) { return engine->createSwapChain(nullptr); }, allow_raw_pointers()) /// destroySwapChain ::method:: /// swapChain ::argument:: an instance of [SwapChain] .function(""destroySwapChain"", (void (*)(Engine*, SwapChain*)) [] (Engine* engine, SwapChain* swapChain) { engine->destroy(swapChain); }, allow_raw_pointers()) /// createRenderer ::method:: /// ::retval:: an instance of [Renderer] .function(""createRenderer"", &Engine::createRenderer, allow_raw_pointers()) /// destroyRenderer ::method:: /// renderer ::argument:: an instance of [Renderer] .function(""destroyRenderer"", (void (*)(Engine*, Renderer*)) [] (Engine* engine, Renderer* renderer) { engine->destroy(renderer); }, allow_raw_pointers()) /// createView ::method:: /// ::retval:: an instance of [View] .function(""createView"", &Engine::createView, allow_raw_pointers()) /// destroyView ::method:: /// view ::argument:: an instance of [View] .function(""destroyView"", (void (*)(Engine*, View*)) [] (Engine* engine, View* view) { engine->destroy(view); }, allow_raw_pointers()) /// createScene ::method:: /// ::retval:: an instance of [Scene] .function(""createScene"", &Engine::createScene, allow_raw_pointers()) /// destroyScene ::method:: /// scene ::argument:: an instance of [Scene] .function(""destroyScene"", (void (*)(Engine*, Scene*)) [] (Engine* engine, Scene* scene) { engine->destroy(scene); }, allow_raw_pointers()) /// createCamera ::method:: /// ::retval:: an instance of [Camera] .function(""createCamera"", select_overload(&Engine::createCamera), allow_raw_pointers()) /// destroyCamera ::method:: /// camera ::argument:: an instance of [Camera] .function(""destroyCamera"", (void (*)(Engine*, Camera*)) [] (Engine* engine, Camera* camera) { engine->destroy(camera); }, allow_raw_pointers()) .function(""_createMaterial"", EMBIND_LAMBDA(Material*, (Engine* engine, BufferDescriptor mbd), { return Material::Builder().package(mbd.bd->buffer, mbd.bd->size).build(*engine); }), allow_raw_pointers()) /// destroyMaterial ::method:: /// material ::argument:: an instance of [Material] .function(""destroyMaterial"", (void (*)(Engine*, Material*)) [] (Engine* engine, Material* mat) { engine->destroy(mat); }, allow_raw_pointers()) /// destroyEntity ::method:: /// entity ::argument:: an [Entity] .function(""destroyEntity"", (void (*)(Engine*, utils::Entity)) [] (Engine* engine, utils::Entity entity) { engine->destroy(entity); }, allow_raw_pointers()) /// destroyIndexBuffer ::method:: /// ib ::argument:: the [IndexBuffer] to destroy .function(""destroyIndexBuffer"", (void (*)(Engine*, IndexBuffer*)) [] (Engine* engine, IndexBuffer* ib) { engine->destroy(ib); }, allow_raw_pointers()) /// destroyIndirectLight ::method:: /// light ::argument:: the [IndirectLight] to destroy .function(""destroyIndirectLight"", (void (*)(Engine*, IndirectLight*)) [] (Engine* engine, IndirectLight* light) { engine->destroy(light); }, allow_raw_pointers()) /// destroyMaterial ::method:: /// instance ::argument:: the [MaterialInstance] to destroy .function(""destroyMaterialInstance"", (void (*)(Engine*, MaterialInstance*)) [] (Engine* engine, MaterialInstance* mi) { engine->destroy(mi); }, allow_raw_pointers()) /// destroyRenderTarget ::method:: /// rt ::argument:: the [RenderTarget] to destroy .function(""destroyRenderTarget"", (void (*)(Engine*, RenderTarget*)) [] (Engine* engine, RenderTarget* rt) { engine->destroy(rt); }, allow_raw_pointers()) /// destroySkybox ::method:: /// skybox ::argument:: the [Skybox] to destroy .function(""destroySkybox"", (void (*)(Engine*, Skybox*)) [] (Engine* engine, Skybox* sky) { engine->destroy(sky); }, allow_raw_pointers()) /// destroyTexture ::method:: /// texture ::argument:: the [Texture] to destroy .function(""destroyTexture"", (void (*)(Engine*, Texture*)) [] (Engine* engine, Texture* tex) { engine->destroy(tex); }, allow_raw_pointers()) /// destroyVertexBuffer ::method:: /// vb ::argument:: the [VertexBuffer] to destroy .function(""destroyVertexBuffer"", (void (*)(Engine*, VertexBuffer*)) [] (Engine* engine, VertexBuffer* vb) { engine->destroy(vb); }, allow_raw_pointers()); /// SwapChain ::core class:: Represents the platform's native rendering surface. /// See also the [Engine] methods `createSwapChain` and `destroySwapChain`. class_(""SwapChain""); /// Renderer ::core class:: Represents the platform's native window. /// See also the [Engine] methods `createRenderer` and `destroyRenderer`. class_(""Renderer"") .function(""renderView"", &Renderer::render, allow_raw_pointers()) /// render ::method:: requests rendering for a single frame on the given [View] /// swapChain ::argument:: the [SwapChain] corresponding to the canvas /// view ::argument:: the [View] corresponding to the canvas .function(""render"", EMBIND_LAMBDA(void, (Renderer* self, SwapChain* swapChain, View* view), { auto engine = self->getEngine(); if (self->beginFrame(swapChain)) { self->render(view); self->endFrame(); } engine->execute(); }), allow_raw_pointers()) .function(""beginFrame"", &Renderer::beginFrame, allow_raw_pointers()) .function(""endFrame"", &Renderer::endFrame, allow_raw_pointers()); /// View ::core class:: Encompasses all the state needed for rendering a Scene. /// A view is associated with a particular [Scene], [Camera], and viewport. /// See also the [Engine] methods `createView` and `destroyView`. class_(""View"") .function(""setScene"", &View::setScene, allow_raw_pointers()) .function(""setCamera"", &View::setCamera, allow_raw_pointers()) .function(""getViewport"", &View::getViewport) .function(""setViewport"", &View::setViewport) .function(""setClearColor"", &View::setClearColor) .function(""setDepthPrepass"", &View::setDepthPrepass) .function(""setPostProcessingEnabled"", &View::setPostProcessingEnabled) .function(""setAntiAliasing"", &View::setAntiAliasing) .function(""getAntiAliasing"", &View::getAntiAliasing) .function(""setSampleCount"", &View::setSampleCount) .function(""setRenderTarget"", EMBIND_LAMBDA(void, (View* self, RenderTarget* renderTarget), { self->setRenderTarget(renderTarget); }), allow_raw_pointers()); /// Scene ::core class:: Flat container of renderables and lights. /// See also the [Engine] methods `createScene` and `destroyScene`. class_(""Scene"") .function(""addEntity"", &Scene::addEntity) .function(""addEntities"", EMBIND_LAMBDA(void, (Scene* self, std::vector entities), { self->addEntities(entities.data(), entities.size()); }), allow_raw_pointers()) .function(""hasEntity"", &Scene::hasEntity) .function(""remove"", &Scene::remove) .function(""setSkybox"", &Scene::setSkybox, allow_raw_pointers()) .function(""setIndirectLight"", &Scene::setIndirectLight, allow_raw_pointers()) .function(""getRenderableCount"", &Scene::getRenderableCount) .function(""getLightCount"", &Scene::getLightCount); /// Frustum ::core class:: Represents the six planes of a truncated viewing pyramid class_(""Frustum"") .constructor(EMBIND_LAMBDA(Frustum*, (flatmat4 m), { return new Frustum(m.m); }), allow_raw_pointers()) .function(""setProjection"", EMBIND_LAMBDA(void, (Frustum* self, flatmat4 m), { self->setProjection(m.m); }), allow_raw_pointers()) .function(""getNormalizedPlane"", &Frustum::getNormalizedPlane) .function(""intersectsBox"", EMBIND_LAMBDA(bool, (Frustum* self, const Box& box), { return self->intersects(box); }), allow_raw_pointers()) .function(""intersectsSphere"", EMBIND_LAMBDA(bool, (Frustum* self, const filament::math::float4& sphere), { return self->intersects(sphere); }), allow_raw_pointers()); /// Camera ::core class:: Represents the eye through which the scene is viewed. /// See also the [Engine] methods `createCamera` and `destroyCamera`. class_(""Camera"") .function(""setProjection"", EMBIND_LAMBDA(void, (Camera* self, Camera::Projection projection, double left, double right, double bottom, double top, double near, double far), { self->setProjection(projection, left, right, bottom, top, near, far); }), allow_raw_pointers()) .function(""setProjectionFov"", EMBIND_LAMBDA(void, (Camera* self, double fovInDegrees, double aspect, double near, double far, Camera::Fov direction), { self->setProjection(fovInDegrees, aspect, near, far, direction); }), allow_raw_pointers()) .function(""setLensProjection"", &Camera::setLensProjection) .function(""setCustomProjection"", EMBIND_LAMBDA(void, (Camera* self, flatmat4 m, double near, double far), { self->setCustomProjection(filament::math::mat4(m.m), near, far); }), allow_raw_pointers()) .function(""getProjectionMatrix"", EMBIND_LAMBDA(flatmat4, (Camera* self), { return flatmat4 { filament::math::mat4f(self->getProjectionMatrix()) }; }), allow_raw_pointers()) .function(""getCullingProjectionMatrix"", EMBIND_LAMBDA(flatmat4, (Camera* self), { return flatmat4 { filament::math::mat4f(self->getCullingProjectionMatrix()) }; }), allow_raw_pointers()) .function(""getNear"", &Camera::getNear) .function(""getCullingFar"", &Camera::getCullingFar) .function(""setModelMatrix"", EMBIND_LAMBDA(void, (Camera* self, flatmat4 m), { self->setModelMatrix(m.m); }), allow_raw_pointers()) .function(""lookAt"", &Camera::lookAt) .function(""getModelMatrix"", EMBIND_LAMBDA(flatmat4, (Camera* self), { return flatmat4 { self->getModelMatrix() }; }), allow_raw_pointers()) .function(""getViewMatrix"", EMBIND_LAMBDA(flatmat4, (Camera* self), { return flatmat4 { self->getViewMatrix() }; }), allow_raw_pointers()) .function(""getPosition"", &Camera::getPosition) .function(""getLeftVector"", &Camera::getLeftVector) .function(""getUpVector"", &Camera::getUpVector) .function(""getForwardVector"", &Camera::getForwardVector) .function(""getFrustum"", &Camera::getFrustum) .function(""setExposure"", &Camera::setExposure) .function(""getAperture"", &Camera::getAperture) .function(""getShutterSpeed"", &Camera::getShutterSpeed) .function(""getSensitivity"", &Camera::getSensitivity) .class_function(""inverseProjection"", (flatmat4 (*)(flatmat4)) [] (flatmat4 m) { return flatmat4 { filament::math::mat4f(Camera::inverseProjection(m.m)) }; }, allow_raw_pointers()); class_(""RenderTarget$Builder"") .BUILDER_FUNCTION(""texture"", RenderTargetBuilder, (RenderTargetBuilder* builder, RenderTarget::AttachmentPoint attachment, Texture* tex), { return &builder->texture(attachment, tex); }) .BUILDER_FUNCTION(""mipLevel"", RenderTargetBuilder, (RenderTargetBuilder* builder, RenderTarget::AttachmentPoint attachment, uint8_t level), { return &builder->mipLevel(attachment, level); }) .BUILDER_FUNCTION(""face"", RenderTargetBuilder, (RenderTargetBuilder* builder, RenderTarget::AttachmentPoint attachment, Texture::CubemapFace face), { return &builder->face(attachment, face); }) .BUILDER_FUNCTION(""layer"", RenderTargetBuilder, (RenderTargetBuilder* builder, RenderTarget::AttachmentPoint attachment, uint32_t layer), { return &builder->layer(attachment, layer); }) .function(""_build"", EMBIND_LAMBDA(RenderTarget*, (RenderTargetBuilder* builder, Engine* engine), { return builder->build(*engine); }), allow_raw_pointers()); class_(""RenderTarget"") .class_function(""Builder"", (RenderTargetBuilder (*)()) [] () { return RenderTarget::Builder(); }) .function(""getMipLevel"", &RenderTarget::getMipLevel) .function(""getFace"", &RenderTarget::getFace) .function(""getLayer"", &RenderTarget::getLayer); class_(""RenderableManager$Builder"") .BUILDER_FUNCTION(""geometry"", RenderableBuilder, (RenderableBuilder* builder, size_t index, RenderableManager::PrimitiveType type, VertexBuffer* vertices, IndexBuffer* indices), { return &builder->geometry(index, type, vertices, indices); }) .BUILDER_FUNCTION(""material"", RenderableBuilder, (RenderableBuilder* builder, size_t index, MaterialInstance* mi), { return &builder->material(index, mi); }) .BUILDER_FUNCTION(""boundingBox"", RenderableBuilder, (RenderableBuilder* builder, Box box), { return &builder->boundingBox(box); }) .BUILDER_FUNCTION(""layerMask"", RenderableBuilder, (RenderableBuilder* builder, uint8_t select, uint8_t values), { return &builder->layerMask(select, values); }) .BUILDER_FUNCTION(""priority"", RenderableBuilder, (RenderableBuilder* builder, uint8_t value), { return &builder->priority(value); }) .BUILDER_FUNCTION(""culling"", RenderableBuilder, (RenderableBuilder* builder, bool enable), { return &builder->culling(enable); }) .BUILDER_FUNCTION(""castShadows"", RenderableBuilder, (RenderableBuilder* builder, bool enable), { return &builder->castShadows(enable); }) .BUILDER_FUNCTION(""receiveShadows"", RenderableBuilder, (RenderableBuilder* builder, bool enable), { return &builder->receiveShadows(enable); }) .BUILDER_FUNCTION(""skinning"", RenderableBuilder, (RenderableBuilder* builder, size_t boneCount), { return &builder->skinning(boneCount); }) .BUILDER_FUNCTION(""skinningBones"", RenderableBuilder, (RenderableBuilder* builder, emscripten::val transforms), { auto nbones = transforms[""length""].as(); std::vector bones(nbones); for (size_t i = 0; i < nbones; i++) { bones[i] = transforms[i].as(); } return &builder->skinning(bones.size(), bones.data()); }) .BUILDER_FUNCTION(""skinningMatrices"", RenderableBuilder, (RenderableBuilder* builder, emscripten::val transforms), { auto nbones = transforms[""length""].as(); std::vector matrices(nbones); for (size_t i = 0; i < nbones; i++) { matrices[i] = transforms[i].as().m; } return &builder->skinning(matrices.size(), matrices.data()); }) .BUILDER_FUNCTION(""morphing"", RenderableBuilder, (RenderableBuilder* builder, bool enable), { return &builder->morphing(enable); }) .BUILDER_FUNCTION(""blendOrder"", RenderableBuilder, (RenderableBuilder* builder, size_t index, uint16_t order), { return &builder->blendOrder(index, order); }) .function(""_build"", EMBIND_LAMBDA(int, (RenderableBuilder* builder, Engine* engine, utils::Entity entity), { return (int) builder->build(*engine, entity); }), allow_raw_pointers()); /// RenderableManager ::core class:: Allows access to properties of drawable objects. class_(""RenderableManager"") .function(""hasComponent"", &RenderableManager::hasComponent) /// getInstance ::method:: Gets an instance of the renderable component for an entity. /// entity ::argument:: an [Entity] /// ::retval:: a renderable component .function(""getInstance"", &RenderableManager::getInstance) .class_function(""Builder"", (RenderableBuilder (*)(int)) [] (int n) { return RenderableBuilder(n); }) .function(""destroy"", &RenderableManager::destroy) .function(""setAxisAlignedBoundingBox"", &RenderableManager::setAxisAlignedBoundingBox) .function(""setLayerMask"", &RenderableManager::setLayerMask) .function(""setPriority"", &RenderableManager::setPriority) .function(""setCastShadows"", &RenderableManager::setCastShadows) .function(""setReceiveShadows"", &RenderableManager::setReceiveShadows) .function(""isShadowCaster"", &RenderableManager::isShadowCaster) .function(""isShadowReceiver"", &RenderableManager::isShadowReceiver) .function(""setBones"", EMBIND_LAMBDA(void, (RenderableManager* self, RenderableManager::Instance instance, emscripten::val transforms, size_t offset), { auto nbones = transforms[""length""].as(); std::vector bones(nbones); for (size_t i = 0; i < nbones; i++) { bones[i] = transforms[i].as(); } self->setBones(instance, bones.data(), bones.size(), offset); }), allow_raw_pointers()) .function(""setBonesFromMatrices"", EMBIND_LAMBDA(void, (RenderableManager* self, RenderableManager::Instance instance, emscripten::val transforms, size_t offset), { auto nbones = transforms[""length""].as(); std::vector bones(nbones); for (size_t i = 0; i < nbones; i++) { bones[i] = transforms[i].as().m; } self->setBones(instance, bones.data(), bones.size(), offset); }), allow_raw_pointers()) // NOTE: this cannot take a float4 due to a binding issue. .function(""setMorphWeights"", EMBIND_LAMBDA(void, (RenderableManager* self, RenderableManager::Instance instance, float x, float y, float z, float w), { self->setMorphWeights(instance, {x, y, z, w}); }), allow_raw_pointers()) .function(""getAxisAlignedBoundingBox"", &RenderableManager::getAxisAlignedBoundingBox) .function(""getPrimitiveCount"", &RenderableManager::getPrimitiveCount) .function(""setMaterialInstanceAt"", &RenderableManager::setMaterialInstanceAt, allow_raw_pointers()) .function(""getMaterialInstanceAt"", &RenderableManager::getMaterialInstanceAt, allow_raw_pointers()) .function(""setGeometryAt"", EMBIND_LAMBDA(void, (RenderableManager* self, RenderableManager::Instance instance, size_t primitiveIndex, RenderableManager::PrimitiveType type, VertexBuffer* vertices, IndexBuffer* indices, size_t offset, size_t count), { self->setGeometryAt(instance, primitiveIndex, type, vertices, indices, offset, count); }), allow_raw_pointers()) .function(""setGeometryRangeAt"", EMBIND_LAMBDA(void, (RenderableManager* self, RenderableManager::Instance instance, size_t primitiveIndex, RenderableManager::PrimitiveType type, size_t offset, size_t count), { self->setGeometryAt(instance, primitiveIndex, type, offset, count); }), allow_raw_pointers()) .function(""setBlendOrderAt"", &RenderableManager::setBlendOrderAt) .function(""getEnabledAttributesAt"", EMBIND_LAMBDA(uint32_t, (RenderableManager* self, RenderableManager::Instance instance, size_t primitiveIndex), { return self->getEnabledAttributesAt(instance, primitiveIndex).getValue(); }), allow_raw_pointers()); /// RenderableManager$Instance ::class:: Component instance returned by [RenderableManager] /// Be sure to call the instance's `delete` method when you're done with it. class_(""RenderableManager$Instance""); /// delete ::method:: Frees an instance obtained via `getInstance` /// TransformManager ::core class:: Adds transform components to entities. class_(""TransformManager"") .function(""hasComponent"", &TransformManager::hasComponent) /// getInstance ::method:: Gets an instance representing the transform component for an entity. /// entity ::argument:: an [Entity] /// ::retval:: a transform component that can be passed to `setTransform`. .function(""getInstance"", &TransformManager::getInstance) .function(""create"", EMBIND_LAMBDA(void, (TransformManager* self, utils::Entity entity), { self->create(entity); }), allow_raw_pointers()) .function(""destroy"", &TransformManager::destroy) .function(""setParent"", &TransformManager::setParent) .function(""getParent"", &TransformManager::getParent) .function(""getChidren"", EMBIND_LAMBDA(std::vector, (TransformManager* self, TransformManager::Instance instance), { std::vector result(self->getChildCount(instance)); self->getChildren(instance, result.data(), result.size()); return result; }), allow_raw_pointers()) /// setTransform ::method:: Sets the mat4 value of a transform component. /// instance ::argument:: The transform instance of entity, obtained via `getInstance`. /// matrix ::argument:: Array of 16 numbers (mat4) .function(""setTransform"", EMBIND_LAMBDA(void, (TransformManager* self, TransformManager::Instance instance, flatmat4 m), { self->setTransform(instance, m.m); }), allow_raw_pointers()) .function(""getTransform"", EMBIND_LAMBDA(flatmat4, (TransformManager* self, TransformManager::Instance instance), { return flatmat4 { self->getTransform(instance) } ; }), allow_raw_pointers()) .function(""getWorldTransform"", EMBIND_LAMBDA(flatmat4, (TransformManager* self, TransformManager::Instance instance), { return flatmat4 { self->getTransform(instance) } ; }), allow_raw_pointers()) .function(""openLocalTransformTransaction"", &TransformManager::openLocalTransformTransaction) .function(""commitLocalTransformTransaction"", &TransformManager::commitLocalTransformTransaction); /// TransformManager$Instance ::class:: Component instance returned by [TransformManager] /// Be sure to call the instance's `delete` method when you're done with it. class_(""TransformManager$Instance""); /// delete ::method:: Frees an instance obtained via `getInstance` class_(""LightManager$Builder"") .function(""_build"", EMBIND_LAMBDA(int, (LightBuilder* builder, Engine* engine, utils::Entity entity), { return (int) builder->build(*engine, entity); }), allow_raw_pointers()) .BUILDER_FUNCTION(""castShadows"", LightBuilder, (LightBuilder* builder, bool enable), { return &builder->castShadows(enable); }) .BUILDER_FUNCTION(""castLight"", LightBuilder, (LightBuilder* builder, bool enable), { return &builder->castLight(enable); }) .BUILDER_FUNCTION(""position"", LightBuilder, (LightBuilder* builder, filament::math::float3 value), { return &builder->position(value); }) .BUILDER_FUNCTION(""direction"", LightBuilder, (LightBuilder* builder, filament::math::float3 value), { return &builder->direction(value); }) .BUILDER_FUNCTION(""color"", LightBuilder, (LightBuilder* builder, filament::math::float3 value), { return &builder->color(value); }) .BUILDER_FUNCTION(""intensity"", LightBuilder, (LightBuilder* builder, float value), { return &builder->intensity(value); }) .BUILDER_FUNCTION(""falloff"", LightBuilder, (LightBuilder* builder, float value), { return &builder->falloff(value); }) .BUILDER_FUNCTION(""spotLightCone"", LightBuilder, (LightBuilder* builder, float inner, float outer), { return &builder->spotLightCone(inner, outer); }) .BUILDER_FUNCTION(""sunAngularRadius"", LightBuilder, (LightBuilder* builder, float value), { return &builder->sunAngularRadius(value); }) .BUILDER_FUNCTION(""sunHaloSize"", LightBuilder, (LightBuilder* builder, float value), { return &builder->sunHaloSize(value); }) .BUILDER_FUNCTION(""sunHaloFalloff"", LightBuilder, (LightBuilder* builder, float value), { return &builder->sunHaloFalloff(value); }); class_(""LightManager"") .function(""hasComponent"", &LightManager::hasComponent) /// getInstance ::method:: Gets an instance of the light component for an entity. /// entity ::argument:: an [Entity] /// ::retval:: a light source component .function(""getInstance"", &LightManager::getInstance) .class_function(""Builder"", (LightBuilder (*)(LightManager::Type)) [] (LightManager::Type lt) { return LightBuilder(lt); }) .function(""getType"", &LightManager::getType) .function(""isDirectional"", &LightManager::isDirectional) .function(""isPointLight"", &LightManager::isPointLight) .function(""isSpotLight"", &LightManager::isSpotLight) .function(""setPosition"", &LightManager::setPosition) .function(""getPosition"", &LightManager::getPosition) .function(""setDirection"", &LightManager::setDirection) .function(""getDirection"", &LightManager::getDirection) .function(""setColor"", &LightManager::setColor) .function(""getColor"", &LightManager::getColor) .function(""setIntensity"", EMBIND_LAMBDA(void, (LightManager* self, LightManager::Instance instance, float intensity), { self->setIntensity(instance, intensity); }), allow_raw_pointers()) .function(""setIntensityEnergy"", EMBIND_LAMBDA(void, (LightManager* self, LightManager::Instance instance, float watts, float efficiency), { self->setIntensity(instance, watts, efficiency); }), allow_raw_pointers()) .function(""getIntensity"", &LightManager::getIntensity) .function(""setFalloff"", &LightManager::setFalloff) .function(""getFalloff"", &LightManager::getFalloff) .function(""setSpotLightCone"", &LightManager::setSpotLightCone) .function(""setSunAngularRadius"", &LightManager::setSunAngularRadius) .function(""getSunAngularRadius"", &LightManager::getSunAngularRadius) .function(""setSunHaloSize"", &LightManager::setSunHaloSize) .function(""getSunHaloSize"", &LightManager::getSunHaloSize) .function(""setSunHaloFalloff"", &LightManager::setSunHaloFalloff) .function(""getSunHaloFalloff"", &LightManager::getSunHaloFalloff) .function(""setShadowCaster"", &LightManager::setShadowCaster) .function(""isShadowCaster"", &LightManager::isShadowCaster) ; /// LightManager$Instance ::class:: Component instance returned by [LightManager] /// Be sure to call the instance's `delete` method when you're done with it. class_(""LightManager$Instance""); /// delete ::method:: Frees an instance obtained via `getInstance` class_(""VertexBuffer$Builder"") .function(""_build"", EMBIND_LAMBDA(VertexBuffer*, (VertexBuilder* builder, Engine* engine), { return builder->build(*engine); }), allow_raw_pointers()) .BUILDER_FUNCTION(""attribute"", VertexBuilder, (VertexBuilder* builder, VertexAttribute attr, uint8_t bufferIndex, VertexBuffer::AttributeType attrType, uint32_t byteOffset, uint8_t byteStride), { return &builder->attribute(attr, bufferIndex, attrType, byteOffset, byteStride); }) .BUILDER_FUNCTION(""vertexCount"", VertexBuilder, (VertexBuilder* builder, int count), { return &builder->vertexCount(count); }) .BUILDER_FUNCTION(""normalized"", VertexBuilder, (VertexBuilder* builder, VertexAttribute attrib), { return &builder->normalized(attrib); }) .BUILDER_FUNCTION(""normalizedIf"", VertexBuilder, (VertexBuilder* builder, VertexAttribute attrib, bool normalized), { return &builder->normalized(attrib, normalized); }) .BUILDER_FUNCTION(""bufferCount"", VertexBuilder, (VertexBuilder* builder, int count), { return &builder->bufferCount(count); }); /// VertexBuffer ::core class:: Bundle of buffers and associated vertex attributes. class_(""VertexBuffer"") .class_function(""Builder"", (VertexBuilder (*)()) [] { return VertexBuilder(); }) .function(""_setBufferAt"", EMBIND_LAMBDA(void, (VertexBuffer* self, Engine* engine, uint8_t bufferIndex, BufferDescriptor vbd), { self->setBufferAt(*engine, bufferIndex, std::move(*vbd.bd)); }), allow_raw_pointers()); class_(""IndexBuffer$Builder"") .function(""_build"", EMBIND_LAMBDA(IndexBuffer*, (IndexBuilder* builder, Engine* engine), { return builder->build(*engine); }), allow_raw_pointers()) .BUILDER_FUNCTION(""indexCount"", IndexBuilder, (IndexBuilder* builder, int count), { return &builder->indexCount(count); }) .BUILDER_FUNCTION(""bufferType"", IndexBuilder, (IndexBuilder* builder, IndexBuffer::IndexType indexType), { return &builder->bufferType(indexType); }); /// IndexBuffer ::core class:: Array of 16-bit or 32-bit unsigned integers consumed by the GPU. class_(""IndexBuffer"") .class_function(""Builder"", (IndexBuilder (*)()) [] { return IndexBuilder(); }) .function(""_setBuffer"", EMBIND_LAMBDA(void, (IndexBuffer* self, Engine* engine, BufferDescriptor ibd), { self->setBuffer(*engine, std::move(*ibd.bd)); }), allow_raw_pointers()); class_(""Material"") .function(""getDefaultInstance"", select_overload(&Material::getDefaultInstance), allow_raw_pointers()) .function(""createInstance"", &Material::createInstance, allow_raw_pointers()) .function(""getName"", EMBIND_LAMBDA(std::string, (Material* self), { return std::string(self->getName()); }), allow_raw_pointers()); class_(""MaterialInstance"") .function(""setBoolParameter"", EMBIND_LAMBDA(void, (MaterialInstance* self, std::string name, bool value), { self->setParameter(name.c_str(), value); }), allow_raw_pointers()) .function(""setFloatParameter"", EMBIND_LAMBDA(void, (MaterialInstance* self, std::string name, float value), { self->setParameter(name.c_str(), value); }), allow_raw_pointers()) .function(""setFloat2Parameter"", EMBIND_LAMBDA(void, (MaterialInstance* self, std::string name, filament::math::float2 value), { self->setParameter(name.c_str(), value); }), allow_raw_pointers()) .function(""setFloat3Parameter"", EMBIND_LAMBDA(void, (MaterialInstance* self, std::string name, filament::math::float3 value), { self->setParameter(name.c_str(), value); }), allow_raw_pointers()) .function(""setFloat4Parameter"", EMBIND_LAMBDA(void, (MaterialInstance* self, std::string name, filament::math::float4 value), { self->setParameter(name.c_str(), value); }), allow_raw_pointers()) .function(""setTextureParameter"", EMBIND_LAMBDA(void, (MaterialInstance* self, std::string name, Texture* value, TextureSampler sampler), { self->setParameter(name.c_str(), value, sampler); }), allow_raw_pointers()) .function(""setColor3Parameter"", EMBIND_LAMBDA(void, (MaterialInstance* self, std::string name, RgbType type, filament::math::float3 value), { self->setParameter(name.c_str(), type, value); }), allow_raw_pointers()) .function(""setColor4Parameter"", EMBIND_LAMBDA(void, (MaterialInstance* self, std::string name, RgbaType type, filament::math::float4 value), { self->setParameter(name.c_str(), type, value); }), allow_raw_pointers()) .function(""setPolygonOffset"", &MaterialInstance::setPolygonOffset) .function(""setMaskThreshold"", &MaterialInstance::setMaskThreshold) .function(""setDoubleSided"", &MaterialInstance::setDoubleSided) .function(""setCullingMode"", &MaterialInstance::setCullingMode); class_(""TextureSampler"") .constructor(); /// Texture ::core class:: 2D image or cubemap that can be sampled by the GPU, possibly mipmapped. class_(""Texture"") .class_function(""Builder"", (TexBuilder (*)()) [] { return TexBuilder(); }) .function(""generateMipmaps"", &Texture::generateMipmaps) .function(""_setImage"", EMBIND_LAMBDA(void, (Texture* self, Engine* engine, uint8_t level, PixelBufferDescriptor pbd), { self->setImage(*engine, level, std::move(*pbd.pbd)); }), allow_raw_pointers()) .function(""_setImageCube"", EMBIND_LAMBDA(void, (Texture* self, Engine* engine, uint8_t level, PixelBufferDescriptor pbd), { uint32_t faceSize = pbd.pbd->size / 6; Texture::FaceOffsets offsets(faceSize); self->setImage(*engine, level, std::move(*pbd.pbd), offsets); }), allow_raw_pointers()); class_(""Texture$Builder"") .function(""_build"", EMBIND_LAMBDA(Texture*, (TexBuilder* builder, Engine* engine), { return builder->build(*engine); }), allow_raw_pointers()) .BUILDER_FUNCTION(""width"", TexBuilder, (TexBuilder* builder, uint32_t width), { return &builder->width(width); }) .BUILDER_FUNCTION(""height"", TexBuilder, (TexBuilder* builder, uint32_t height), { return &builder->height(height); }) .BUILDER_FUNCTION(""depth"", TexBuilder, (TexBuilder* builder, uint32_t depth), { return &builder->depth(depth); }) .BUILDER_FUNCTION(""levels"", TexBuilder, (TexBuilder* builder, uint8_t levels), { return &builder->levels(levels); }) .BUILDER_FUNCTION(""sampler"", TexBuilder, (TexBuilder* builder, Texture::Sampler target), { return &builder->sampler(target); }) .BUILDER_FUNCTION(""format"", TexBuilder, (TexBuilder* builder, Texture::InternalFormat fmt), { return &builder->format(fmt); }) .BUILDER_FUNCTION(""usage"", TexBuilder, (TexBuilder* builder, Texture::Usage usage), { return &builder->usage(usage); }); class_(""IndirectLight"") .class_function(""Builder"", (IblBuilder (*)()) [] { return IblBuilder(); }) .function(""setIntensity"", &IndirectLight::setIntensity) .function(""getIntensity"", &IndirectLight::getIntensity) .function(""setRotation"", EMBIND_LAMBDA(void, (IndirectLight* self, flatmat3 value), { return self->setRotation(value.m); }), allow_raw_pointers()) .function(""getRotation"", EMBIND_LAMBDA(flatmat3, (IndirectLight* self), { return flatmat3 { self->getRotation() }; }), allow_raw_pointers()) .function(""getDirectionEstimate"", &IndirectLight::getDirectionEstimate) .function(""getColorEstimate"", &IndirectLight::getColorEstimate); class_(""IndirectLight$Builder"") .function(""_build"", EMBIND_LAMBDA(IndirectLight*, (IblBuilder* builder, Engine* engine), { return builder->build(*engine); }), allow_raw_pointers()) .BUILDER_FUNCTION(""reflections"", IblBuilder, (IblBuilder* builder, Texture const* cubemap), { return &builder->reflections(cubemap); }) .BUILDER_FUNCTION(""irradianceTex"", IblBuilder, (IblBuilder* builder, Texture const* cubemap), { return &builder->irradiance(cubemap); }) .BUILDER_FUNCTION(""irradianceSh"", IblBuilder, (IblBuilder* builder, uint8_t nbands, val ta), { // This is not efficient but consuming a BufferDescriptor would be overkill. size_t nfloats = ta[""length""].as(); if (nfloats != nbands * nbands * 3) { printf(""Received %zu floats for spherical harmonics, expected %d."", nfloats, nbands); return builder; } std::vector floats(nfloats); for (size_t i = 0; i < nfloats; i++) { floats[i] = ta[i].as(); } return &builder->irradiance(nbands, (filament::math::float3 const*) floats.data()); }) .BUILDER_FUNCTION(""intensity"", IblBuilder, (IblBuilder* builder, float value), { return &builder->intensity(value); }) .BUILDER_FUNCTION(""rotation"", IblBuilder, (IblBuilder* builder, flatmat3 value), { return &builder->rotation(value.m); }); class_(""Skybox"") .class_function(""Builder"", (SkyBuilder (*)()) [] { return SkyBuilder(); }); class_(""Skybox$Builder"") .function(""_build"", EMBIND_LAMBDA(Skybox*, (SkyBuilder* builder, Engine* engine), { return builder->build(*engine); }), allow_raw_pointers()) .BUILDER_FUNCTION(""environment"", SkyBuilder, (SkyBuilder* builder, Texture* cubemap), { return &builder->environment(cubemap); }) .BUILDER_FUNCTION(""showSun"", SkyBuilder, (SkyBuilder* builder, bool show), { return &builder->showSun(show); }); // UTILS TYPES // ----------- /// Entity ::core class:: Handle to an object consisting of a set of components. /// To create an entity with no components, use [EntityManager]. class_(""Entity""); /// EntityManager ::core class:: Singleton used for constructing entities in Filament's ECS. class_(""EntityManager"") /// get ::static method:: Gets the singleton entity manager instance. /// ::retval:: the one and only entity manager .class_function(""get"", (utils::EntityManager* (*)()) [] { return &utils::EntityManager::get(); }, allow_raw_pointers()) /// create ::method:: /// ::retval:: an [Entity] without any components .function(""create"", select_overload(&utils::EntityManager::create)) .function(""destroy"", select_overload(&utils::EntityManager::destroy)); // DRIVER TYPES // ------------ /// BufferDescriptor ::class:: Low level buffer wrapper. /// Clients should use the [Buffer] helper function to contruct BufferDescriptor objects. class_(""driver$BufferDescriptor"") .constructor() /// getBytes ::method:: Gets a view of the WASM heap referenced by the buffer descriptor. /// ::retval:: Uint8Array .function(""getBytes"", &BufferDescriptor::getBytes); /// PixelBufferDescriptor ::class:: Low level pixel buffer wrapper. /// Clients should use the [PixelBuffer] helper function to contruct PixelBufferDescriptor objects. class_(""driver$PixelBufferDescriptor"") .constructor() .constructor() /// getBytes ::method:: Gets a view of the WASM heap referenced by the buffer descriptor. /// ::retval:: Uint8Array .function(""getBytes"", &PixelBufferDescriptor::getBytes); // HELPER TYPES // ------------ /// KtxBundle ::class:: In-memory representation of a KTX file. /// Most clients should use one of the `create*FromKtx` utility methods in the JavaScript [Engine] /// wrapper rather than interacting with `KtxBundle` directly. class_(""KtxBundle"") .constructor(EMBIND_LAMBDA(KtxBundle*, (BufferDescriptor kbd), { return new KtxBundle((uint8_t*) kbd.bd->buffer, (uint32_t) kbd.bd->size); })) /// info ::method:: Obtains properties of the KTX header. /// ::retval:: The [KtxInfo] property accessor object. .function(""getNumMipLevels"", &KtxBundle::getNumMipLevels) /// getArrayLength ::method:: Obtains length of the texture array. /// ::retval:: The number of elements in the texture array .function(""getArrayLength"", &KtxBundle::getArrayLength) /// getInternalFormat ::method:: /// srgb ::argument:: boolean that forces the resulting format to SRGB if possible. /// ::retval:: [Texture$InternalFormat] /// Returns ""undefined"" if no valid Filament enumerant exists. .function(""getInternalFormat"", EMBIND_LAMBDA(Texture::InternalFormat, (KtxBundle* self, bool srgb), { auto result = KtxUtility::toTextureFormat(self->info()); if (srgb) { if (result == Texture::InternalFormat::RGB8) { result = Texture::InternalFormat::SRGB8; } if (result == Texture::InternalFormat::RGBA8) { result = Texture::InternalFormat::SRGB8_A8; } } return result; }), allow_raw_pointers()) /// getPixelDataFormat ::method:: /// ::retval:: [PixelDataFormat] /// Returns ""undefined"" if no valid Filament enumerant exists. .function(""getPixelDataFormat"", EMBIND_LAMBDA(backend::PixelDataFormat, (KtxBundle* self), { return KtxUtility::toPixelDataFormat(self->getInfo()); }), allow_raw_pointers()) /// getPixelDataType ::method:: /// ::retval:: [PixelDataType] /// Returns ""undefined"" if no valid Filament enumerant exists. .function(""getPixelDataType"", EMBIND_LAMBDA(backend::PixelDataType, (KtxBundle* self), { return KtxUtility::toPixelDataType(self->getInfo()); }), allow_raw_pointers()) /// getCompressedPixelDataType ::method:: /// ::retval:: [CompressedPixelDataType] /// Returns ""undefined"" if no valid Filament enumerant exists. .function(""getCompressedPixelDataType"", EMBIND_LAMBDA(backend::CompressedPixelDataType, (KtxBundle* self), { return KtxUtility::toCompressedPixelDataType(self->getInfo()); }), allow_raw_pointers()) /// isCompressed ::method:: /// Per spec, compressed textures in KTX always have their glFormat field set to 0. /// ::retval:: boolean .function(""isCompressed"", EMBIND_LAMBDA(bool, (KtxBundle* self), { return KtxUtility::isCompressed(self->getInfo()); }), allow_raw_pointers()) .function(""isCubemap"", &KtxBundle::isCubemap) .function(""_getBlob"", EMBIND_LAMBDA(BufferDescriptor, (KtxBundle* self, KtxBlobIndex index), { uint8_t* data; uint32_t size; self->getBlob(index, &data, &size); return BufferDescriptor(data, size); }), allow_raw_pointers()) .function(""_getCubeBlob"", EMBIND_LAMBDA(BufferDescriptor, (KtxBundle* self, uint32_t miplevel), { uint8_t* data; uint32_t size; self->getBlob({miplevel}, &data, &size); return BufferDescriptor(data, size * 6); }), allow_raw_pointers()) /// info ::method:: Obtains properties of the KTX header. /// ::retval:: The [KtxInfo] property accessor object. .function(""info"", &KtxBundle::info) /// getMetadata ::method:: Obtains arbitrary metadata from the KTX file. /// key ::argument:: string /// ::retval:: string .function(""getMetadata"", EMBIND_LAMBDA(std::string, (KtxBundle* self, std::string key), { return std::string(self->getMetadata(key.c_str())); }), allow_raw_pointers()); function(""KtxUtility$createTexture"", EMBIND_LAMBDA(Texture*, (Engine* engine, const KtxBundle& ktx, bool srgb), { return KtxUtility::createTexture(engine, ktx, srgb, nullptr, nullptr); }), allow_raw_pointers()); /// KtxInfo ::class:: Property accessor for KTX header. /// For example, `ktxbundle.info().pixelWidth`. See the /// [KTX spec](https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/) for the list of /// properties. class_(""KtxInfo"") .property(""endianness"", &KtxInfo::endianness) .property(""glType"", &KtxInfo::glType) .property(""glTypeSize"", &KtxInfo::glTypeSize) .property(""glFormat"", &KtxInfo::glFormat) .property(""glInternalFormat"", &KtxInfo::glInternalFormat) .property(""glBaseInternalFormat"", &KtxInfo::glBaseInternalFormat) .property(""pixelWidth"", &KtxInfo::pixelWidth) .property(""pixelHeight"", &KtxInfo::pixelHeight) .property(""pixelDepth"", &KtxInfo::pixelDepth); register_vector(""RegistryKeys""); register_vector(""EntityVector""); class_(""MeshReader$MaterialRegistry"") .constructor<>() .function(""size"", &MeshReader::MaterialRegistry::numRegistered) .function(""get"", EMBIND_LAMBDA(val, (MeshReader::MaterialRegistry* self, std::string k), { const utils::CString name(k.c_str(), k.size()); auto i = self->getMaterialInstance(name); if (i == nullptr) { return val::undefined(); } else { return val(i); } }), allow_raw_pointers()) .function(""set"", EMBIND_LAMBDA(void, (MeshReader::MaterialRegistry* self, std::string k, filament::MaterialInstance* v), { const utils::CString name(k.c_str(), k.size()); self->registerMaterialInstance(name, v); }), allow_raw_pointers()) .function(""keys"", EMBIND_LAMBDA(std::vector, (MeshReader::MaterialRegistry* self), { std::vector names(self->numRegistered()); self->getRegisteredMaterialNames(names.data()); std::vector result(self->numRegistered()); for (const auto& name : names) { result.emplace_back(name.c_str()); } return result; }), allow_raw_pointers()); // MeshReader ::class:: Simple parser for filamesh files. // JavaScript clients are encouraged to use the [loadFilamesh] helper function instead of using // this class directly. class_(""MeshReader"") // loadMeshFromBuffer ::static method:: Parses a filamesh buffer. // engine ::argument:: [Engine] // buffer ::argument:: [Buffer] // materials ::argument:: [MeshReader$MaterialRegistry] // ::retval:: the [MeshReader$Mesh] object .class_function(""loadMeshFromBuffer"", EMBIND_LAMBDA(MeshReader::Mesh, (Engine* engine, BufferDescriptor buffer, MeshReader::MaterialRegistry& matreg), { // This destruction lambda is called for the vertex buffer AND index buffer, so release // CPU memory only after both have been uploaded to the GPU. struct Bundle { int count; BufferDescriptor buffer; }; Bundle* bundle = new Bundle({ .count = 0, .buffer = buffer }); const auto destructor = [](void* buffer, size_t size, void* user) { Bundle* bundle = (Bundle*) user; if (++bundle->count == 2) { delete bundle; } }; // Parse the filamesh buffer. This creates the VB, IB, and renderable. return MeshReader::loadMeshFromBuffer( engine, buffer.bd->buffer, destructor, bundle, matreg); }), allow_raw_pointers()); // MeshReader$Mesh ::class:: Property accessor for objects created by [MeshReader]. // This exposes three getter methods: `renderable()`, `vertexBuffer()`, and `indexBuffer()`. These // are of type [Entity], [VertexBuffer], and [IndexBuffer]. JavaScript clients are encouraged to // use the [loadFilamesh] helper function instead of using this class directly. class_(""MeshReader$Mesh"") .function(""renderable"", EMBIND_LAMBDA(utils::Entity, (MeshReader::Mesh mesh), { return mesh.renderable; }), allow_raw_pointers()) .function(""vertexBuffer"", EMBIND_LAMBDA(VertexBuffer*, (MeshReader::Mesh mesh), { return mesh.vertexBuffer; }), allow_raw_pointers()) .function(""indexBuffer"", EMBIND_LAMBDA(IndexBuffer*, (MeshReader::Mesh mesh), { return mesh.indexBuffer; }), allow_raw_pointers()); // Clients should call [createTextureFromPng] rather than using decodePng and DecodedPng directly. function(""decodePng"", &decodePng); class_(""DecodedPng"") .property(""width"", &DecodedPng::width) .property(""height"", &DecodedPng::height) .property(""data"", &DecodedPng::decoded_data); class_(""SurfaceOrientation$Builder"") .constructor<>() .BUILDER_FUNCTION(""vertexCount"", SurfaceBuilder, (SurfaceBuilder* builder, size_t nverts), { return &builder->vertexCount(nverts); }) .BUILDER_FUNCTION(""normals"", SurfaceBuilder, (SurfaceBuilder* builder, intptr_t data, int stride), { return &builder->normals((const filament::math::float3*) data, stride); }) .BUILDER_FUNCTION(""tangents"", SurfaceBuilder, (SurfaceBuilder* builder, intptr_t data, int stride), { return &builder->tangents((const filament::math::float4*) data, stride); }) .BUILDER_FUNCTION(""uvs"", SurfaceBuilder, (SurfaceBuilder* builder, intptr_t data, int stride), { return &builder->uvs((const filament::math::float2*) data, stride); }) .BUILDER_FUNCTION(""positions"", SurfaceBuilder, (SurfaceBuilder* builder, intptr_t data, int stride), { return &builder->positions((const filament::math::float3*) data, stride); }) .BUILDER_FUNCTION(""triangleCount"", SurfaceBuilder, (SurfaceBuilder* builder, size_t n), { return &builder->triangleCount(n); }) .BUILDER_FUNCTION(""triangles16"", SurfaceBuilder, (SurfaceBuilder* builder, intptr_t data), { return &builder->triangles((filament::math::ushort3*) data); }) .BUILDER_FUNCTION(""triangles32"", SurfaceBuilder, (SurfaceBuilder* builder, intptr_t data), { return &builder->triangles((filament::math::uint3*) data); }) .function(""_build"", EMBIND_LAMBDA(SurfaceOrientation*, (SurfaceBuilder* builder), { return new SurfaceOrientation(builder->build()); }), allow_raw_pointers()); class_(""SurfaceOrientation"") .function(""getQuats"", EMBIND_LAMBDA(void, (SurfaceOrientation* self, intptr_t out, size_t quatCount, VertexBuffer::AttributeType attrtype), { switch (attrtype) { case VertexBuffer::AttributeType::FLOAT4: { self->getQuats((filament::math::quatf*) out, quatCount); break; } case VertexBuffer::AttributeType::HALF4: { self->getQuats((filament::math::quath*) out, quatCount); break; } case VertexBuffer::AttributeType::SHORT4: { self->getQuats((filament::math::short4*) out, quatCount); break; } default: utils::slog.e << ""Unsupported quaternion type."" << utils::io::endl; } }), allow_raw_pointers()); class_(""gltfio$Animator"") .function(""applyAnimation"", &Animator::applyAnimation) .function(""updateBoneMatrices"", &Animator::updateBoneMatrices) .function(""getAnimationCount"", &Animator::getAnimationCount) .function(""getAnimationDuration"", &Animator::getAnimationDuration) .function(""getAnimationName"", EMBIND_LAMBDA(std::string, (Animator* self, size_t index), { return std::string(self->getAnimationName(index)); }), allow_raw_pointers()); class_(""gltfio$FilamentAsset"") .function(""getEntities"", EMBIND_LAMBDA(std::vector, (FilamentAsset* self), { const utils::Entity* ptr = self->getEntities(); return std::vector(ptr, ptr + self->getEntityCount()); }), allow_raw_pointers()) .function(""getRoot"", &FilamentAsset::getRoot) .function(""getMaterialInstances"", EMBIND_LAMBDA(std::vector, (FilamentAsset* self), { const filament::MaterialInstance* const* ptr = self->getMaterialInstances(); return std::vector(ptr, ptr + self->getMaterialInstanceCount()); }), allow_raw_pointers()) .function(""getResourceUris"", EMBIND_LAMBDA(std::vector, (FilamentAsset* self), { std::vector retval; auto uris = self->getResourceUris(); for (size_t i = 0, len = self->getResourceUriCount(); i < len; ++i) { retval.push_back(uris[i]); } return retval; }), allow_raw_pointers()) .function(""getBoundingBox"", &FilamentAsset::getBoundingBox) .function(""getName"", EMBIND_LAMBDA(std::string, (FilamentAsset* self, utils::Entity entity), { return std::string(self->getName(entity)); }), allow_raw_pointers()) .function(""getAnimator"", &FilamentAsset::getAnimator, allow_raw_pointers()) .function(""getWireframe"", &FilamentAsset::getWireframe) .function(""getEngine"", &FilamentAsset::getEngine, allow_raw_pointers()) .function(""releaseSourceData"", &FilamentAsset::releaseSourceData); // This little wrapper exists to get around RTTI requirements in embind. struct UbershaderLoader { MaterialProvider* provider; void destroyMaterials() { provider->destroyMaterials(); } }; class_(""gltfio$UbershaderLoader"") .constructor(EMBIND_LAMBDA(UbershaderLoader, (Engine* engine), { return UbershaderLoader { createUbershaderLoader(engine) }; })) .function(""destroyMaterials"", &UbershaderLoader::destroyMaterials); class_(""gltfio$AssetLoader"") .constructor(EMBIND_LAMBDA(AssetLoader*, (Engine* engine, UbershaderLoader materials), { auto names = new utils::NameComponentManager(utils::EntityManager::get()); return AssetLoader::create({ engine, materials.provider, names }); }), allow_raw_pointers()) /// createAssetFromJson ::static method:: /// buffer ::argument:: asset string, or Uint8Array, or [Buffer] /// ::retval:: an instance of [FilamentAsset] .function(""_createAssetFromJson"", EMBIND_LAMBDA(FilamentAsset*, (AssetLoader* self, BufferDescriptor buffer), { return self->createAssetFromJson((const uint8_t*) buffer.bd->buffer, buffer.bd->size); }), allow_raw_pointers()) /// createAssetFroBinary ::static method:: /// buffer ::argument:: asset string, or Uint8Array, or [Buffer] /// ::retval:: an instance of [FilamentAsset] .function(""_createAssetFromBinary"", EMBIND_LAMBDA(FilamentAsset*, (AssetLoader* self, BufferDescriptor buffer), { return self->createAssetFromBinary((const uint8_t*) buffer.bd->buffer, buffer.bd->size); }), allow_raw_pointers()); class_(""gltfio$ResourceLoader"") .constructor(EMBIND_LAMBDA(ResourceLoader*, (Engine* engine), { return new ResourceLoader({ .engine = engine, .gltfPath = utils::Path(), .normalizeSkinningWeights = true, .recomputeBoundingBoxes = true }); }), allow_raw_pointers()) .function(""addResourceData"", EMBIND_LAMBDA(void, (ResourceLoader* self, std::string url, BufferDescriptor buffer), { self->addResourceData(url, std::move(*buffer.bd)); }), allow_raw_pointers()) .function(""loadResources"", &ResourceLoader::loadResources, allow_raw_pointers()); } // EMSCRIPTEN_BINDINGS ",16357,True,3331.63878801197,median "[id=""machineset-machine-openshift-io-v1beta1""] = MachineSet [machine.openshift.io/v1beta1] ifdef::product-title[] include::modules/common-attributes.adoc[] endif::[] toc::[] Description:: / [MachineSet] MachineSet ensures that a specified number of machines replicas are running at any given time. Type:: `object` == Specification [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `.apiVersion` | `string` | APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources | `.kind` | `string` | Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds | `.metadata` | xref:../objects/index.adoc#objectmeta-meta-v1[`ObjectMeta meta/v1`] | Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata | `.spec` | `object` | / [MachineSetSpec] MachineSetSpec defines the desired state of MachineSet | `.status` | `object` | / [MachineSetStatus] MachineSetStatus defines the observed state of MachineSet |=== ..spec Description:: / [MachineSetSpec] MachineSetSpec defines the desired state of MachineSet Type:: `object` Required:: - `selector` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `deletePolicy` | `string` | DeletePolicy defines the policy used to identify nodes to delete when downscaling. Defaults to ""Random"". Valid values are ""Random, ""Newest"", ""Oldest"" | `minReadySeconds` | `integer` | MinReadySeconds is the minimum number of seconds for which a newly created machine should be ready. Defaults to 0 (machine will be considered available as soon as it is ready) | `replicas` | `integer` | Replicas is the number of desired replicas. This is a pointer to distinguish between explicit zero and unspecified. Defaults to 1. | `selector` | `object` | Selector is a label query over machines that should match the replica count. Label keys and values that must match in order to be controlled by this MachineSet. It must match the machine template's labels. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors | `template` | `object` | Template is the object that describes the machine that will be created if insufficient replicas are detected. |=== ..spec.selector Description:: Selector is a label query over machines that should match the replica count. Label keys and values that must match in order to be controlled by this MachineSet. It must match the machine template's labels. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `matchExpressions` | `array` | matchExpressions is a list of label selector requirements. The requirements are ANDed. | `matchExpressions[]` | `object` | A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values. | `matchLabels` | `object (string)` | matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is ""key"", the operator is ""In"", and the values array contains only ""value"". The requirements are ANDed. |=== ..spec.selector.matchExpressions Description:: matchExpressions is a list of label selector requirements. The requirements are ANDed. Type:: `array` ..spec.selector.matchExpressions[] Description:: A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values. Type:: `object` Required:: - `key` - `operator` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `key` | `string` | key is the label key that the selector applies to. | `operator` | `string` | operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist. | `values` | `array (string)` | values is an array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. This array is replaced during a strategic merge patch. |=== ..spec.template Description:: Template is the object that describes the machine that will be created if insufficient replicas are detected. Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `metadata` | `object` | Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata | `spec` | `object` | Specification of the desired behavior of the machine. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status |=== ..spec.template.metadata Description:: Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `annotations` | `object (string)` | Annotations is an unstructured key value map stored with a resource that may be set by external tools to store and retrieve arbitrary metadata. They are not queryable and should be preserved when modifying objects. More info: http://kubernetes.io/docs/user-guide/annotations | `generateName` | `string` | GenerateName is an optional prefix, used by the server, to generate a unique name ONLY IF the Name field has not been provided. If this field is used, the name returned to the client will be different than the name passed. This value will also be combined with a unique suffix. The provided value has the same validation rules as the Name field, and may be truncated by the length of the suffix required to make the value unique on the server. If this field is specified and the generated name exists, the server will NOT return a 409 - instead, it will either return 201 Created or 500 with Reason ServerTimeout indicating a unique name could not be found in the time allotted, and the client should retry (optionally after the time indicated in the Retry-After header). Applied only if Name is not specified. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#idempotency | `labels` | `object (string)` | Map of string keys and values that can be used to organize and categorize (scope and select) objects. May match selectors of replication controllers and services. More info: http://kubernetes.io/docs/user-guide/labels | `name` | `string` | Name must be unique within a namespace. Is required when creating resources, although some resources may allow a client to request the generation of an appropriate name automatically. Name is primarily intended for creation idempotence and configuration definition. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/identifiers#names | `namespace` | `string` | Namespace defines the space within each name must be unique. An empty namespace is equivalent to the ""default"" namespace, but ""default"" is the canonical representation. Not all objects are required to be scoped to a namespace - the value of this field for those objects will be empty. Must be a DNS_LABEL. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/namespaces | `ownerReferences` | `array` | List of objects depended by this object. If ALL objects in the list have been deleted, this object will be garbage collected. If this object is managed by a controller, then an entry in this list will point to this controller, with the controller field set to true. There cannot be more than one managing controller. | `ownerReferences[]` | `object` | OwnerReference contains enough information to let you identify an owning object. An owning object must be in the same namespace as the dependent, or be cluster-scoped, so there is no namespace field. |=== ..spec.template.metadata.ownerReferences Description:: List of objects depended by this object. If ALL objects in the list have been deleted, this object will be garbage collected. If this object is managed by a controller, then an entry in this list will point to this controller, with the controller field set to true. There cannot be more than one managing controller. Type:: `array` ..spec.template.metadata.ownerReferences[] Description:: OwnerReference contains enough information to let you identify an owning object. An owning object must be in the same namespace as the dependent, or be cluster-scoped, so there is no namespace field. Type:: `object` Required:: - `apiVersion` - `kind` - `name` - `uid` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `apiVersion` | `string` | API version of the referent. | `blockOwnerDeletion` | `boolean` | If true, AND if the owner has the ""foregroundDeletion"" finalizer, then the owner cannot be deleted from the key-value store until this reference is removed. Defaults to false. To set this field, a user needs ""delete"" permission of the owner, otherwise 422 (Unprocessable Entity) will be returned. | `controller` | `boolean` | If true, this reference points to the managing controller. | `kind` | `string` | Kind of the referent. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds | `name` | `string` | Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names | `uid` | `string` | UID of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#uids |=== ..spec.template.spec Description:: Specification of the desired behavior of the machine. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `metadata` | `object` | ObjectMeta will autopopulate the Node created. Use this to indicate what labels, annotations, name prefix, etc., should be used when creating the Node. | `providerID` | `string` | ProviderID is the identification ID of the machine provided by the provider. This field must match the provider ID as seen on the node object corresponding to this machine. This field is required by higher level consumers of cluster-api. Example use case is cluster autoscaler with cluster-api as provider. Clean-up logic in the autoscaler compares machines to nodes to find out machines at provider which could not get registered as Kubernetes nodes. With cluster-api as a generic out-of-tree provider for autoscaler, this field is required by autoscaler to be able to have a provider view of the list of machines. Another list of nodes is queried from the k8s apiserver and then a comparison is done to find out unregistered machines and are marked for delete. This field will be set by the actuators and consumed by higher level entities like autoscaler that will be interfacing with cluster-api as generic provider. | `providerSpec` | `object` | ProviderSpec details Provider-specific configuration to use during node creation. | `taints` | `array` | The list of the taints to be applied to the corresponding Node in additive manner. This list will not overwrite any other taints added to the Node on an ongoing basis by other entities. These taints should be actively reconciled e.g. if you ask the machine controller to apply a taint and then manually remove the taint the machine controller will put it back) but not have the machine controller remove any taints | `taints[]` | `object` | The node this Taint is attached to has the ""effect"" on any pod that does not tolerate the Taint. |=== ..spec.template.spec.metadata Description:: ObjectMeta will autopopulate the Node created. Use this to indicate what labels, annotations, name prefix, etc., should be used when creating the Node. Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `annotations` | `object (string)` | Annotations is an unstructured key value map stored with a resource that may be set by external tools to store and retrieve arbitrary metadata. They are not queryable and should be preserved when modifying objects. More info: http://kubernetes.io/docs/user-guide/annotations | `generateName` | `string` | GenerateName is an optional prefix, used by the server, to generate a unique name ONLY IF the Name field has not been provided. If this field is used, the name returned to the client will be different than the name passed. This value will also be combined with a unique suffix. The provided value has the same validation rules as the Name field, and may be truncated by the length of the suffix required to make the value unique on the server. If this field is specified and the generated name exists, the server will NOT return a 409 - instead, it will either return 201 Created or 500 with Reason ServerTimeout indicating a unique name could not be found in the time allotted, and the client should retry (optionally after the time indicated in the Retry-After header). Applied only if Name is not specified. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#idempotency | `labels` | `object (string)` | Map of string keys and values that can be used to organize and categorize (scope and select) objects. May match selectors of replication controllers and services. More info: http://kubernetes.io/docs/user-guide/labels | `name` | `string` | Name must be unique within a namespace. Is required when creating resources, although some resources may allow a client to request the generation of an appropriate name automatically. Name is primarily intended for creation idempotence and configuration definition. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/identifiers#names | `namespace` | `string` | Namespace defines the space within each name must be unique. An empty namespace is equivalent to the ""default"" namespace, but ""default"" is the canonical representation. Not all objects are required to be scoped to a namespace - the value of this field for those objects will be empty. Must be a DNS_LABEL. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/namespaces | `ownerReferences` | `array` | List of objects depended by this object. If ALL objects in the list have been deleted, this object will be garbage collected. If this object is managed by a controller, then an entry in this list will point to this controller, with the controller field set to true. There cannot be more than one managing controller. | `ownerReferences[]` | `object` | OwnerReference contains enough information to let you identify an owning object. An owning object must be in the same namespace as the dependent, or be cluster-scoped, so there is no namespace field. |=== ..spec.template.spec.metadata.ownerReferences Description:: List of objects depended by this object. If ALL objects in the list have been deleted, this object will be garbage collected. If this object is managed by a controller, then an entry in this list will point to this controller, with the controller field set to true. There cannot be more than one managing controller. Type:: `array` ..spec.template.spec.metadata.ownerReferences[] Description:: OwnerReference contains enough information to let you identify an owning object. An owning object must be in the same namespace as the dependent, or be cluster-scoped, so there is no namespace field. Type:: `object` Required:: - `apiVersion` - `kind` - `name` - `uid` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `apiVersion` | `string` | API version of the referent. | `blockOwnerDeletion` | `boolean` | If true, AND if the owner has the ""foregroundDeletion"" finalizer, then the owner cannot be deleted from the key-value store until this reference is removed. Defaults to false. To set this field, a user needs ""delete"" permission of the owner, otherwise 422 (Unprocessable Entity) will be returned. | `controller` | `boolean` | If true, this reference points to the managing controller. | `kind` | `string` | Kind of the referent. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds | `name` | `string` | Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names | `uid` | `string` | UID of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#uids |=== ..spec.template.spec.providerSpec Description:: ProviderSpec details Provider-specific configuration to use during node creation. Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `value` | `object` | Value is an inlined, serialized representation of the resource configuration. It is recommended that providers maintain their own versioned API types that should be serialized/deserialized from this field, akin to component config. |=== ..spec.template.spec.providerSpec.value Description:: Value is an inlined, serialized representation of the resource configuration. It is recommended that providers maintain their own versioned API types that should be serialized/deserialized from this field, akin to component config. Type:: `object` ..spec.template.spec.taints Description:: The list of the taints to be applied to the corresponding Node in additive manner. This list will not overwrite any other taints added to the Node on an ongoing basis by other entities. These taints should be actively reconciled e.g. if you ask the machine controller to apply a taint and then manually remove the taint the machine controller will put it back) but not have the machine controller remove any taints Type:: `array` ..spec.template.spec.taints[] Description:: The node this Taint is attached to has the "effect" on any pod that does not tolerate the Taint. Type:: `object` Required:: - `effect` - `key` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `effect` | `string` | Required. The effect of the taint on pods that do not tolerate the taint. Valid effects are NoSchedule, PreferNoSchedule and NoExecute. | `key` | `string` | Required. The taint key to be applied to a node. | `timeAdded` | `string` | TimeAdded represents the time at which the taint was added. It is only written for NoExecute taints. | `value` | `string` | The taint value corresponding to the taint key. |=== ..status Description:: / [MachineSetStatus] MachineSetStatus defines the observed state of MachineSet Type:: `object` Required:: - `replicas` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `availableReplicas` | `integer` | The number of available replicas (ready for at least minReadySeconds) for this MachineSet. | `errorMessage` | `string` | | `errorReason` | `string` | In the event that there is a terminal problem reconciling the replicas, both ErrorReason and ErrorMessage will be set. ErrorReason will be populated with a succinct value suitable for machine interpretation, while ErrorMessage will contain a more verbose string suitable for logging and human consumption. These fields should not be set for transitive errors that a controller faces that are expected to be fixed automatically over time (like service outages), but instead indicate that something is fundamentally wrong with the MachineTemplate's spec or the configuration of the machine controller, and that manual intervention is required. Examples of terminal errors would be invalid combinations of settings in the spec, values that are unsupported by the machine controller, or the responsible machine controller itself being critically misconfigured. Any transient errors that occur during the reconciliation of Machines can be added as events to the MachineSet object and/or logged in the controller's output. | `fullyLabeledReplicas` | `integer` | The number of replicas that have labels matching the labels of the machine template of the MachineSet. | `observedGeneration` | `integer` | ObservedGeneration reflects the generation of the most recently observed MachineSet. | `readyReplicas` | `integer` | The number of ready replicas for this MachineSet. A machine is considered ready when the node has been created and is ""Ready"". | `replicas` | `integer` | Replicas is the most recently observed number of replicas. |=== == API endpoints The following API endpoints are available: * `/apis/machine.openshift.io/v1beta1/machinesets` - `GET`: list objects of kind MachineSet * `/apis/machine.openshift.io/v1beta1/namespaces/{namespace}/machinesets` - `DELETE`: delete collection of MachineSet - `GET`: list objects of kind MachineSet - `POST`: create a MachineSet * `/apis/machine.openshift.io/v1beta1/namespaces/{namespace}/machinesets/{name}` - `DELETE`: delete a MachineSet - `GET`: read the specified MachineSet - `PATCH`: partially update the specified MachineSet - `PUT`: replace the specified MachineSet * `/apis/machine.openshift.io/v1beta1/namespaces/{namespace}/machinesets/{name}/scale` - `GET`: read scale of the specified MachineSet - `PATCH`: partially update scale of the specified MachineSet - `PUT`: replace scale of the specified MachineSet * `/apis/machine.openshift.io/v1beta1/namespaces/{namespace}/machinesets/{name}/status` - `GET`: read status of the specified MachineSet - `PATCH`: partially update status of the specified MachineSet - `PUT`: replace status of the specified MachineSet === /apis/machine.openshift.io/v1beta1/machinesets .Global guery parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `allowWatchBookmarks` | `boolean` | allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. If the feature gate WatchBookmarks is not enabled in apiserver, this field is ignored. | `continue` | `string` | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. | `pretty` | `string` | If 'true', then the output is pretty printed. | `resourceVersion` | `string` | When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. | `watch` | `boolean` | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== HTTP method:: `GET` Description:: list objects of kind MachineSet .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#machinesetlist-machine-openshift-io-v1beta1[`MachineSetList machine.openshift.io/v1beta1`] | 401 - Unauthorized | Empty |=== === /apis/machine.openshift.io/v1beta1/namespaces/{namespace}/machinesets .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global guery parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `DELETE` Description:: delete collection of MachineSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `allowWatchBookmarks` | `boolean` | allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. If the feature gate WatchBookmarks is not enabled in apiserver, this field is ignored. | `continue` | `string` | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. | `resourceVersion` | `string` | When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. | `watch` | `boolean` | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#status-meta-v1[`Status meta/v1`] | 401 - Unauthorized | Empty |=== HTTP method:: `GET` Description:: list objects of kind MachineSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `allowWatchBookmarks` | `boolean` | allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. If the feature gate WatchBookmarks is not enabled in apiserver, this field is ignored. | `continue` | `string` | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. | `resourceVersion` | `string` | When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. | `watch` | `boolean` | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#machinesetlist-machine-openshift-io-v1beta1[`MachineSetList machine.openshift.io/v1beta1`] | 401 - Unauthorized | Empty |=== HTTP method:: `POST` Description:: create a MachineSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../machine_apis/machineset-machine-openshift-io-v1beta1.adoc#machineset-machine-openshift-io-v1beta1[`MachineSet machine.openshift.io/v1beta1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../machine_apis/machineset-machine-openshift-io-v1beta1.adoc#machineset-machine-openshift-io-v1beta1[`MachineSet machine.openshift.io/v1beta1`] | 201 - Created | xref:../machine_apis/machineset-machine-openshift-io-v1beta1.adoc#machineset-machine-openshift-io-v1beta1[`MachineSet machine.openshift.io/v1beta1`] | 202 - Accepted | xref:../machine_apis/machineset-machine-openshift-io-v1beta1.adoc#machineset-machine-openshift-io-v1beta1[`MachineSet machine.openshift.io/v1beta1`] | 401 - Unauthorized | Empty |=== === /apis/machine.openshift.io/v1beta1/namespaces/{namespace}/machinesets/{name} .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the MachineSet | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global guery parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `DELETE` Description:: delete a MachineSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `gracePeriodSeconds` | `integer` | The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. | `orphanDependents` | `boolean` | Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. | `propagationPolicy` | `string` | Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#deleteoptions-meta-v1[`DeleteOptions meta/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#status-meta-v1[`Status meta/v1`] | 202 - Accepted | xref:../objects/index.adoc#status-meta-v1[`Status meta/v1`] | 401 - Unauthorized | Empty |=== HTTP method:: `GET` Description:: read the specified MachineSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `resourceVersion` | `string` | When specified: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../machine_apis/machineset-machine-openshift-io-v1beta1.adoc#machineset-machine-openshift-io-v1beta1[`MachineSet machine.openshift.io/v1beta1`] | 401 - Unauthorized | Empty |=== HTTP method:: `PATCH` Description:: partially update the specified MachineSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#patch-meta-v1[`Patch meta/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../machine_apis/machineset-machine-openshift-io-v1beta1.adoc#machineset-machine-openshift-io-v1beta1[`MachineSet machine.openshift.io/v1beta1`] | 401 - Unauthorized | Empty |=== HTTP method:: `PUT` Description:: replace the specified MachineSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../machine_apis/machineset-machine-openshift-io-v1beta1.adoc#machineset-machine-openshift-io-v1beta1[`MachineSet machine.openshift.io/v1beta1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../machine_apis/machineset-machine-openshift-io-v1beta1.adoc#machineset-machine-openshift-io-v1beta1[`MachineSet machine.openshift.io/v1beta1`] | 201 - Created | xref:../machine_apis/machineset-machine-openshift-io-v1beta1.adoc#machineset-machine-openshift-io-v1beta1[`MachineSet machine.openshift.io/v1beta1`] | 401 - Unauthorized | Empty |=== === /apis/machine.openshift.io/v1beta1/namespaces/{namespace}/machinesets/{name}/scale .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the MachineSet | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global guery parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `GET` Description:: read scale of the specified MachineSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `resourceVersion` | `string` | When specified: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#scale-autoscaling-v1[`Scale autoscaling/v1`] | 401 - Unauthorized | Empty |=== HTTP method:: `PATCH` Description:: partially update scale of the specified MachineSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#patch-meta-v1[`Patch meta/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#scale-autoscaling-v1[`Scale autoscaling/v1`] | 401 - Unauthorized | Empty |=== HTTP method:: `PUT` Description:: replace scale of the specified MachineSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#scale-autoscaling-v1[`Scale autoscaling/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#scale-autoscaling-v1[`Scale autoscaling/v1`] | 201 - Created | xref:../objects/index.adoc#scale-autoscaling-v1[`Scale autoscaling/v1`] | 401 - Unauthorized | Empty |=== === /apis/machine.openshift.io/v1beta1/namespaces/{namespace}/machinesets/{name}/status .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the MachineSet | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global guery parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `GET` Description:: read status of the specified MachineSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `resourceVersion` | `string` | When specified: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../machine_apis/machineset-machine-openshift-io-v1beta1.adoc#machineset-machine-openshift-io-v1beta1[`MachineSet machine.openshift.io/v1beta1`] | 401 - Unauthorized | Empty |=== HTTP method:: `PATCH` Description:: partially update status of the specified MachineSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#patch-meta-v1[`Patch meta/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../machine_apis/machineset-machine-openshift-io-v1beta1.adoc#machineset-machine-openshift-io-v1beta1[`MachineSet machine.openshift.io/v1beta1`] | 401 - Unauthorized | Empty |=== HTTP method:: `PUT` Description:: replace status of the specified MachineSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../machine_apis/machineset-machine-openshift-io-v1beta1.adoc#machineset-machine-openshift-io-v1beta1[`MachineSet machine.openshift.io/v1beta1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../machine_apis/machineset-machine-openshift-io-v1beta1.adoc#machineset-machine-openshift-io-v1beta1[`MachineSet machine.openshift.io/v1beta1`] | 201 - Created | xref:../machine_apis/machineset-machine-openshift-io-v1beta1.adoc#machineset-machine-openshift-io-v1beta1[`MachineSet machine.openshift.io/v1beta1`] | 401 - Unauthorized | Empty |=== ",12315,False,2470.311347302672,median "/******************************************************************************* * Copyright 2019-2020 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include ""common/c_types_map.hpp"" #include ""common/memory.hpp"" #include ""common/memory_tracking.hpp"" #include ""common/nstl.hpp"" #include ""common/type_helpers.hpp"" #include ""common/utils.hpp"" #include ""cpu/x64/jit_uni_x8s8s32x_conv_kernel.hpp"" #define GET_OFF(field) offsetof(jit_conv_call_s, field) namespace dnnl { namespace impl { namespace cpu { namespace x64 { using namespace dnnl::impl::memory_tracking::names; using namespace dnnl::impl::utils; using namespace Xbyak; namespace { void pick_loop_order(jit_conv_conf_t &jcp) { jcp.loop_order = loop_cwgn; if (jcp.ngroups > 1) { jcp.loop_order = loop_ngcw; if (jcp.mb < jcp.nthr && jcp.ndims != 5) jcp.loop_order = jcp.ndims == 3 ? loop_nwcg : loop_nhwcg; } else if (jcp.mb >= jcp.nthr && jcp.ic_without_padding <= 8) { jcp.loop_order = loop_ngcw; } } } // namespace template void _jit_uni_x8s8s32x_fwd_kernel::prepare_output(int ur_w) { int nb_oc_block = jcp.is_depthwise ? jcp.nb_ch_blocking : jcp.nb_oc_blocking; for (int k = 0; k < nb_oc_block; ++k) for (int j = 0; j < ur_w; ++j) { Vmm vmm = vmm_out(j, k); uni_vpxor(vmm, vmm, vmm); } if (jcp.signed_input) { auto xmm_shift = Xbyak::Xmm(vmm_shift.getIdx()); if (jcp.is_depthwise) mov(reg_scratch, 128); else mov(reg_scratch, 0x80808080); uni_vmovq(xmm_shift, reg_scratch); uni_vpbroadcastd(vmm_shift, xmm_shift); } } template void _jit_uni_x8s8s32x_fwd_kernel::cvt2ps(data_type_t type_in, const Vmm &vmm_in, const Reg64 ®, int offset, int load_size) { load_data(type_in, vmm_in, reg, offset, load_size); if (type_in != data_type::f32) uni_vcvtdq2ps(vmm_in, vmm_in); } template void _jit_uni_x8s8s32x_fwd_kernel::store_output( int ur_w, bool last_oc_block_flag) { int nb_oc_block = jcp.is_depthwise ? jcp.nb_ch_blocking : jcp.nb_oc_blocking; int oc_block = jcp.is_depthwise ? jcp.ch_block : jcp.oc_block; mov(reg_bias, ptr[param1 + GET_OFF(bias)]); mov(reg_ptr_scales, ptr[param1 + GET_OFF(scales)]); if (jcp.signed_input || jcp.with_input_zp) mov(reg_compensation, ptr[param1 + GET_OFF(compensation)]); const auto &p = attr_.post_ops_; const int sum_idx = p.find(primitive_kind::sum); const float *p_sum_scale = nullptr; if (sum_idx != -1) { const auto &p_entry = p.entry_[sum_idx]; p_sum_scale = &p_entry.sum.scale; } if (p_sum_scale && *p_sum_scale != 1.f) mov(reg_ptr_sum_scale, (size_t)p_sum_scale); if (jcp.signed_input && jcp.ver != ver_vnni) { /* put 'wei_adj_scale = 0.5' for bias calculation */ mov(reg_bias_alpha, float2int(jcp.wei_adj_scale)); uni_vmovq(xmm_bias_alpha(), reg_bias_alpha); uni_vbroadcastss(vmm_bias_alpha(), xmm_bias_alpha()); } for (int k = 0; k < nb_oc_block; ++k) { const bool mask_flag = last_oc_block_flag && k == nb_oc_block - 1; int scale_offset = jcp.is_oc_scale * (sizeof(float) * k * oc_block); if (jcp.with_bias) { int bias_offset = jcp.typesize_bia * k * oc_block; cvt2ps(jcp.bia_dt, vmm_bias, reg_bias, bias_offset, mask_flag ? get_tail_size() : get_blocking_size()); if (jcp.signed_input && jcp.ver != ver_vnni) /* bias *= 0.5 */ uni_vmulps(vmm_bias, vmm_bias, vmm_bias_alpha()); } if (jcp.signed_input || jcp.with_input_zp) { int comp_offset = sizeof(int32_t) * k * oc_block; cvt2ps(data_type::s32, vmm_comp, reg_compensation, comp_offset, mask_flag ? get_tail_size() : get_blocking_size()); } /* add to ymm_accum: compensation, bias and permute */ if (mask_flag) { uni_vpxor(vmm_scale, vmm_scale, vmm_scale); load_data(data_type::s32, vmm_scale, reg_ptr_scales, scale_offset, get_tail_size()); } else { uni_vmovups(vmm_scale, ptr[reg_ptr_scales + scale_offset]); } for (int j = 0; j < ur_w; ++j) { Vmm vmm = vmm_out(j, k); uni_vcvtdq2ps(vmm, vmm); if (jcp.signed_input || jcp.with_input_zp) uni_vaddps(vmm, vmm, vmm_comp); if (jcp.with_bias) uni_vaddps(vmm, vmm, vmm_bias); uni_vmulps(vmm, vmm, vmm_scale); } } /* Do post-ops */ int eltwise_inj_idx = 0; int depthwise_inj_idx = 0; int quantization_inj_idx = 0; for (int i = 0; i < p.len(); i++) { auto& post_op = p.entry_[i]; if (post_op.is_eltwise()) { size_t s_idx = vmm_out(ur_w - 1, nb_oc_block - 1).getIdx(); size_t e_idx = vmm_out(0, 0).getIdx() + 1; eltwise_injectors[eltwise_inj_idx]->compute_vector_range(s_idx, e_idx); eltwise_inj_idx++; } else if (post_op.is_depthwise()) { mov(reg_d_weights, reinterpret_cast(post_op.depthwise.weights_data)); mov(reg_d_bias, reinterpret_cast(post_op.depthwise.biases_data)); add(reg_d_weights, ptr[param1 + GET_OFF(oc_off)]); add(reg_d_bias, ptr[param1 + GET_OFF(oc_off)]); for (int k = 0; k < nb_oc_block; k++) { int s_idx = vmm_out(ur_w - 1, k).getIdx(); int e_idx = vmm_out(0, k).getIdx() + 1; depthwise_injectors[depthwise_inj_idx]->compute_vector_range(s_idx, e_idx, reg_d_weights, reg_d_bias); add(reg_d_weights, oc_block * sizeof(float)); add(reg_d_bias, oc_block * sizeof(float)); } depthwise_inj_idx++; } else if (post_op.is_quantization()) { bool do_dequantization = post_op.quantization.alg == alg_kind::quantization_quantize_dequantize; bool do_rounding = do_dequantization || jcp.dst_dt == dnnl_f32 || i != p.len() - 1; quantization_injectors[quantization_inj_idx]->init_crop_ptrs(ptr[param1 + GET_OFF(oc_off)]); for (int k = 0; k < nb_oc_block; k++) { int s_idx = vmm_out(ur_w - 1, k).getIdx(); int e_idx = vmm_out(0, k).getIdx() + 1; quantization_injectors[quantization_inj_idx]->compute_crop(s_idx, e_idx, k * oc_block * sizeof(float)); } quantization_injectors[quantization_inj_idx]->init_input_scale_shift_ptrs(ptr[param1 + GET_OFF(oc_off)]); for (int k = 0; k < nb_oc_block; k++) { int s_idx = vmm_out(ur_w - 1, k).getIdx(); int e_idx = vmm_out(0, k).getIdx() + 1; quantization_injectors[quantization_inj_idx]->compute_input_scale_shift(s_idx, e_idx, k * oc_block * sizeof(float), do_rounding); } quantization_injectors[quantization_inj_idx]->init_output_scale_shift_ptrs(ptr[param1 + GET_OFF(oc_off)]); for (int k = 0; k < nb_oc_block; k++) { int s_idx = vmm_out(ur_w - 1, k).getIdx(); int e_idx = vmm_out(0, k).getIdx() + 1; quantization_injectors[quantization_inj_idx]->compute_output_scale_shift(s_idx, e_idx, k * oc_block * sizeof(float)); } quantization_inj_idx++; } else if (post_op.is_sum(false)) { for (int k = 0; k < nb_oc_block; k++) { const bool mask_flag = last_oc_block_flag && k == nb_oc_block - 1; for (int j = 0; j < ur_w; j++) { int aux_output_offset = jcp.typesize_out * (k * oc_block + j * jcp.oc_without_padding * jcp.ngroups); cvt2ps(post_op.sum.dt, vmm_prev_dst, reg_out, aux_output_offset, mask_flag ? get_tail_size() : get_blocking_size()); Vmm vmm = vmm_out(j, k); if (*p_sum_scale == 1.f) uni_vaddps(vmm, vmm, vmm_prev_dst); else { uni_vbroadcastss(vmm_tmp, ptr[reg_ptr_sum_scale]); uni_vfmadd231ps(vmm, vmm_prev_dst, vmm_tmp); } } } } } // Properly saturate the accumulators for integer datatypes // No need to saturate on lower bound for signed integer types, as // the conversion to int would return INT_MIN, and then proper // saturation will happen in store_data if (jcp.dst_dt == data_type::u8) { uni_vpxor(vmm_zero, vmm_zero, vmm_zero); for (int k = 0; k < nb_oc_block; ++k) { for (int j = 0; j < ur_w; ++j) { Vmm vmm = vmm_out(j, k); uni_vmaxps(vmm, vmm, vmm_zero); } } } if (utils::one_of( jcp.dst_dt, data_type::u8, data_type::s8, data_type::s32)) { float saturation_ubound = types::max_value(jcp.dst_dt); Xmm xmm_saturation(vmm_saturation.getIdx()); mov(reg_ptr_saturation_ubound, float2int(saturation_ubound)); uni_vmovq(xmm_saturation, reg_ptr_saturation_ubound); uni_vbroadcastss(vmm_saturation, xmm_saturation); for (int k = 0; k < nb_oc_block; ++k) { for (int j = 0; j < ur_w; ++j) { Vmm vmm = vmm_out(j, k); uni_vminps(vmm, vmm, vmm_saturation); } } } // Convert float accumulators to int datatype if needed if (utils::one_of(jcp.dst_dt, data_type::u8, data_type::s8, data_type::s32)) for (int k = 0; k < nb_oc_block; ++k) for (int j = 0; j < ur_w; ++j) { Vmm vmm = vmm_out(j, k); uni_vcvtps2dq(vmm, vmm); } /* write out register to output_addr */ for (int k = 0; k < nb_oc_block; ++k) { const bool mask_flag = last_oc_block_flag && k == nb_oc_block - 1; for (int j = 0; j < ur_w; ++j) { Vmm r_vmm = vmm_out(j, k); int aux_output_offset = jcp.typesize_out * (k * oc_block + j * jcp.oc_without_padding * jcp.ngroups); store_data(jcp.dst_dt, r_vmm, reg_out, aux_output_offset, mask_flag ? get_tail_size() : get_blocking_size()); } } } template void _jit_uni_x8s8s32x_fwd_kernel::compute_ker_dw(int ur_w, int pad_l, int pad_r, ic_block_t last_ic_block_flag, bool h_padded) { if (!(utils::one_of(isa, avx2) && std::is_same::value) && !(utils::one_of(isa, sse41) && std::is_same::value)) assert(!""invalid group blocking for depthwise convolution""); auto input_spatial_index = [=](int oi, int ki) { return (ki * (jcp.dilate_w + 1) + oi * jcp.stride_w - pad_l); }; auto input_offset2 = [=](int ii, int ci) { if (jcp.is_fused_conv) return jcp.typesize_in * (ii * jcp.dw_conv_buffer_oc + ci * jcp.ch_block); else return jcp.typesize_in * (ii * jcp.ngroups + ci * jcp.ch_block); }; auto input_offset3 = [=](int oi, int ci, int ki) { return jcp.typesize_in * input_offset2(input_spatial_index(oi, ki), ci); }; auto kernel_offset = [=](int ci, int ki) { return jcp.typesize_in * ((ci * jcp.kd * jcp.kh * jcp.kw + ki) * jcp.ch_block); }; auto compute = [=](Vmm vreg_acc, Vmm vreg_wei, Vmm vreg_src) { if (jcp.ver == ver_vnni) { vpdpbusd(vreg_acc, vreg_src, vreg_wei, VexEncoding); } else { // okay for depthwise since src is zero-extended uni_vpmaddwd(vmm_dw_tmp, vreg_src, vreg_wei); uni_vpaddd(vreg_acc, vreg_acc, vmm_dw_tmp); } }; int ii_start = 0; int ii_end = -1; if (jcp.is_resrc_depthwise && !h_padded) { // find bounds of input spatial indices bool first = true; for (int ki = 0; ki < jcp.kw; ++ki) { int oi_start = get_ow_start(ki, pad_l); int oi_end = get_ow_end(ur_w, ki, pad_r); for (int oi = oi_start; oi < oi_end; ++oi) { int ii = input_spatial_index(oi, ki); if (first || ii < ii_start) ii_start = ii; if (first || ii > ii_end) ii_end = ii; first = false; } } } if (jcp.signed_input || jcp.with_input_zp) uni_vmovups(vmm_dw_shifted_zero, vmm_shift); for (int ci = 0; ci < jcp.nb_ch_blocking; ++ci) { if (jcp.with_input_zp && (h_padded || get_ow_start(0, pad_l) != 0 || get_ow_end(ur_w, jcp.kw-1, pad_r) != ur_w)) { load_data(data_type::u8, vmm_dw_shifted_zero, reg_input_zp, ci * jcp.ch_block, get_blocking_size()); } const bool mask_flag = last_ic_block_flag != no_last_block && ci == jcp.nb_ch_blocking - 1; if (jcp.is_resrc_depthwise && !h_padded) { // now we can load input once and reuse up to jcp.kw times for (int ii = ii_start; ii <= ii_end; ++ii) { int aux_input_offset = input_offset2(ii, ci); const Vmm vmm_inp_tmp = vmm_inp(ii, jcp.nb_ch_blocking); uni_vpxor(vmm_inp_tmp, vmm_inp_tmp, vmm_inp_tmp); load_data(data_type::u8, vmm_inp_tmp, aux_reg_inp, aux_input_offset, mask_flag ? get_tail_size() : get_blocking_size()); if (jcp.signed_input) uni_vpaddb(vmm_inp_tmp, vmm_inp_tmp, vmm_shift); } } for (int ki = 0; ki < jcp.kw; ++ki) { int aux_kernel_offset = kernel_offset(ci, ki); uni_vpmovsxbd(vmm_dw_wei, ptr[aux_reg_ker + aux_kernel_offset]); if (h_padded) { assert(jcp.signed_input || jcp.with_input_zp); for (int oi = 0; oi < ur_w; ++oi) compute(vmm_out(oi, ci), vmm_dw_wei, vmm_dw_shifted_zero); } else { int oi_start = get_ow_start(ki, pad_l); int oi_end = get_ow_end(ur_w, ki, pad_r); int start_ = (jcp.signed_input || jcp.with_input_zp) ? 0 : oi_start; int end_ = (jcp.signed_input || jcp.with_input_zp) ? ur_w : oi_end; for (int oi = start_; oi < end_; ++oi) { if (oi >= oi_start && oi < oi_end) { if (jcp.is_resrc_depthwise) { int ii = input_spatial_index(oi, ki); vmm_dw_src = vmm_inp(ii, jcp.nb_ch_blocking); } else { int aux_input_offset = input_offset3(oi, ci, ki); load_data(data_type::u8, vmm_dw_src, aux_reg_inp, aux_input_offset, mask_flag ? get_tail_size() : get_blocking_size()); if (jcp.signed_input) uni_vpaddb(vmm_dw_src, vmm_dw_src, vmm_shift); } compute(vmm_out(oi, ci), vmm_dw_wei, vmm_dw_src); } else { assert(jcp.signed_input || jcp.with_input_zp); compute(vmm_out(oi, ci), vmm_dw_wei, vmm_dw_shifted_zero); } } } } } } template void _jit_uni_x8s8s32x_fwd_kernel::compute_ker(int ur_w, int pad_l, int pad_r, ic_block_t last_ic_block_flag, bool h_padded) { if (jcp.is_depthwise) return compute_ker_dw(ur_w, pad_l, pad_r, last_ic_block_flag, h_padded); int kw = jcp.kw; int stride_w = jcp.stride_w; int ic_block = jcp.ic_block; int oc_block = jcp.oc_block; int ch_block_all = jcp.ch_block * ic_block * oc_block; int nb_oc_block = jcp.nb_oc_blocking; auto input_offset = [=](int oi, int ic, int ki) { return jcp.typesize_in * ((ki * (jcp.dilate_w + 1) + oi * stride_w - pad_l) * jcp.ic_without_padding * jcp.ngroups + ic_sub_step * ic); }; auto kernel_offset = [=](int ii, int ic, int ki) { return jcp.typesize_in * ((ii * jcp.nb_ic * jcp.kd * jcp.kh * jcp.kw + ki) * ch_block_all + ic_sub_step * ic * oc_block); }; auto compute = [=](Vmm vreg_acc, Vmm vreg_wei, Vmm vreg_src) { if (jcp.ver == ver_vnni) { vpdpbusd(vreg_acc, vreg_src, vreg_wei, VexEncoding); } else { uni_vpmaddubsw(vmm_tmp, vreg_src, vreg_wei); uni_vpmaddwd(vmm_tmp, vmm_tmp, vmm_one); uni_vpaddd(vreg_acc, vreg_acc, vmm_tmp); } }; for (int ki = 0; ki < kw; ++ki) { int ow_start = get_ow_start(ki, pad_l); int ow_end = get_ow_end(ur_w, ki, pad_r); int ic_tail_size = jcp.ic_without_padding % ic_sub_step; int _start = (jcp.signed_input || jcp.with_input_zp) ? 0 : ow_start; int _end = (jcp.signed_input || jcp.with_input_zp) ? ur_w : ow_end; /* Skip the last loads of input if (ic % 8) / ic_sub_step < ic_block / ic_sub_step */ int icb = (last_ic_block_flag != no_last_block) ? div_up((jcp.ic_without_padding % ic_block), ic_sub_step) : ic_block / ic_sub_step; for (int ic = 0; ic < icb; ++ic) { if (h_padded) { if (jcp.with_input_zp) uni_vpbroadcastd(vmm_shift, ptr[reg_input_zp + ic_sub_step * ic * sizeof(uint8_t)]); /* fill padded area with shifted values */ Vmm inp = vmm_inp(0, nb_oc_block); uni_vmovups(inp, vmm_shift); } else { for (int jj = _start; jj < _end; ++jj) { int aux_input_offset = input_offset(jj, ic, ki); if (jj >= ow_start && jj < ow_end) { const bool need_partial_ic_bcast = true && last_ic_block_flag == last_sp_block && ic_tail_size != 0 && ic == icb - 1; if (need_partial_ic_bcast) { const auto inp_bcastd_vmm = vmm_inp(jj, nb_oc_block); load_bytes(inp_bcastd_vmm, aux_reg_inp, aux_input_offset, ic_tail_size, isa == sse41); auto inp_bcastd = Xmm(inp_bcastd_vmm.getIdx()); uni_vpbroadcastd( vmm_inp(jj, nb_oc_block), inp_bcastd); } else { uni_vpbroadcastd(vmm_inp(jj, nb_oc_block), ptr[aux_reg_inp + aux_input_offset]); } if (jcp.signed_input) uni_vpaddb(vmm_inp(jj, nb_oc_block), vmm_inp(jj, nb_oc_block), vmm_shift); } else { /* fill padded area with shifted values */ if (jcp.signed_input || jcp.with_input_zp) { if (jcp.with_input_zp) uni_vpbroadcastd(vmm_shift, ptr[reg_input_zp + 4 * ic * sizeof(uint8_t)]); Vmm inp = vmm_inp(jj, nb_oc_block); uni_vmovups(inp, vmm_shift); } } } } for (int ii = 0; ii < nb_oc_block; ++ii) { int aux_kernel_offset = kernel_offset(ii, ic, ki); uni_vmovdqu(vmm_wei, ptr[aux_reg_ker + aux_kernel_offset]); for (int jj = _start; jj < _end; ++jj) { Vmm inp = vmm_inp(h_padded ? 0 : jj, nb_oc_block); compute(vmm_out(jj, ii), vmm_wei, inp); } } } } } template void _jit_uni_x8s8s32x_fwd_kernel::kh_loop( int ur_w, int pad_l, int pad_r, ic_block_t last_ic_block_flag) { Label kd_label, kh_label, skip_kd_loop, skip_kh_loop; Label f_overflow_label, no_f_overflow_label, d_h_f_overflow_label, t_overflow_label, no_t_overflow_label, b_overflow_label, no_b_overflow_label, back_overflow_label, no_back_overflow_label, d_h_back_overflow_label; int ch_block_all = jcp.ch_block * jcp.ic_block * jcp.oc_block; int shift_kernel_ptr = jcp.typesize_in * jcp.kw * ch_block_all; int shift_input_ptr = jcp.typesize_in * jcp.iw * jcp.ic_without_padding * jcp.ngroups; if (jcp.ndims == 5) { mov(aux_reg_ker_d, reg_ker); mov(aux_reg_inp_d, reg_inp); if (jcp.signed_input || jcp.with_input_zp) { //TODO: May be avoided when f_pad=0 and dd0 //TODO: Potential optimization by precomputing, when kd <<< od? mov(reg_ki, ptr[param1 + GET_OFF(f_overflow)]); cmp(reg_ki, 0); je(no_f_overflow_label, T_NEAR); L(f_overflow_label); { mov(aux_reg_ker, aux_reg_ker_d); mov(reg_kj, jcp.kh); L(d_h_f_overflow_label); { compute_ker(ur_w, pad_l, pad_r, last_ic_block_flag, true); add(aux_reg_ker, shift_kernel_ptr); dec(reg_kj); jne(d_h_f_overflow_label); } add(aux_reg_ker_d, shift_kernel_ptr * jcp.kh); dec(reg_ki); jne(f_overflow_label); } L(no_f_overflow_label); } mov(reg_ki, ptr[param1 + GET_OFF(kd_padding)]); if ((jcp.signed_input || jcp.with_input_zp) || (jcp.dilate_d >= jcp.id) || ((!jcp.signed_input && !jcp.with_input_zp) && (jcp.kd - 1) * (jcp.dilate_d + 1) < nstl::max(jcp.f_pad, jcp.back_pad))) { cmp(reg_ki, 0); je(skip_kd_loop, T_NEAR); } L(kd_label); mov(aux_reg_inp, aux_reg_inp_d); mov(aux_reg_ker, aux_reg_ker_d); } else { if (jcp.is_fused_conv) { mov(aux_reg_inp_buffer_ptr, reg_inp_buffer_ptr); } else { mov(aux_reg_inp, reg_inp); } mov(aux_reg_ker, reg_ker); } if ((jcp.signed_input || jcp.with_input_zp) && jcp.ndims > 3) { mov(reg_overflow, ptr[param1 + GET_OFF(t_overflow)]); cmp(reg_overflow, 0); je(no_t_overflow_label, T_NEAR); L(t_overflow_label); { compute_ker(ur_w, pad_l, pad_r, last_ic_block_flag, true); add(aux_reg_ker, shift_kernel_ptr); dec(reg_overflow); cmp(reg_overflow, 0); jg(t_overflow_label, T_NEAR); } L(no_t_overflow_label); } mov(reg_kj, ptr[param1 + GET_OFF(kh_padding)]); if ((jcp.signed_input || jcp.with_input_zp) || (jcp.dilate_h >= jcp.ih) || ((!jcp.signed_input && !jcp.with_input_zp) && (jcp.kh - 1) * (jcp.dilate_h + 1) < nstl::max(jcp.t_pad, jcp.b_pad))) { cmp(reg_kj, 0); je(skip_kh_loop, T_NEAR); } L(kh_label); { if (jcp.is_fused_conv) { mov(aux_reg_inp, ptr[aux_reg_inp_buffer_ptr]); add(aux_reg_inp, reg_inp); } compute_ker(ur_w, pad_l, pad_r, last_ic_block_flag, false); add(aux_reg_ker, shift_kernel_ptr); if (jcp.is_fused_conv) { add(aux_reg_inp_buffer_ptr, sizeof(void *)); } else { add(aux_reg_inp, shift_input_ptr * (jcp.dilate_h + 1)); } dec(reg_kj); cmp(reg_kj, 0); jg(kh_label, T_NEAR); } L(skip_kh_loop); if ((jcp.signed_input || jcp.with_input_zp) && jcp.ndims > 3) { mov(reg_overflow, ptr[param1 + GET_OFF(b_overflow)]); cmp(reg_overflow, 0); je(no_b_overflow_label, T_NEAR); L(b_overflow_label); { compute_ker(ur_w, pad_l, pad_r, last_ic_block_flag, true); add(aux_reg_ker, shift_kernel_ptr); dec(reg_overflow); cmp(reg_overflow, 0); jg(b_overflow_label, T_NEAR); } L(no_b_overflow_label); } if (jcp.ndims == 5) { add(aux_reg_inp_d, shift_input_ptr * jcp.ih * (jcp.dilate_d + 1)); add(aux_reg_ker_d, shift_kernel_ptr * jcp.kh); dec(reg_ki); jne(kd_label, T_NEAR); L(skip_kd_loop); if (jcp.signed_input || jcp.with_input_zp) { mov(reg_ki, ptr[param1 + GET_OFF(back_overflow)]); cmp(reg_ki, 0); je(no_back_overflow_label, T_NEAR); L(back_overflow_label); { mov(aux_reg_ker, aux_reg_ker_d); mov(reg_kj, jcp.kh); L(d_h_back_overflow_label); { compute_ker(ur_w, pad_l, pad_r, last_ic_block_flag, true); add(aux_reg_ker, shift_kernel_ptr); dec(reg_kj); jne(d_h_back_overflow_label); } add(aux_reg_ker_d, shift_kernel_ptr * jcp.kh); dec(reg_ki); jne(back_overflow_label); } L(no_back_overflow_label); } } } template void _jit_uni_x8s8s32x_fwd_kernel::icb_loop( int ur_w, int pad_l, int pad_r, bool is_last_sp_block) { prepare_output(ur_w); // IC loop Label icb_label; mov(reg_icb, jcp.nb_ic); if (jcp.with_input_zp) mov(reg_input_zp, ptr[param1 + GET_OFF(input_zp)]); L(icb_label); const bool do_icb_loop = jcp.is_depthwise ? jcp.nb_ch > jcp.nb_ch_blocking : jcp.nb_ic > 1; if (jcp.ngroups % jcp.ch_block != 0 || jcp.ic_without_padding != jcp.ic) { Label common_ker, end_ker; if (do_icb_loop) { if (jcp.is_depthwise) cmp(reg_oc_blocks, jcp.nb_ch - jcp.nb_ch_blocking); else cmp(reg_icb, 1); // The last IC block jne(common_ker, T_NEAR); } kh_loop(ur_w, pad_l, pad_r, is_last_sp_block ? last_sp_block : last_ic_block); if (do_icb_loop) { jmp(end_ker, T_NEAR); L(common_ker); kh_loop(ur_w, pad_l, pad_r, no_last_block); L(end_ker); } } else { kh_loop(ur_w, pad_l, pad_r, no_last_block); } // End of IC Loop if (do_icb_loop) { int inp_step = jcp.ic_block; int ker_step = jcp.kd * jcp.kh * jcp.kw * jcp.oc_block * jcp.ic_block; add(reg_inp, jcp.typesize_in * inp_step); add(reg_ker, jcp.typesize_in * ker_step); if (jcp.with_input_zp) add(reg_input_zp, sizeof(uint8_t) * inp_step); dec(reg_icb); cmp(reg_icb, 0); jg(icb_label, T_NEAR); sub(reg_inp, jcp.typesize_in * inp_step * jcp.nb_ic); sub(reg_ker, jcp.typesize_in * ker_step * jcp.nb_ic); } if (jcp.ngroups % jcp.ch_block != 0 || jcp.oc_without_padding != jcp.oc) { Label common_store, end_store; if (jcp.is_depthwise) cmp(reg_oc_blocks, jcp.nb_ch - jcp.nb_ch_blocking); else cmp(reg_oc_blocks, jcp.nb_oc - jcp.nb_oc_blocking); jne(common_store, T_NEAR); store_output(ur_w, true); // last oc block jmp(end_store, T_NEAR); L(common_store); store_output(ur_w, false); L(end_store); } else { store_output(ur_w, false); } } template void _jit_uni_x8s8s32x_fwd_kernel::generate() { const auto &p = attr_.post_ops_; for (int i = 0; i < p.len(); i++) { auto &post_op = p.entry_[i]; if (post_op.is_eltwise()) { eltwise_injectors.push_back(new jit_uni_eltwise_injector_f32( this, post_op.eltwise, true, eltwise_reserved )); } else if (post_op.is_depthwise()) { depthwise_injectors.push_back(new jit_uni_depthwise_injector_f32( this, post_op.depthwise.alg )); } else if (post_op.is_quantization()) { quantization_injectors.push_back(new jit_uni_quantization_injector_f32( this, post_op, vmm_d_weights, vmm_d_bias, reg_d_weights, reg_d_bias )); } } Label permute_index_table; int in_ic_shift = jcp.is_fused_conv ? jcp.dw_conv_buffer_oc : jcp.ic_without_padding * jcp.ngroups; const int urw_inp_stride = jcp.ur_w * jcp.stride_w; const int n_urw_l_pad = nstl::min(div_up(jcp.l_pad, urw_inp_stride), jcp.ow / jcp.ur_w); const int inp_shift_pad = nstl::max(0, jcp.typesize_in * (n_urw_l_pad * urw_inp_stride - jcp.l_pad) * in_ic_shift); int inp_shift = jcp.typesize_in * (jcp.ur_w * jcp.stride_w * in_ic_shift); int out_shift = jcp.typesize_out * (jcp.ur_w * jcp.oc_without_padding * jcp.ngroups); preamble(); if (jcp.is_depthwise) { int idx = 16 - jcp.max_regs_ur; if (!jcp.is_resrc_depthwise) vmm_dw_src = Vmm(--idx); if (jcp.ver != ver_vnni) vmm_dw_tmp = Vmm(--idx); if (jcp.signed_input || jcp.with_input_zp) { vmm_dw_shifted_zero = Vmm(--idx); --idx; // due to extra register used for compensations } assert(idx == 15 - ker_dw_reg_base_idx); } if (!jcp.is_depthwise && jcp.ver != ver_vnni) { auto vmm_one_128 = Xbyak::Xmm(vmm_one.getIdx()); mov(reg_scratch, 0x10001); uni_vmovq(vmm_one_128, reg_scratch); uni_vpbroadcastd(vmm_one, vmm_one_128); } if (jcp.is_fused_conv) { mov(reg_inp_buffer_ptr, ptr[param1 + GET_OFF(src)]); /* In case of fused depthwise convolution, `param.src` is not a pointer to input, instead it points to a buffer containing pointers to consecutive rows of input in format wc with c=jcp.dw_conv_buffer_oc. Example: [ptr_to_inp_row0, ptr_to_inp_row1, ptr_to_inp_row2]. Traverse the data as mov(reg_data, ptr[reg_input_buffer_ptr]) ... process row0 ... add(reg_input_buffer_ptr, sizeof(void*)) mov(reg_data, ptr[reg_input_buffer_ptr]) ... process row1 ... add(reg_input_buffer_ptr, sizeof(void*)) mov(reg_data, ptr[reg_input_buffer_ptr]) ... process row2 ... */ xor_(reg_inp, reg_inp); } else { mov(reg_inp, ptr[param1 + GET_OFF(src)]); } mov(reg_out, ptr[param1 + GET_OFF(dst)]); mov(reg_ker, ptr[param1 + GET_OFF(filt)]); if (jcp.ngroups % jcp.ch_block != 0 || jcp.oc_without_padding != jcp.oc) { mov(reg_oc_blocks, ptr[param1 + GET_OFF(oc_blocks)]); } const int extended_filter_size = calculate_extended_filter_size(jcp.kw, jcp.dilate_w); const int r_pad = nstl::max(0, jcp.r_pad); const int ow_with_no_rpad = 1 + (jcp.iw + jcp.l_pad + nstl::min(0, jcp.r_pad) - extended_filter_size) / jcp.stride_w; const int n_urw_per_ow_block = jcp.ow_block / jcp.ur_w; const int max_safe_iw = nstl::max( 0, jcp.iw - div_up(ic_sub_step, jcp.ic_without_padding)); const int max_safe_ow = jcp.ic_without_padding % ic_sub_step == 0 ? jcp.ow : (max_safe_iw + jcp.l_pad - extended_filter_size) / jcp.stride_w; Label middle_block_label, done_compute; std::vector